Skip to content

Commit 99e6268

Browse files
committed
cp: apply the finalize chmod without following a symlink
Both chmod sites in copy_file/copy_attributes decide whether to act by testing dest for being a symlink, but the test happens long before the chmod: in copy_file the lstat is taken before the copy starts, so the gap spans the whole file copy. A symlink swapped into dest during that gap redirected the mode change onto the link's target, off the destination tree. Measured with a tight unlink/symlink loop against a 20MB copy, 40 rounds each, an unrelated 0600 file taken to 0777: before 12/40 and 13/40 rounds hit after 0/40 GNU 9.10 2/40 and 3/40 Anchor the chmod to the parent directory fd with NoFollow, reusing DirFd::chmod_at. EOPNOTSUPP/ELOOP mean dest is now a symlink, which is exactly the "do nothing" case both guards already describe, so it maps to success. Note GNU is affected by the same class at a lower rate, so this is hardening beyond GNU rather than a compatibility fix. The remaining path-based steps in copy_attributes (timestamps, xattr, ACL, SELinux) are unchanged.
1 parent 0d02663 commit 99e6268

2 files changed

Lines changed: 79 additions & 2 deletions

File tree

‎src/uu/cp/src/cp.rs‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1881,7 +1881,7 @@ pub(crate) fn copy_attributes(
18811881
#[cfg(not(unix))]
18821882
let source_perms = source_metadata.permissions();
18831883

1884-
fs::set_permissions(dest, source_perms)
1884+
chmod_nofollow(dest, &source_perms)
18851885
.map_err(|e| CpError::IoErrContext(e, context.to_owned()))?;
18861886
// FIXME: Implement this for windows as well
18871887
#[cfg(feature = "feat_acl")]
@@ -2511,6 +2511,42 @@ fn calculate_dest_permissions(
25112511
///
25122512
/// The original permissions of `source` will be copied to `dest`
25132513
/// after a successful copy.
2514+
/// Apply `permissions` to `dest` without following a symlink at the final component.
2515+
///
2516+
/// Both callers test `dest` for being a symlink well before the chmod, so a symlink
2517+
/// swapped in inside that gap would redirect the mode onto the link's target.
2518+
/// `chmod(2)` cannot change a symlink's permissions, so `EOPNOTSUPP` here means
2519+
/// exactly the "do nothing" case the callers' guards describe.
2520+
#[cfg(unix)]
2521+
fn chmod_nofollow(dest: &Path, permissions: &Permissions) -> io::Result<()> {
2522+
use uucore::safe_traversal::{DirFd, SymlinkBehavior};
2523+
2524+
let (Some(parent), Some(name)) = (dest.parent(), dest.file_name()) else {
2525+
// `.`, `..` and `/` have no final component to anchor against. They are
2526+
// always directories and never a symlink themselves, so there is nothing
2527+
// to be redirected: chmod the directory through its own fd.
2528+
let dir_fd = DirFd::open(dest, SymlinkBehavior::NoFollow)?;
2529+
return dir_fd.fchmod(permissions.mode());
2530+
};
2531+
// `Path::parent()` yields "" for a bare filename.
2532+
let parent = if parent.as_os_str().is_empty() {
2533+
Path::new(".")
2534+
} else {
2535+
parent
2536+
};
2537+
2538+
let dir_fd = DirFd::open(parent, SymlinkBehavior::Follow)?;
2539+
match dir_fd.chmod_at(name, permissions.mode(), SymlinkBehavior::NoFollow) {
2540+
Err(e) if matches!(e.raw_os_error(), Some(libc::EOPNOTSUPP) | Some(libc::ELOOP)) => Ok(()),
2541+
other => other,
2542+
}
2543+
}
2544+
2545+
#[cfg(not(unix))]
2546+
fn chmod_nofollow(dest: &Path, permissions: &Permissions) -> io::Result<()> {
2547+
fs::set_permissions(dest, permissions.clone())
2548+
}
2549+
25142550
#[allow(clippy::cognitive_complexity, clippy::too_many_arguments)]
25152551
fn copy_file(
25162552
progress_bar: Option<&ProgressBar>,
@@ -2703,7 +2739,7 @@ fn copy_file(
27032739
//
27042740
// FWIW, the OS will throw an error later, on the write op, if
27052741
// the user does not have permission to write to the file.
2706-
fs::set_permissions(dest, dest_permissions).ok();
2742+
chmod_nofollow(dest, &dest_permissions).ok();
27072743
}
27082744

27092745
let copy_attributes_result = if options.dereference(source_in_command_line) {

‎tests/by-util/test_cp.rs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6695,6 +6695,47 @@ fn test_cp_parents_symlink_permissions_file() {
66956695
);
66966696
}
66976697

6698+
/// The finalize chmod goes through a parent-fd + `NoFollow` chmod rather than a
6699+
/// path-based `set_permissions`. Pin the modes it is responsible for, including
6700+
/// the setuid and read-only cases, so the no-follow path cannot silently stop
6701+
/// applying them.
6702+
#[test]
6703+
#[cfg(unix)]
6704+
fn test_cp_preserve_mode_via_nofollow_chmod() {
6705+
for mode in [0o644, 0o600, 0o755, 0o444, 0o4755] {
6706+
let scene = TestScenario::new(util_name!());
6707+
let at = &scene.fixtures;
6708+
at.write("src", "hi");
6709+
at.set_mode("src", mode);
6710+
6711+
scene.ucmd().args(&["-p", "src", "dst"]).succeeds();
6712+
6713+
assert_eq!(
6714+
at.metadata("dst").permissions().mode() & 0o7777,
6715+
mode,
6716+
"cp -p did not reproduce mode {mode:o}"
6717+
);
6718+
}
6719+
}
6720+
6721+
/// Overwriting an existing destination keeps the destination's mode, not the
6722+
/// source's — the other branch feeding the same chmod.
6723+
#[test]
6724+
#[cfg(unix)]
6725+
fn test_cp_existing_dest_keeps_its_mode() {
6726+
let scene = TestScenario::new(util_name!());
6727+
let at = &scene.fixtures;
6728+
at.write("src", "new");
6729+
at.set_mode("src", 0o600);
6730+
at.write("dst", "old");
6731+
at.set_mode("dst", 0o640);
6732+
6733+
scene.ucmd().args(&["src", "dst"]).succeeds();
6734+
6735+
assert_eq!(at.metadata("dst").permissions().mode() & 0o7777, 0o640);
6736+
assert_eq!(at.read("dst"), "new");
6737+
}
6738+
66986739
/// Test the behavior of preserving permissions of parents when copying through
66996740
/// a symlink when source is a dir.
67006741
#[test]

0 commit comments

Comments
 (0)