diff --git a/.github/workflows/CICD.yml b/.github/workflows/CICD.yml index 4bdf2a8ac36..806bbc8e8b0 100644 --- a/.github/workflows/CICD.yml +++ b/.github/workflows/CICD.yml @@ -980,7 +980,7 @@ jobs: - name: Install strace and libselinux headers (needed to build chcon) run: sudo apt-get update && sudo apt-get install -y strace libselinux1-dev - name: Build utilities with safe traversal - run: cargo build --profile=release-small -p uu_rm -p uu_chmod -p uu_chown -p uu_chgrp -p uu_mv -p uu_du -p uu_split -p uu_chcon + run: cargo build --profile=release-small -p uu_rm -p uu_chmod -p uu_chown -p uu_chgrp -p uu_mv -p uu_du -p uu_split -p uu_chcon -p uu_cp - name: Run safe traversal verification run: ./util/check-safe-traversal.sh diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index bb4c05c38f0..5a90d566d4b 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -4,7 +4,7 @@ // file that was distributed with this source code. // spell-checker:ignore (ToDO) copydir fiemap linkgs lstat nlink nlinks pathbuf reflink strs xattrs symlinked deduplicated advcpmv nushell IRWXG IRWXO IRWXU IRWXUGO IRWXU IRWXG IRWXO IRWXUGO sflag -// spell-checker:ignore RDONLY futimens utimensat unioned +// spell-checker:ignore utimensat unioned fchmodat use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; @@ -1829,6 +1829,7 @@ pub(crate) fn set_selinux_context(path: &Path, context: Option<&String>) -> Copy ))] fn copy_extended_attrs(source: &Path, dest: &Path, skip_selinux: bool) -> CopyResult<()> { use std::fs::File; + use std::os::unix::fs::OpenOptionsExt; use uucore::fsxattr::copy_xattrs; let metadata = fs::symlink_metadata(dest)?; @@ -1840,7 +1841,7 @@ fn copy_extended_attrs(source: &Path, dest: &Path, skip_selinux: bool) -> CopyRe if was_readonly { #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); - fs::set_permissions(dest, perms)?; + set_permissions_nofollow(dest, &perms)?; } // Perform the xattr copy and capture any potential error, @@ -1856,7 +1857,10 @@ fn copy_extended_attrs(source: &Path, dest: &Path, skip_selinux: bool) -> CopyRe // The source must be regular too: opening a FIFO here blocks until a // writer appears, and a device would have side effects on open. let source_file = File::open(source)?; - let dest_file = OpenOptions::new().write(true).open(dest)?; + let dest_file = OpenOptions::new() + .write(true) + .custom_flags(libc::O_NOFOLLOW) + .open(dest)?; copy_xattrs_fd(&source_file, &dest_file) } else { copy_xattrs(source, dest) @@ -1869,7 +1873,7 @@ fn copy_extended_attrs(source: &Path, dest: &Path, skip_selinux: bool) -> CopyRe if was_readonly { let mut revert_perms = fs::symlink_metadata(dest)?.permissions(); revert_perms.set_readonly(true); - fs::set_permissions(dest, revert_perms)?; + set_permissions_nofollow(dest, &revert_perms)?; } // If copying xattrs failed, propagate that error now with context. @@ -1968,11 +1972,8 @@ pub(crate) fn copy_attributes( }); handle_preserve(mode, || -> CopyResult<()> { - // The `chmod()` system call that underlies the - // `fs::set_permissions()` call is unable to change the - // permissions of a symbolic link. In that case, we just - // do nothing, since every symbolic link has the same - // permissions. + // Leave a symlink alone, like GNU: on FreeBSD and macOS a no-follow chmod + // would change the link's own mode, and the fallback elsewhere follows it. if !dest.is_symlink() { #[cfg(unix)] let source_perms = { @@ -1993,7 +1994,7 @@ pub(crate) fn copy_attributes( #[cfg(not(unix))] let source_perms = source_metadata.permissions(); - fs::set_permissions(dest, source_perms) + set_permissions_nofollow(dest, &source_perms) .map_err(|e| CpError::IoErrContext(e, context.to_owned()))?; // GNU `cp -p` preserves POSIX ACLs as part of mode. On Linux the // ACLs are stored as `system.posix_acl_*` xattrs; copy just those @@ -2023,23 +2024,12 @@ pub(crate) fn copy_attributes( handle_preserve(attributes.timestamps, || -> CopyResult<()> { let (atime, mtime) = source_times(&source_metadata, context)?; - // `set_file_times` opens the destination (O_RDONLY) before calling - // futimens; opening a FIFO or device with no peer blocks forever, and a - // socket cannot be opened at all. For symlinks and these special files - // use the path-based, no-follow variant, which sets the times via - // utimensat without opening. + // utimensat without following or opening: a symlink swapped in is not + // followed, and a FIFO or device with no peer would block on open. #[cfg(unix)] - let no_open = { - let ft = source_metadata.file_type(); - dest.is_symlink() - || ft.is_fifo() - || ft.is_socket() - || ft.is_char_device() - || ft.is_block_device() - }; + filetime::set_symlink_file_times(dest, atime, mtime)?; #[cfg(not(unix))] - let no_open = dest.is_symlink(); - if no_open { + if dest.is_symlink() { filetime::set_symlink_file_times(dest, atime, mtime)?; } else { filetime::set_file_times(dest, atime, mtime)?; @@ -2769,6 +2759,38 @@ fn calculate_dest_permissions( } } +/// Apply `permissions` to `dest` without following a symlink there, which callers checked +/// well before; finding one now is not an error. +#[cfg(all(unix, not(target_os = "redox")))] +fn set_permissions_nofollow(dest: &Path, permissions: &Permissions) -> io::Result<()> { + let Err(e) = uucore::safe_traversal::chmod_nofollow(dest, permissions.mode()) else { + return Ok(()); + }; + // A guard, not an or-pattern: ENOTSUP and EOPNOTSUPP are one value on Linux only. + let refused = matches!(e.raw_os_error(), + Some(c) if c == libc::EOPNOTSUPP || c == libc::ENOTSUP || c == libc::ELOOP); + if refused && fs::symlink_metadata(dest).is_ok_and(|md| md.file_type().is_symlink()) { + return Ok(()); + } + // Linux and Android refuse only a symlink, but fail with ENOENT without fchmodat2 or /proc. + // Elsewhere, refusing anything else means the platform can't chmod without following. + let cannot_nofollow = if cfg!(any(target_os = "linux", target_os = "android")) { + e.raw_os_error() == Some(libc::ENOENT) && !Path::new("/proc/self/fd").exists() + } else { + refused + }; + // Then do what cp did before. + if cannot_nofollow { + return fs::set_permissions(dest, permissions.clone()); + } + Err(e) +} + +#[cfg(any(not(unix), target_os = "redox"))] +fn set_permissions_nofollow(dest: &Path, permissions: &Permissions) -> io::Result<()> { + fs::set_permissions(dest, permissions.clone()) +} + /// Copy the a file from `source` to `dest`. `source` will be dereferenced if /// `options.dereference` is set to true. `dest` will be dereferenced only if /// the source was not a symlink. @@ -3003,7 +3025,7 @@ fn copy_file( // // FWIW, the OS will throw an error later, on the write op, if // the user does not have permission to write to the file. - fs::set_permissions(dest, dest_permissions).ok(); + set_permissions_nofollow(dest, &dest_permissions).ok(); } let copy_attributes_result = if options.dereference(source_in_command_line) { @@ -3036,6 +3058,19 @@ fn copy_file( ) }; + // A destination that was a symlink from the start was written through, so empty + // its target; otherwise refuse a symlink swapped in after the copy. + let empty_dest = || { + let mut open_options = OpenOptions::new(); + open_options.write(true).create(true).truncate(true); + #[cfg(unix)] + if !dest_is_symlink { + use std::os::unix::fs::OpenOptionsExt; + open_options.custom_flags(libc::O_NOFOLLOW); + } + open_options.open(dest) + }; + // Empty the destination when the SELinux security context cannot be // preserved, but keep the copied data when preserving other attributes // (e.g. xattrs) fails. @@ -3043,7 +3078,7 @@ fn copy_file( if matches!( err, CpError::SelinuxContext(_) | CpError::SelinuxContextIoErr(..) - ) && fs::File::create(dest).is_err() + ) && empty_dest().is_err() { // The permissions applied above may lack the write bit (e.g. a // read-only source), making the truncating open fail. Restore @@ -3052,9 +3087,9 @@ fn copy_file( #[cfg(unix)] if let Ok(metadata) = fs::symlink_metadata(dest) { let mode = metadata.permissions().mode(); - if fs::set_permissions(dest, Permissions::from_mode(mode | 0o200)).is_ok() { - fs::File::create(dest).ok(); - fs::set_permissions(dest, Permissions::from_mode(mode)).ok(); + if set_permissions_nofollow(dest, &Permissions::from_mode(mode | 0o200)).is_ok() { + empty_dest().ok(); + set_permissions_nofollow(dest, &Permissions::from_mode(mode)).ok(); } } } diff --git a/src/uucore/src/lib/features/safe_traversal.rs b/src/uucore/src/lib/features/safe_traversal.rs index 6dbe26f9a43..232c6cbc0ab 100644 --- a/src/uucore/src/lib/features/safe_traversal.rs +++ b/src/uucore/src/lib/features/safe_traversal.rs @@ -5,7 +5,7 @@ // spell-checker:ignore CLOEXEC RDONLY TOCTOU closedir dirp fdopendir fstatat openat REMOVEDIR unlinkat smallfile // spell-checker:ignore RAII dirfd fchownat fchown FchmodatFlags fchmodat fchmod mkdirat CREAT WRONLY ELOOP ENOTDIR EXCL EEXIST -// spell-checker:ignore atimensec mtimensec ctimensec opath chmods fakeroot fakechroot EOVERFLOW chowned chmoded +// spell-checker:ignore atimensec mtimensec ctimensec opath chmods fakeroot fakechroot EOVERFLOW chowned chmoded FDCWD // spell-checker:ignore LARGEFILE getdents atim mtim ctim statat // Safe directory traversal using openat() and related syscalls @@ -447,6 +447,22 @@ impl DirFd { let name_cstr = CString::new(name.as_bytes()).map_err(|_| SafeTraversalError::PathContainsNull)?; + Self::chmod_at_fd( + self.fd.as_fd(), + name_cstr.as_c_str(), + mode, + symlink_behavior, + ) + } + + /// Shared implementation behind [`DirFd::chmod_at`] and [`chmod_nofollow`], + /// which passes `AT_FDCWD` as `dirfd`. + fn chmod_at_fd( + dirfd: BorrowedFd<'_>, + name_cstr: &CStr, + mode: u32, + symlink_behavior: SymlinkBehavior, + ) -> io::Result<()> { let flags = if symlink_behavior.should_follow() { FchmodatFlags::FollowSymlink } else { @@ -461,8 +477,8 @@ impl DirFd { // fallback takes over instead. #[cfg_attr(target_os = "linux", allow(unused_variables))] let libc_err = match fchmodat( - &self.fd, - name_cstr.as_c_str(), + dirfd, + name_cstr, Mode::from_bits_truncate(mode as libc::mode_t), flags, ) { @@ -513,7 +529,7 @@ impl DirFd { let res = unsafe { libc::syscall( SYS_FCHMODAT2, - self.fd.as_raw_fd(), + dirfd.as_raw_fd(), name_cstr.as_ptr(), mode as libc::mode_t, libc::AT_SYMLINK_NOFOLLOW, @@ -535,7 +551,7 @@ impl DirFd { #[cfg(target_os = "linux")] { - self.chmod_at_via_opath(name_cstr.as_c_str(), mode) + Self::chmod_at_fd_via_opath(dirfd, name_cstr, mode) } #[cfg(not(target_os = "linux"))] { @@ -543,20 +559,21 @@ impl DirFd { } } - /// `O_PATH`-based fallback for chmod when fchmodat with `AT_SYMLINK_NOFOLLOW` - /// is not available (musl on kernel < 6.6). - /// - /// Opens the file with `O_PATH|O_NOFOLLOW` to get an fd without following - /// symlinks, then chmods via /proc/self/fd/{fd}. This avoids the TOCTOU - /// race because the fd pins the inode. - /// + /// Kernels without `fchmodat2`: chmod an `O_PATH|O_NOFOLLOW` fd through /proc, refusing + /// a symlink with `EOPNOTSUPP`. Without procfs this fails with `ENOENT`. #[cfg(target_os = "linux")] - fn chmod_at_via_opath(&self, name: &CStr, mode: u32) -> io::Result<()> { + fn chmod_at_fd_via_opath(dirfd: BorrowedFd<'_>, name: &CStr, mode: u32) -> io::Result<()> { // Same reason as in chmod_at: rustix's linux_raw backend would make // these raw syscalls, invisible to LD_PRELOAD wrappers. use std::os::unix::fs::PermissionsExt; - let fd = open_path_at(&self.fd, name, SymlinkBehavior::NoFollow)?; + let fd = open_path_at(dirfd, name, SymlinkBehavior::NoFollow)?; + + let stat = + nix::sys::stat::fstat(&fd).map_err(|e| io::Error::from_raw_os_error(e as i32))?; + if stat.st_mode & libc::S_IFMT == libc::S_IFLNK { + return Err(io::Error::from_raw_os_error(libc::EOPNOTSUPP)); + } // set_permissions goes through the libc chmod() symbol. fs::set_permissions(proc_fd_path(fd.as_fd()), fs::Permissions::from_mode(mode)) @@ -629,6 +646,20 @@ impl DirFd { } } +/// Change the mode of `path` without following a symlink at its final component: the +/// `AT_FDCWD` counterpart of [`DirFd::chmod_at`], so the parent is not opened first. +pub fn chmod_nofollow(path: &Path, mode: u32) -> io::Result<()> { + let path_cstr = CString::new(path.as_os_str().as_bytes()) + .map_err(|_| SafeTraversalError::PathContainsNull)?; + + DirFd::chmod_at_fd( + nix::fcntl::AT_FDCWD, + path_cstr.as_c_str(), + mode, + SymlinkBehavior::NoFollow, + ) +} + /// Find the deepest existing directory ancestor for a path. /// /// Returns the existing ancestor path and a list of components that need to be created. @@ -1718,6 +1749,94 @@ mod tests { assert!(target.join("subdir").exists()); } + /// `chmod_nofollow` is the finalize-chmod primitive: a symlink planted at the + /// path must never have its target's mode changed. + #[test] + fn test_chmod_nofollow_does_not_follow_a_symlink() { + use std::os::unix::fs::PermissionsExt; + + let temp_dir = TempDir::new().unwrap(); + let target = temp_dir.path().join("target"); + fs::write(&target, b"x").unwrap(); + fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap(); + symlink(&target, temp_dir.path().join("link")).unwrap(); + + let result = chmod_nofollow(&temp_dir.path().join("link"), 0o777); + + // Linux refuses a symlink; macOS changes the link's own mode instead. + if cfg!(target_os = "linux") { + assert_eq!(result.unwrap_err().raw_os_error(), Some(libc::EOPNOTSUPP)); + } + assert_eq!( + fs::metadata(&target).unwrap().permissions().mode() & 0o777, + 0o600, + "chmod_nofollow followed the symlink and changed its target" + ); + } + + #[test] + fn test_chmod_nofollow_changes_a_regular_file() { + use std::os::unix::fs::PermissionsExt; + + let temp_dir = TempDir::new().unwrap(); + let file = temp_dir.path().join("f"); + fs::write(&file, b"x").unwrap(); + + chmod_nofollow(&file, 0o640).unwrap(); + + assert_eq!( + fs::metadata(&file).unwrap().permissions().mode() & 0o777, + 0o640 + ); + } + + #[cfg(target_os = "linux")] + mod linux { + use super::*; + + /// The `O_PATH` fallback (kernels without `fchmodat2`) must refuse a + /// symlink rather than reach its target through `/proc/self/fd`. + #[test] + fn test_chmod_via_opath_refuses_a_symlink() { + use std::os::unix::fs::PermissionsExt; + + let temp_dir = TempDir::new().unwrap(); + let target = temp_dir.path().join("target"); + fs::write(&target, b"x").unwrap(); + fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap(); + symlink(&target, temp_dir.path().join("link")).unwrap(); + + let dir = DirFd::open(temp_dir.path(), SymlinkBehavior::Follow).unwrap(); + let err = DirFd::chmod_at_fd_via_opath(dir.as_fd(), c"link", 0o777).unwrap_err(); + + assert_eq!(err.raw_os_error(), Some(libc::EOPNOTSUPP)); + assert_eq!( + fs::metadata(&target).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + + #[test] + fn test_chmod_via_opath_changes_a_regular_file() { + use std::os::unix::fs::PermissionsExt; + + let temp_dir = TempDir::new().unwrap(); + fs::write(temp_dir.path().join("f"), b"x").unwrap(); + + let dir = DirFd::open(temp_dir.path(), SymlinkBehavior::Follow).unwrap(); + DirFd::chmod_at_fd_via_opath(dir.as_fd(), c"f", 0o640).unwrap(); + + assert_eq!( + fs::metadata(temp_dir.path().join("f")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o640 + ); + } + } + #[test] fn test_open_subdir_nofollow_fails_on_symlink() { let temp_dir = TempDir::new().unwrap(); diff --git a/util/check-safe-traversal.sh b/util/check-safe-traversal.sh index c02fb547527..7cba179d786 100755 --- a/util/check-safe-traversal.sh +++ b/util/check-safe-traversal.sh @@ -279,6 +279,28 @@ if have_util cp; then fi echo "✓ cp -P opens source with O_NOFOLLOW" rm -f test_cp_src test_cp_dst + + # After the copy, cp must not follow a symlink swapped in for the destination: + # every chmod, chown, utimensat or reopen of it by name must refuse to follow. + echo "cp_attr_test" > test_cp_src_attr + chmod 0444 test_cp_src_attr + if ! strace -f -e trace=open,openat,openat2,chmod,fchmodat,?fchmodat2,lchown,fchownat,utimensat \ + -o strace_cp_dest_nofollow.log $cp_cmd -a test_cp_src_attr test_cp_dst_attr; then + cat strace_cp_dest_nofollow.log + fail_immediately "cp -a under strace failed" + fi + if ! grep -q '"test_cp_dst_attr".*NOFOLLOW' strace_cp_dest_nofollow.log; then + cat strace_cp_dest_nofollow.log + fail_immediately "strace saw no no-follow call on the cp destination" + fi + following=$(grep '"test_cp_dst_attr"' strace_cp_dest_nofollow.log \ + | grep -vE 'O_CREAT.*, 0600\)|NOFOLLOW| lchown\(' || true) + if [ -n "$following" ]; then + cat strace_cp_dest_nofollow.log + fail_immediately "cp must not follow a symlink at the destination after the copy: $following" + fi + echo "✓ cp sets the destination's attributes without following a symlink" + rm -f test_cp_src_attr test_cp_dst_attr fi # split must harden its output open against TOCTOU target swaps (issue #11401 /