From 946232dd6d0129b852640700fff819f4d8826be4 Mon Sep 17 00:00:00 2001 From: Tirthraj Chavan Date: Tue, 17 Nov 2026 12:14:26 +0530 Subject: [PATCH 1/4] fix(migrate): close TOCTOU between target check and LMDB open (#1128) (cherry picked from commit 4bb8c4b7d90f41f8f602c7ec947f26f4f9d4a307) --- .changeset/migrate-target-toctou-pin.md | 4 + crates/nostream-cli/src/commands/migrate.rs | 111 ++++++++++++++++++-- 2 files changed, 105 insertions(+), 10 deletions(-) create mode 100644 .changeset/migrate-target-toctou-pin.md diff --git a/.changeset/migrate-target-toctou-pin.md b/.changeset/migrate-target-toctou-pin.md new file mode 100644 index 000000000..c72692dec --- /dev/null +++ b/.changeset/migrate-target-toctou-pin.md @@ -0,0 +1,4 @@ +--- +--- + +fix(migrate): close TOCTOU between target validation and store open via handle pinning (#1128) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 30d8e3bdd..aa2a0e6cc 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -106,8 +106,9 @@ pub fn run(options: MigrateOptions, out: &mut dyn Write) -> Result Result<(), CliError> { } } -/// Creates the target when it is missing, then judges what is on disk. -/// -/// `refuse_unsafe_target` can only judge what exists, and the source is dialled and probed -/// before the store opens, so a directory another user planted in that window would be adopted -/// by `create_dir_all` without a word. Creating it here, under the mode the store itself uses, -/// and checking again closes the window: after this call the target is a directory this process -/// made, or the run has ended. +/// A handle and device/inode pin that closes the TOCTOU window between target creation +/// and store open. Holding the file handle keeps the directory inode active, and verify +/// ensures the directory opened by LMDB is the exact inode judged by the security checks. +#[cfg(unix)] +#[derive(Debug)] +struct TargetPin { + _handle: fs::File, + dev: u64, + ino: u64, +} + +#[cfg(unix)] +impl TargetPin { + fn pin(path: &Path) -> Result { + let file = fs::File::open(path) + .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; + let metadata = file + .metadata() + .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; + Ok(Self { + _handle: file, + dev: metadata.dev(), + ino: metadata.ino(), + }) + } + + fn verify(&self, path: &Path) -> Result<(), CliError> { + let metadata = fs::symlink_metadata(path) + .map_err(|error| CliError::Migrate(format!("{}: {error}", path.display())))?; + if metadata.dev() != self.dev || metadata.ino() != self.ino { + return Err(CliError::Migrate(format!( + "{} was replaced between check and open: expected inode {} on device {}, found inode {} on device {}", + path.display(), + self.ino, + self.dev, + metadata.ino(), + metadata.dev() + ))); + } + Ok(()) + } +} + +#[cfg(not(unix))] +#[derive(Debug)] +struct TargetPin; + +#[cfg(not(unix))] +impl TargetPin { + fn pin(_path: &Path) -> Result { + Ok(Self) + } + + fn verify(&self, _path: &Path) -> Result<(), CliError> { + Ok(()) + } +} + +/// Creates the target when it is missing, judges what is on disk, and pins the directory +/// handle to close the TOCTOU window before the store opens. #[cfg(unix)] -fn create_target(options: &MigrateOptions) -> Result<(), CliError> { +fn create_target(options: &MigrateOptions) -> Result { fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(&options.target) .map_err(|error| CliError::Migrate(format!("{}: {error}", options.target.display())))?; - refuse_unsafe_target(options) + refuse_unsafe_target(options)?; + TargetPin::pin(&options.target) +} + +#[cfg(not(unix))] +fn create_target(options: &MigrateOptions) -> Result { + fs::create_dir_all(&options.target) + .map_err(|error| CliError::Migrate(format!("{}: {error}", options.target.display())))?; + + refuse_unsafe_target(options)?; + TargetPin::pin(&options.target) } /// The line and exit code a verify answers when the target has no manifest. @@ -1228,4 +1292,31 @@ mod tests { assert_eq!(limbs, [1, 0, 0, 0]); } + + /// A target swapped between the pre-open check and store open has a different inode or device; + /// `TargetPin::verify` detects the swap and refuses it. + #[test] + #[cfg(unix)] + #[allow(clippy::expect_used)] + fn a_target_swapped_between_check_and_open_is_refused() { + let temporary = tempfile::tempdir().expect("a temporary directory"); + let target = temporary.path().join("target"); + fs::create_dir(&target).expect("target is created"); + + let pin = TargetPin::pin(&target).expect("target is pinned"); + + // Swap the target directory with a newly created one (different inode) + let swapped = temporary.path().join("target_swapped"); + fs::create_dir(&swapped).expect("swapped is created"); + fs::remove_dir(&target).expect("original target removed"); + fs::rename(&swapped, &target).expect("swapped renamed to target"); + + let error = pin + .verify(&target) + .expect_err("a target replaced between check and open must be refused"); + assert!( + error.to_string().contains("replaced between check and open"), + "{error}" + ); + } } From 3e34703b99b9b25ade5acec3fd92859b2297789c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Tue, 17 Nov 2026 13:33:48 -0500 Subject: [PATCH 2/4] style(migrate): rustfmt the refusal assertion cargo fmt --all --check was red on the wrapped error.to_string() chain, which failed Rust Checks and the Windows CLI Check before either could run. Formatting only; no behaviour change. --- crates/nostream-cli/src/commands/migrate.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index aa2a0e6cc..208363c70 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -1315,7 +1315,9 @@ mod tests { .verify(&target) .expect_err("a target replaced between check and open must be refused"); assert!( - error.to_string().contains("replaced between check and open"), + error + .to_string() + .contains("replaced between check and open"), "{error}" ); } From eafa472b91c75359e32c239d94a628f392c9db99 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Tue, 17 Nov 2026 13:36:40 -0500 Subject: [PATCH 3/4] fix(migrate): refuse a target under an ancestor another user owns The pin narrowed the check-to-open window but could not close it: an ancestor's owner renames its entries whatever the bits say, so `--target /home/alice/store` run as root passes every mode check and alice can still move the target aside. Refuse an ancestor owned by neither the caller nor root unless its sticky bit makes the caller's own entry unrenamable by its owner. With that rule in place every permitted target's parent is caller- or root-owned, or sticky over a caller-owned entry, so no other local user can mount the swap and the pin's verify is a second line rather than the only one. Found by Greptile's P1 on #1161. --- crates/nostream-cli/src/commands/migrate.rs | 88 +++++++++++++++++++-- 1 file changed, 83 insertions(+), 5 deletions(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 208363c70..87e65285d 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -809,9 +809,9 @@ fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Re } // The directory that holds the target decides whether the target itself can be replaced. // Write permission on a directory is what allows an entry in it to be renamed away and - // another put in its place, and it takes no ownership of the entry to do it, so this is a - // mode question rather than a uid one. - refuse_swappable_ancestry(&options.target)?; + // another put in its place, and it takes no ownership of the entry to do it, so the mode is + // asked first; the holder's own owner is asked after it, since its owner needs no bits. + refuse_swappable_ancestry(&options.target, caller)?; // The data file itself, which `is_file()` and LMDB both follow: a link there would let the // copy read or write through it, and heed creates `lock.mdb` beside whatever it resolves to. @@ -856,8 +856,13 @@ fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Re /// the entry itself, so a group- or world-writable ancestor lets another user move this target /// aside and put their own there before the store opens. The sticky bit is the exception that /// makes `/tmp` usable: it refuses the rename of an entry its writer does not own. +/// +/// Ownership is the other half, and the mode cannot see it: the owner of an ancestor can rename +/// its entries whatever the bits say, so `--target /home/alice/store` run as root is swappable by +/// alice even though `/home/alice` is `0755`. An ancestor owned by neither the caller nor root is +/// therefore refused unless its sticky bit makes the caller's own entry unrenamable by its owner. #[cfg(unix)] -fn refuse_swappable_ancestry(target: &Path) -> Result<(), CliError> { +fn refuse_swappable_ancestry(target: &Path, caller: Option) -> Result<(), CliError> { let mut path = match target.parent() { Some(parent) if parent.as_os_str().is_empty() => PathBuf::from("."), Some(parent) => parent.to_path_buf(), @@ -870,7 +875,8 @@ fn refuse_swappable_ancestry(target: &Path) -> Result<(), CliError> { match fs::metadata(&path) { Ok(metadata) => { let mode = metadata.permissions().mode(); - if mode & 0o022 != 0 && mode & 0o1000 == 0 { + let sticky = mode & 0o1000 != 0; + if mode & 0o022 != 0 && !sticky { return Err(CliError::Migrate(format!( "{} is writable by group or other ({:04o}) and has no sticky bit: another \ user could replace {} before the store opens. Put the target under a \ @@ -880,6 +886,25 @@ fn refuse_swappable_ancestry(target: &Path) -> Result<(), CliError> { target.display() ))); } + // The mode's blind spot: an ancestor's owner renames its entries whatever the + // bits say, and root is the caller often enough that `/home/` is reached + // this way. A sticky ancestor is the exception, for the same reason it is above: + // the owner cannot rename an entry the caller owns. + if let Some(caller) = caller + && metadata.uid() != caller + && metadata.uid() != 0 + && !sticky + { + return Err(CliError::Migrate(format!( + "{} is owned by uid {}, neither the user running the copy ({caller}) nor \ + root, so its owner could replace {} before the store opens. Put the \ + target under a directory the caller or root owns, or one with the sticky \ + bit", + path.display(), + metadata.uid(), + target.display() + ))); + } } Err(error) if error.kind() == io::ErrorKind::NotFound => {} Err(error) => { @@ -1192,6 +1217,59 @@ mod tests { ); } + /// The mode's blind spot: an ancestor can be `0755` and still be another user's to reorder, + /// because its owner needs no write bits to rename an entry inside it. `--target + /// /home/alice/store` run as root is the shape — every ancestor passes the mode check and + /// alice can still move the target aside. Measured as if a different uid were running, since + /// a directory this process owns cannot be made to belong to another user without root. + #[cfg(unix)] + #[test] + #[allow(clippy::expect_used)] + fn a_target_under_an_ancestor_another_user_owns_is_refused() { + let temporary = tempfile::tempdir().expect("a temporary directory"); + let home = temporary.path().join("home"); + fs::create_dir(&home).expect("the ancestor is made"); + fs::set_permissions(&home, fs::Permissions::from_mode(0o755)) + .expect("the ancestor is left as a home directory is"); + let options = MigrateOptions { + target: home.join("target"), + batch_size: 1_000, + verify: false, + }; + + let owner = std::fs::symlink_metadata(&home) + .expect("the ancestor's metadata") + .uid(); + if owner == 0 { + // Running as root: every ancestor this test can make is root's own, and root is + // exempt by rule, so there is no foreign owner to measure against. + return; + } + // A uid that owns none of these ancestors and is not root, so the refusal is the + // ancestor's ownership rather than anything about the target. + let other = 0; + let error = refuse_unsafe_target_for(&options, Some(other)) + .expect_err("an ancestor owned by neither the caller nor root is refused"); + assert!( + error + .to_string() + .contains("neither the user running the copy"), + "{error}" + ); + + // The same shape with the sticky bit set cannot have the caller's entry renamed by its + // owner, so it is allowed — `/tmp` again, one level up. Every ancestor the caller does + // not own needs the bit for that to hold, the temporary directory included. + fs::set_permissions(temporary.path(), fs::Permissions::from_mode(0o1755)) + .expect("the temporary directory is made sticky"); + fs::set_permissions(&home, fs::Permissions::from_mode(0o1755)) + .expect("the sticky bit is set"); + assert!( + refuse_unsafe_target_for(&options, Some(other)).is_ok(), + "a sticky ancestor is the shape /tmp has, and is allowed" + ); + } + /// The check that runs before the source is dialled can only judge what exists, so the /// target is created and then judged. Both halves are needed: the creation gives the second /// check something to see, and the second check is what refuses a directory another user From 69132c451555e0121e8611c3e1edf9ab39ef6520 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Tue, 17 Nov 2026 13:41:55 -0500 Subject: [PATCH 4/4] fix(migrate): a sticky ancestor is no exemption for its owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous commit allowed a foreign-owned ancestor when its sticky bit was set, on the reasoning that sticky refuses the rename. It refuses it for other users, not for the directory's owner, who may rename an entry inside it — so alice could still mount the swap on /home/alice with 1755. The ownership rule now stands alone; /tmp stays usable because root owns it, not because it is sticky. --- crates/nostream-cli/src/commands/migrate.rs | 33 ++++++++++++--------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/crates/nostream-cli/src/commands/migrate.rs b/crates/nostream-cli/src/commands/migrate.rs index 87e65285d..85ece3a1a 100644 --- a/crates/nostream-cli/src/commands/migrate.rs +++ b/crates/nostream-cli/src/commands/migrate.rs @@ -860,7 +860,9 @@ fn refuse_unsafe_target_for(options: &MigrateOptions, caller: Option) -> Re /// Ownership is the other half, and the mode cannot see it: the owner of an ancestor can rename /// its entries whatever the bits say, so `--target /home/alice/store` run as root is swappable by /// alice even though `/home/alice` is `0755`. An ancestor owned by neither the caller nor root is -/// therefore refused unless its sticky bit makes the caller's own entry unrenamable by its owner. +/// refused outright. The sticky bit is no exemption here: it restrains other users, not the +/// directory's own owner, who may still rename an entry inside it — `/tmp` is safe because root +/// owns it, not because it is sticky. #[cfg(unix)] fn refuse_swappable_ancestry(target: &Path, caller: Option) -> Result<(), CliError> { let mut path = match target.parent() { @@ -888,18 +890,16 @@ fn refuse_swappable_ancestry(target: &Path, caller: Option) -> Result<(), C } // The mode's blind spot: an ancestor's owner renames its entries whatever the // bits say, and root is the caller often enough that `/home/` is reached - // this way. A sticky ancestor is the exception, for the same reason it is above: - // the owner cannot rename an entry the caller owns. + // this way. The sticky bit does not help — it restrains other users, not the + // directory's owner — so ownership is asked on its own. if let Some(caller) = caller && metadata.uid() != caller && metadata.uid() != 0 - && !sticky { return Err(CliError::Migrate(format!( "{} is owned by uid {}, neither the user running the copy ({caller}) nor \ root, so its owner could replace {} before the store opens. Put the \ - target under a directory the caller or root owns, or one with the sticky \ - bit", + target under a directory the caller or root owns", path.display(), metadata.uid(), target.display() @@ -1220,8 +1220,10 @@ mod tests { /// The mode's blind spot: an ancestor can be `0755` and still be another user's to reorder, /// because its owner needs no write bits to rename an entry inside it. `--target /// /home/alice/store` run as root is the shape — every ancestor passes the mode check and - /// alice can still move the target aside. Measured as if a different uid were running, since - /// a directory this process owns cannot be made to belong to another user without root. + /// alice can still move the target aside. The sticky bit is not an exemption for the same + /// reason: it restrains other users, not the stholder's own owner. Measured as if a different + /// uid were running, since a directory this process owns cannot be made to belong to another + /// user without root. #[cfg(unix)] #[test] #[allow(clippy::expect_used)] @@ -1257,16 +1259,19 @@ mod tests { "{error}" ); - // The same shape with the sticky bit set cannot have the caller's entry renamed by its - // owner, so it is allowed — `/tmp` again, one level up. Every ancestor the caller does - // not own needs the bit for that to hold, the temporary directory included. + // The sticky bit is not an exemption: a sticky directory restrains other users, not its + // own owner, who can still rename the target out of it. fs::set_permissions(temporary.path(), fs::Permissions::from_mode(0o1755)) .expect("the temporary directory is made sticky"); fs::set_permissions(&home, fs::Permissions::from_mode(0o1755)) - .expect("the sticky bit is set"); + .expect("the ancestor is made sticky"); + let error = refuse_unsafe_target_for(&options, Some(other)) + .expect_err("a sticky ancestor owned by another user is still refused"); assert!( - refuse_unsafe_target_for(&options, Some(other)).is_ok(), - "a sticky ancestor is the shape /tmp has, and is allowed" + error + .to_string() + .contains("neither the user running the copy"), + "{error}" ); }