diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index e020dda9c3..f48032c020 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -22,7 +22,7 @@ flate2 = { workspace = true } # file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds # no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "fs"] } +rustix = { workspace = true, features = ["std", "fs", "process"] } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 1e353f309f..3f5683841e 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -153,13 +153,19 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { - // A missing target is created by `create_target`, after the last check. An existing one is - // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. - if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { - return Err(io::ErrorKind::NotFound.into()); + // Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created + // only by `create_target`, after the last check. + #[cfg(test)] + if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) { + hook(); } - let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; - Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + // `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader. + let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY }; + let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?); + if write { + protected_regular(&dir, &file)?; + } + Ok(file) }; let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { @@ -265,6 +271,31 @@ pub fn write_atomic_checked( } } +/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest +/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular +/// file is refused, and so is a file in a sticky folder that others or the group can write to +/// when neither this process nor the folder's owner owns it. +#[cfg(unix)] +fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> { + let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?); + if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); + } + if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(()) +} + +/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is +/// refused to the user `me`: the folder is sticky, others or the group can write to it, and +/// neither `me` nor `folder_owner` owns the file. +#[cfg(unix)] +fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool { + use rustix::fs::Mode; + folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner +} + /// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is /// filled, right before it is put in place; a refusal then removes the temporary file and leaves /// `path` unchanged. @@ -784,6 +815,9 @@ thread_local! { /// Tests: [`write_atomic_checked`]'s folder refuses the rename. #[cfg(unix)] static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: run once right before [`write_atomic_checked`] opens its target for writing. + #[cfg(unix)] + static BEFORE_TARGET_OPEN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -1282,6 +1316,81 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A target removed after the write starts is not created again before the last check: when its + /// folder has moved outside by then, nothing is left there. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_no_target_removed_while_it_is_opened() { + let (d, root, outside) = checked_folders("checked-removed-target"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + let (inside, moved) = (root.join("inside"), outside.join("inside")); + let (from, to) = (inside.clone(), moved.clone()); + BEFORE_TARGET_OPEN.with(|h| { + *h.borrow_mut() = Some(Box::new(move || { + std::fs::remove_file(from.join("doc.txt")).unwrap(); + std::fs::rename(&from, &to).unwrap(); + })) + }); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()); + assert!(r.is_err(), "{r:?}"); + assert!(!moved.join("doc.txt").exists(), "the removed target was created again"); + assert!(!inside.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// An existing regular file this process owns passes the check. + #[cfg(unix)] + #[test] + fn protected_regular_allows_a_file_this_process_owns() { + let d = std::fs::canonicalize(dir("protected-regular")).unwrap(); + std::fs::write(d.join("doc.txt"), b"old").unwrap(); + let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into(); + let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap(); + protected_regular(&folder, &file).unwrap(); + let _ = std::fs::remove_dir_all(d); + } + + /// A FIFO at the name is not written into when the rename is refused: without a reader the + /// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not + /// return), and with a reader nothing reaches it. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_does_not_write_into_a_fifo_at_its_name() { + use rustix::fs::{Mode, OFlags}; + use std::io::Read as _; + let (d, root, _) = checked_folders("checked-fifo"); + let path = root.join("inside/doc.txt"); + rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + RENAME_REFUSED.with(|c| c.set(true)); + let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap()); + let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}"); + let mut got = [0u8; 8]; + assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO"); + let _ = std::fs::remove_dir_all(d); + } + + /// A file in a sticky folder that others or the group can write to is refused when neither this + /// user nor the folder's owner owns it. + #[cfg(unix)] + #[test] + fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() { + let (me, folder_owner, other) = (1000, 0, 2000); + let mode = rustix::fs::Mode::from_raw_mode; + assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me)); + assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me)); + } + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. #[cfg(unix)] #[test]