From 4ab8d3868f6a2dc0d6c6bb3401ed2819362b31b9 Mon Sep 17 00:00:00 2001 From: Yerkebulan Tulibergenov Date: Sat, 17 Jun 2023 20:28:38 -0700 Subject: [PATCH] don't allow custom build script path to escape package root --- src/cargo/util/toml/mod.rs | 33 +++++++++++++++++++++++++++------ src/cargo/util/toml/targets.rs | 2 +- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs index 1cc32dee8f0..2e39de53f09 100644 --- a/src/cargo/util/toml/mod.rs +++ b/src/cargo/util/toml/mod.rs @@ -2888,20 +2888,41 @@ impl TomlManifest { &self, build: &Option, package_root: &Path, - ) -> Option { + ) -> CargoResult> { let build_rs = package_root.join("build.rs"); match *build { // Explicitly no build script. - Some(StringOrBool::Bool(false)) => None, - Some(StringOrBool::Bool(true)) => Some(build_rs), - Some(StringOrBool::String(ref s)) => Some(PathBuf::from(s)), + Some(StringOrBool::Bool(false)) => Ok(None), + Some(StringOrBool::Bool(true)) => Ok(Some(build_rs)), + Some(StringOrBool::String(ref s)) => { + let custom_build = PathBuf::from(s); + + // Check if custom build path escapes the package root. If so, bail. + // Can we assume that package_root is absolute path? + if custom_build.is_absolute() { + bail!("custom build script path cannot be absolute"); + } + if custom_build.is_relative() { + let custom_build_path = package_root.join(&custom_build); + let custom_build_path = custom_build_path.canonicalize(); + if custom_build_path.is_err() { + bail!("cannot find path to custom build script"); + } + let custom_build_path = custom_build_path.unwrap(); + if !custom_build_path.starts_with(package_root) { + bail!("custom build script has to be inside package directory"); + } + } + + Ok(Some(custom_build)) + } None => { // If there is a `build.rs` file next to the `Cargo.toml`, assume it is // a build script. if build_rs.is_file() { - Some(build_rs) + Ok(Some(build_rs)) } else { - None + Ok(None) } } } diff --git a/src/cargo/util/toml/targets.rs b/src/cargo/util/toml/targets.rs index a7e30c61bce..7e92c3f7116 100644 --- a/src/cargo/util/toml/targets.rs +++ b/src/cargo/util/toml/targets.rs @@ -105,7 +105,7 @@ pub fn targets( )?); // processing the custom build script - if let Some(custom_build) = manifest.maybe_custom_build(custom_build, package_root) { + if let Some(custom_build) = manifest.maybe_custom_build(custom_build, package_root)? { if metabuild.is_some() { anyhow::bail!("cannot specify both `metabuild` and `build`"); }