Skip to content

Commit aa9b9d9

Browse files
committed
cp: only apply setuid/setgid bits after setting the ownership
When creating the destination, cp chmod'ed it to the source mode, setuid/setgid included, before copy_attributes() changed its owner. With -p/-a the copy was briefly (or, if the chown failed, permanently) a setuid/setgid file still owned by the user running cp. Like GNU, clear these bits in the initial mode; when the mode is preserved, copy_attributes() sets them again after the chown.
1 parent 1614fa9 commit aa9b9d9

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2757,8 +2757,10 @@ fn calculate_dest_permissions(
27572757
let mut permissions = source_metadata.permissions();
27582758
let mode = handle_no_preserve_mode(options, permissions.mode());
27592759

2760-
// Apply umask
2761-
let mode = mode & !uucore::mode::get_umask();
2760+
// Apply umask. Like GNU, never put the setuid/setgid bits on the
2761+
// copy before its ownership is set: when the mode is preserved,
2762+
// copy_attributes() restores them after the chown.
2763+
let mode = mode & !0o6000 & !uucore::mode::get_umask();
27622764
permissions.set_mode(mode);
27632765
permissions
27642766
}

‎tests/by-util/test_cp.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9391,6 +9391,44 @@ fn test_cp_preserve_setuid_when_chown_succeeds() {
93919391
);
93929392
}
93939393

9394+
// The setuid/setgid bits are only applied once the ownership has been set
9395+
// (like GNU), so a mode-preserving copy must still end up with them, while a
9396+
// plain copy drops them.
9397+
#[uutests::wasi_ignore(NoPermissionBits)]
9398+
#[test]
9399+
#[cfg(unix)]
9400+
fn test_cp_setuid_setgid_applied_after_ownership() {
9401+
let scene = TestScenario::new(util_name!());
9402+
let at = &scene.fixtures;
9403+
at.touch("src");
9404+
at.set_mode("src", 0o6755);
9405+
9406+
for (i, (args, expected)) in [
9407+
(&[][..], 0o755),
9408+
(&["-p"][..], 0o6755),
9409+
(&["-a"][..], 0o6755),
9410+
(&["--preserve=mode"][..], 0o6755),
9411+
(&["--preserve=mode,ownership"][..], 0o6755),
9412+
]
9413+
.into_iter()
9414+
.enumerate()
9415+
{
9416+
let dst = format!("dst{i}");
9417+
scene
9418+
.ucmd()
9419+
.umask(0o022)
9420+
.args(args)
9421+
.arg("src")
9422+
.arg(&dst)
9423+
.succeeds();
9424+
assert_eq!(
9425+
at.metadata(&dst).mode() & 0o7777,
9426+
expected,
9427+
"cp {args:?} src {dst}"
9428+
);
9429+
}
9430+
}
9431+
93949432
#[uutests::wasi_ignore(NonUtf8ArgsUnsupported)]
93959433
#[test]
93969434
#[cfg(all(unix, not(target_vendor = "apple")))]

0 commit comments

Comments
 (0)