Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions crates/templates/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ pub enum SkippedReason {
AlreadyExists,
/// The template was skipped because its manifest was missing or invalid.
InvalidManifest(String),
/// The template was skipped because it contained suspicious content.
SafetyValidation(String),
/// The template was removed from the source but could not be removed locally.
CouldNotRemove,
}
Expand Down Expand Up @@ -256,6 +258,13 @@ impl TemplateManager {
};
let id = template.id();

if let Err(e) = validate_safe_to_install(source_dir, &template) {
return Ok(InstallationResult::Skipped(
id.to_string(),
SkippedReason::SafetyValidation(e.to_string()),
));
}

let message = format!("Installing template {id}...");
reporter.report(&message);

Expand Down Expand Up @@ -477,6 +486,20 @@ async fn copy_template_into(
load_template_from(id, dest_dir)
}

fn validate_safe_to_install(source_dir: &Path, template: &Template) -> anyhow::Result<()> {
let walk = walkdir::WalkDir::new(source_dir).follow_links(false);

for entry in walk {
if entry.is_ok_and(|e| e.path_is_symlink()) {
anyhow::bail!("template contains a symlink");
}
}

template.validate_safe_to_run()?;

Ok(())
}

fn write_install_record(dest_dir: &Path, source: &TemplateSource) {
let layout = TemplateLayout::new(dest_dir);
let install_record_path = layout.installation_record_file();
Expand Down Expand Up @@ -902,10 +925,13 @@ mod tests {

let install_results = manager.install_test_data_templates().await;

assert_eq!(1, install_results.skipped.len());
assert!(!install_results.skipped.is_empty());

let (id, reason) = &install_results.skipped[0];
assert_eq!("testing-custom-filter", id);
let (_, reason) = &install_results
.skipped
.iter()
.find(|(id, _)| id == "testing-custom-filter")
.expect("'testing-custom-filter' should have been skipped'");
let SkippedReason::InvalidManifest(message) = reason else {
panic!("skip reason should be InvalidManifest"); // clippy dislikes assert!(false...)
};
Expand Down
10 changes: 8 additions & 2 deletions crates/templates/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,7 @@ impl Run {
&self,
interaction: impl InteractionStrategy,
) -> anyhow::Result<Option<TemplateRenderer>> {
self.validate_version()?;
self.validate_add_component_manifest_version()?;
self.validate_template()?;

// TODO: rationalise `path` and `dir`
let to = self.generation_target_dir();
Expand Down Expand Up @@ -248,6 +247,13 @@ impl Run {
}
}

fn validate_template(&self) -> anyhow::Result<()> {
self.template.validate_safe_to_run()?;
self.validate_version()?;
self.validate_add_component_manifest_version()?;
Ok(())
}

fn validate_add_component_manifest_version(&self) -> anyhow::Result<()> {
match &self.options.variant {
TemplateVariantInfo::NewApplication => Ok(()),
Expand Down
44 changes: 44 additions & 0 deletions crates/templates/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,26 @@ impl Template {
}
}

pub(crate) fn validate_safe_to_run(&self) -> anyhow::Result<()> {
for variant in self.variants.values() {
for snippet_path in variant.snippets.values() {
let snippet_path = PathBuf::from(snippet_path);
if snippet_path.is_absolute() {
anyhow::bail!("invalid template: snippet paths must be relative");
}
for component in snippet_path.components() {
if !matches!(component, std::path::Component::Normal(_)) {
anyhow::bail!(
"invalid template: snippet path attempts directory traversal"
);
}
}
}
}

Ok(())
}

// TODO: we should resolve this once at the start of Run and then use that forever
fn variant(&self, variant_info: &TemplateVariantInfo) -> Option<TemplateVariant> {
let kind = variant_info.kind();
Expand Down Expand Up @@ -770,4 +790,28 @@ mod test {
assert!(!add_variant.snippets.contains_key("s1"));
assert!(add_variant.snippets.contains_key("s2"));
}

fn test_data_root() -> PathBuf {
let crate_dir = env!("CARGO_MANIFEST_DIR");
PathBuf::from(crate_dir).join("tests")
}

#[test]
fn template_is_unsafe_if_it_attempts_directory_traversal() {
let test_dir = test_data_root().join("templates");
for malign_dir in &["evil-absolute", "evil-traverses"] {
let template_dir = test_dir.join(malign_dir);
let template = Template::load_from(&TemplateLayout::new(template_dir)).unwrap();
template.validate_safe_to_run().expect_err(&format!(
"'{malign_dir}' should have been judged unsafe but was not"
));
}
for non_malign_dir in &["add-only-redirect", "partials"] {
let template_dir = test_dir.join(non_malign_dir);
let template = Template::load_from(&TemplateLayout::new(template_dir)).unwrap();
template.validate_safe_to_run().unwrap_or_else(|_| {
panic!("'{non_malign_dir}' should have been judged safe but was not")
}); // I know but clippy gets mad if I use expect
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
manifest_version = "1"
id = "evil-absolute"
description = "Tests absolute path in snippets is caught"
trigger_type = "http"

[add_component]
[add_component.snippets]
component = "/home/victim/secrets/secret.txt"
variables = "variables.txt"
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
manifest_version = "1"
id = "evil-traverses"
description = "Tests path traversal in snippets is caught"
trigger_type = "http"

[add_component]
[add_component.snippets]
component = "wibble/../../../secrets/secret.txt"
1 change: 1 addition & 0 deletions src/commands/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ fn skipped_reason_text(reason: &SkippedReason) -> String {
match reason {
SkippedReason::AlreadyExists => "Already exists".to_owned(),
SkippedReason::InvalidManifest(msg) => format!("Template load error: {msg}"),
SkippedReason::SafetyValidation(msg) => format!("Invalid template: {msg}"),
SkippedReason::CouldNotRemove => {
"No longer exists in source, but could not uninstall".to_owned()
}
Expand Down
Loading