diff --git a/src/common/validation.rs b/src/common/validation.rs index 1dbc141db16..4813afbf623 100644 --- a/src/common/validation.rs +++ b/src/common/validation.rs @@ -110,7 +110,7 @@ pub fn binary_path(args: &mut impl Iterator) -> PathBuf { // no fallback for empty args. current_exe() (/proc/self/exe) is valid only for hardlinks } /// Get actual binary path from kernel, not argv0, to prevent `env -a` from bypassing -/// AppArmor, SELinux policies on hard-linked binaries +/// AppArmor (path-based) policies on hard-linked binaries #[cfg(all( any( target_os = "linux", @@ -119,31 +119,30 @@ pub fn binary_path(args: &mut impl Iterator) -> PathBuf { not(target_env = "musl") ))] pub fn binary_path(args: &mut impl Iterator) -> PathBuf { - use std::fs::File; - use std::io::Read; use std::os::unix::ffi::OsStrExt; let execfn = rustix::param::linux_execfn(); let execfn_bytes = execfn.to_bytes(); let exec_path = Path::new(OsStr::from_bytes(execfn_bytes)); let argv0 = args.next().unwrap(); - let mut shebang_buf = [0u8; 2]; // When the names match, keep the kernel path: argv0 may lack the directory after PATH lookup. + // execfn_bytes is path to script.sh, and argv0 is interpreter with env -a fake script.sh if execfn_bytes.rsplit(|&b| b == b'/').next() == argv0.as_bytes().rsplit(|&b| b == b'/').next() { - return exec_path.into(); - } - // exec_path is wrong when called from a shebang, or via fexecve/execveat: - // the kernel reports /dev/fd/* and memfd_create/glibc's fallback /proc/self/fd/* - if execfn_bytes.starts_with(b"/proc/") - || execfn_bytes.starts_with(b"/dev/fd/") - || (File::open(Path::new(exec_path)) - .and_then(|mut f| f.read_exact(&mut shebang_buf)) - .is_ok() - && &shebang_buf == b"#!") - { - argv0.into() - } else { exec_path.into() + // `readlink(2)` fast-path needs mounted /proc and coreutils should be installed as hardlinks which is default of `GNUmakefile`. + // only owner (root at the most cases) of the binary can cause race condition. + } else if let Some(bin) = std::env::current_exe().ok().filter(|b| { + // memfd depends on argv0 + !b.as_os_str().as_encoded_bytes().starts_with(b"/memfd:") + && !b + .file_stem() + // No worth to optimize *box just for busybox test suite + .is_some_and(|s| s.as_bytes().ends_with(b"utils")) + }) { + bin + } else { + // there is no safe-traversal way to check that myself is called via shebang + argv0.into() } } /// Extracts the binary name from a path diff --git a/tests/test_util_name.rs b/tests/test_util_name.rs index 114feae15d9..855b8e59092 100644 --- a/tests/test_util_name.rs +++ b/tests/test_util_name.rs @@ -28,21 +28,48 @@ fn init() { not(target_env = "musl") ))] fn binary_name_protection() { + use std::fs; let ts = TestScenario::new("env"); - let bin = ts.bin_path.clone(); + let real_bin = ts.fixtures.plus("hard-env"); + if fs::hard_link(&ts.bin_path, &real_bin).is_err() { + fs::copy(&ts.bin_path, &real_bin).unwrap(); + } ts.ucmd() .arg("-a") .arg("hijacked") - .arg(&bin) + .arg(&real_bin) .arg("--version") .succeeds() .stdout_contains("coreutils"); } +#[test] +#[cfg(all(feature = "env", target_os = "linux", target_env = "gnu"))] +fn binary_name_shebang() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + let ts = TestScenario::new("env"); + let at = &ts.fixtures; + let real_bin = at.plus("env"); + // let symlink = at.plus("false"); //todo: use this when was merged + let script = at.plus("script.sh"); + if fs::hard_link(&ts.bin_path, &real_bin).is_err() { + fs::copy(&ts.bin_path, &real_bin).unwrap(); + } + // symlink_file(&ts.bin_path, &symlink).unwrap(); + at.write(&script, &format!("#!{} echo\n", real_bin.display())); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let output = std::process::Command::new(&script).output().unwrap(); + assert!(output.status.success()); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("/script.sh")); +} + // missing /proc/self/fd on Android? #[test] #[cfg(all(feature = "true", target_os = "linux", target_env = "gnu"))] -fn binary_name_execfn_fallback() { +fn binary_name_memfd() { use std::os::{fd::AsRawFd, unix::process::CommandExt}; use std::process::Command; let ts = TestScenario::new("true"); @@ -53,20 +80,15 @@ fn binary_name_execfn_fallback() { let raw_fd = file.as_raw_fd(); // memfd has AT_EXECFN as below. Fallback to argv[0] - let res1 = Command::new(format!("/proc/self/fd/{raw_fd}")) - .arg0("true") - .output() - .unwrap() - .status - .success(); - // fexecve uses /dev/fd which is symlink to /proc/self/fd/N - let res2 = Command::new(format!("/dev/fd/{raw_fd}")) + let res = Command::new(format!("/proc/self/fd/{raw_fd}")) .arg0("true") .output() .unwrap() .status .success(); - assert!(res1 && res2); + assert!(res); + // fexecve has AT_EXECFN=/dev/fd or /proc/self/fd/N too, but /proc/self/exe might point + // the binary (installed as hardlink) we want to exec. } #[rstest::rstest]