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
4 changes: 2 additions & 2 deletions docs/src/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ Our `coreutils` calls utility by `coreutils utility-name` and has `--list` to ru
Our `coreutils` is called as `utility-name` if its binary name ends with `utility-name` to support prefixed names.
Longer name is prioritized e.g. `sum` with the prefix `ck` is called as `cksum`.

On Linux with glibc, a symlink alias with invalid name such as
`dummy -> ... -> true` selects `true` when `true` is a hardlink or copy of `coreutils`.
On Linux with glibc, hardlink (or copy) of `coreutils` mimics individual binaries:
the symlink chain such as `false -> ... -> true` selects `true` if `false` is not on `/usr/bin/`.

## `base32/base64/basenc`

Expand Down
15 changes: 1 addition & 14 deletions src/bin/coreutils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,6 @@ fn matched_utility<T>(name: &str, utils: &UtilityMap<T>) -> Option<&'static str>
.copied()
}

fn utility_from_real<T>(utils: &UtilityMap<T>) -> Option<&'static str> {
// resolve symlink chain to match with (path-based) AppArmor profile.
// Depending on /proc/self/exe is fine since this is an extension.
// GNUmakefile installs hardlinks by default.
let target = std::env::current_exe().ok()?;
let name = validation::name(&target)?;
matched_utility(name, utils)
}

fn usage<T>(utils: &UtilityMap<T>, name: &str) {
let display_list = utils.keys().copied().join(", ");
let width = cmp::min(textwrap::termwidth(), 100) - 8; // (opinion/heuristic) max 100 chars wide with 4 character side indentions
Expand Down Expand Up @@ -67,7 +58,7 @@ fn main() -> ExitCode {
let utils = util_map();
let mut args = uucore::args_os().peekable();

let binary = validation::binary_path(&mut args);
let binary = validation::binary_path(args.next().unwrap());
let Some(binary_as_util) = validation::name(&binary) else {
usage(&utils, "<unknown binary name>");
return ExitCode::SUCCESS;
Expand Down Expand Up @@ -95,10 +86,6 @@ fn main() -> ExitCode {
// todo: Remove support of "*box" from binary
uucore::set_utility_is_second_arg();
args.next()
} else if cfg!(all(target_os = "linux", target_env = "gnu"))
&& let Some(util) = utility_from_real(&utils)
{
Some(OsString::from(util))
} else {
return validation::not_found(&OsString::from(binary_as_util));
};
Expand Down
45 changes: 24 additions & 21 deletions src/common/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ fn get_canonical_util_name(util_name: &str) -> &str {
)),
target_env = "musl"
))]
pub fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
PathBuf::from(args.next().unwrap())
pub fn binary_path(argv0: OsString) -> PathBuf {
PathBuf::from(argv0)
// 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
Expand All @@ -120,32 +120,35 @@ pub fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
),
not(target_env = "musl")
))]
pub fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
use std::fs::File;
use std::io::Read;
pub fn binary_path(argv0: OsString) -> PathBuf {
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];
// don't pay `readlink(2)` when called via PATH which is the most common usecase.
// package should not contain dummy `/usr/bin/false`.
if execfn_bytes.starts_with(b"/usr/bin")
// When the names match, keep the kernel path: argv0 may lack the directory after PATH lookup.
if execfn_bytes.rsplit(|&b| b == b'/').next() == argv0.as_bytes().rsplit(|&b| b == b'/').next()
// execfn_bytes is path to script.sh, and argv0 is interpreter with env -a fake script.sh
&& 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()
// The hardlink `false` mimics individual `false` binary: `fake-true` -> `false` selects `false`.
// This depends on /proc/self/exe.
// 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| {
// TODO: Use `coreutils.rs`'s `matched_utility` for both of /proc/self/exe and argv0.
// Then memfd, busybox, coreutils, packaging errors, and fake /proc under MV are covered.
!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
Expand Down
17 changes: 11 additions & 6 deletions tests/test_util_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@ 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");
Expand Down Expand Up @@ -357,6 +361,7 @@ fn test_sorted_utils() {
assert!(out.lines().filter(|s| !s.is_empty()).is_sorted());
}

// even false is enabled, false -> ... -> echo mimics individual echo binary if echo is installed as hardlink
#[cfg(all(target_os = "linux", target_env = "gnu", feature = "echo"))]
#[rstest::rstest]
#[case::relative_target_absolute_alias(false, false, false, true)]
Expand Down Expand Up @@ -388,16 +393,16 @@ fn test_utility_alias_symlink_chain(
} else {
std::path::PathBuf::from("bin/echo")
};
symlink_file(target, at.plus("dummy")).unwrap();
symlink_file(target, at.plus("not-false")).unwrap();
let binary = if path_lookup {
std::path::PathBuf::from("dummy")
std::path::PathBuf::from("not-false")
} else {
at.plus("dummy")
at.plus("not-false")
};
let mut command = Command::new(binary);
command.args(["hello", "world"]).current_dir(at.plus("bin"));
if unset_path {
command.arg0("dummy").env_remove("PATH");
command.arg0("not-false").env_remove("PATH");
} else {
command.env("PATH", at.root_dir_resolved());
}
Expand Down
Loading