diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e5cd625..f5c5d771 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 not a usage error. `newusers` refuses to create a group over 32 characters, as upstream does (#391) +- `userdel -r` keeps a mail spool that the user does not own, or a symlink to a + file they do not own, says `SPOOL not owned by LOGIN, not removing` and exits 12 + after removing the home, as upstream does; `-f` removes it. It unlinked the + spool whoever owned it (#400) + - `userdel -r` says `LOGIN mail spool (PATH) not found` and `LOGIN home directory (PATH) not found` on standard error when either is missing, mail spool first, as upstream does, with exit 0. It said nothing (#392) diff --git a/docs/man/userdel.8.md b/docs/man/userdel.8.md index 7f495ab0..f0a2a34f 100644 --- a/docs/man/userdel.8.md +++ b/docs/man/userdel.8.md @@ -20,7 +20,8 @@ is also removed from membership lists in /etc/group and /etc/gshadow. **-f**, **--force** : With **-r**, remove the home directory even if it is not owned by the user or - is shared with another account. A user that does not exist is still exit + is shared with another account, and the mail spool even if it is not owned by + the user. A user that does not exist is still exit status 6. **-P**, **--prefix** *PREFIX_DIR* @@ -37,6 +38,11 @@ is also removed from membership lists in /etc/group and /etc/gshadow. (PATH) not found* and *LOGIN home directory (PATH) not found* are printed on standard error, in that order, and the exit status is unchanged. + A mail spool the user does not own is kept unless **-f** is given: *SPOOL not + owned by LOGIN, not removing* is printed on standard error, the home is still + removed, and the exit status is 12. A spool that is a symbolic link is judged + by the file it points to; the link is what is removed, never that file. + **-R**, **--root** *CHROOT_DIR* : Apply changes in the *CHROOT_DIR* directory. diff --git a/src/uu/userdel/src/userdel.rs b/src/uu/userdel/src/userdel.rs index eca8a4f2..78b8dd62 100644 --- a/src/uu/userdel/src/userdel.rs +++ b/src/uu/userdel/src/userdel.rs @@ -16,6 +16,7 @@ use clap::{Arg, ArgAction, Command}; use uucore::error::{UError, UResult}; use shadow_core::audit; +use shadow_core::cli::AlreadyPrinted; use shadow_core::error::ShadowError; use shadow_core::group::GroupEntry; use shadow_core::gshadow::GshadowEntry; @@ -201,8 +202,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { // Restore signals before potentially long-running home removal. drop(signals); - // 7. Optionally remove the mail spool and home directory. - if remove_home { + // 7. Optionally remove the mail spool and home directory. The account is + // already gone, so a spool or home that was kept is exit 12 only after + // the steps below have run. + let removal = if remove_home { remove_spool_and_home( &root, login, @@ -210,8 +213,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { saved_uid, force, home_shared_by_other, - )?; - } + ) + } else { + Ok(()) + }; if selinux_user { shadow_core::selinux::remove_login(login) @@ -223,7 +228,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { audit::log_user_event("DEL_USER", login, saved_uid, true); - Ok(()) + removal.map_err(Into::into) } #[must_use] @@ -286,7 +291,9 @@ pub fn uu_app() -> Command { /// Remove the mail spool and the home of the account being deleted, for `-r`. /// /// Either one missing is said on stderr and is not a failure, spool first, as -/// upstream does. +/// upstream does. A spool the user does not own is kept unless `force`; the +/// home is still removed. Whatever is kept is said here, in that order, and +/// the error only carries `CANT_REMOVE_HOME` for the caller to return last. fn remove_spool_and_home( root: &SysRoot, login: &str, @@ -294,29 +301,78 @@ fn remove_spool_and_home( uid: u32, force: bool, shared_by_other: bool, -) -> Result<(), UserdelError> { +) -> Result<(), AlreadyPrinted> { + let mut kept = false; let mail = root.resolve(&format!("/var/mail/{login}")); - // `exists()` follows a symlink on purpose, here and for the home below: - // Ubuntu 26.04's `userdel -r` reports a dangling link as not found, exit - // 0, and leaves it in place. - if mail.exists() { - let _ = std::fs::remove_file(&mail); - } else { - uucore::show_error!("{login} mail spool ({}) not found", mail.display()); + match remove_mail_spool(&mail, uid, force) { + Spool::Removed => {} + Spool::Missing => { + uucore::show_error!("{login} mail spool ({}) not found", mail.display()); + } + Spool::NotOwned => { + uucore::show_error!("{} not owned by {login}, not removing", mail.display()); + kept = true; + } } if home.is_empty() { // Nothing to remove; upstream names the empty path all the same. uucore::show_error!("{login} home directory () not found"); - return Ok(()); - } - let home = root.resolve(home); - if home.exists() { - safe_remove_home(&home, uid, force, shared_by_other) } else { - uucore::show_error!("{login} home directory ({}) not found", home.display()); - Ok(()) + let home = root.resolve(home); + // `exists()` follows a symlink on purpose: Ubuntu 26.04's `userdel -r` + // reports a dangling link as not found, exit 0, and leaves it in place. + if home.exists() { + if let Err(e) = safe_remove_home(&home, uid, force, shared_by_other) { + uucore::show_error!("{e}"); + kept = true; + } + } else { + uucore::show_error!("{login} home directory ({}) not found", home.display()); + } + } + + if kept { + return Err(AlreadyPrinted(exit_codes::CANT_REMOVE_HOME)); + } + Ok(()) +} + +/// What `-r` did with the mail spool. +enum Spool { + Removed, + Missing, + NotOwned, +} + +/// Remove the mail spool at `mail` unless it belongs to someone other than +/// `uid` and `force` is not given. +/// +/// Ownership is that of the file a symlink leads to; only the link is removed. +/// The check and the unlink go through one descriptor on the directory, so it +/// cannot be swapped in between. +fn remove_mail_spool(mail: &Path, uid: u32, force: bool) -> Spool { + use rustix::fs::{AtFlags, Mode, OFlags}; + + let (Some(parent), Some(name)) = (mail.parent(), mail.file_name()) else { + return Spool::Missing; + }; + let Ok(dir) = rustix::fs::open( + parent, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) else { + return Spool::Missing; + }; + let Ok(target) = rustix::fs::statat(&dir, name, AtFlags::empty()) else { + return Spool::Missing; + }; + if !force && target.st_uid != uid { + return Spool::NotOwned; } + // Ignored as it always was here; upstream warns and exits 12, a separate fix. + let _ = rustix::fs::unlinkat(&dir, name, AtFlags::empty()); + Spool::Removed } // --------------------------------------------------------------------------- diff --git a/tests/by-util/test_userdel.rs b/tests/by-util/test_userdel.rs index 22f04e7e..30f99c83 100644 --- a/tests/by-util/test_userdel.rs +++ b/tests/by-util/test_userdel.rs @@ -738,3 +738,184 @@ fn test_remove_leaves_a_dangling_home_link() { assert!(meta.file_type().is_symlink()); assert!(!read_passwd(&dir).contains("testuser:")); } + +/// What a spool test starts from: a home the user owns, so that the home's +/// fate shows whether `-r` carried on past the spool. +struct SpoolCase { + dir: tempfile::TempDir, + home: std::path::PathBuf, + spool: std::path::PathBuf, + target: std::path::PathBuf, +} + +/// The spool is a regular file, or with `link` a symlink to a file outside +/// /var/mail; that file, or the spool itself, is owned by `owner`. +fn spool_case(link: bool, owner: u32) -> SpoolCase { + let dir = setup_root_dir(); + let root = dir.path().to_path_buf(); + let home = root.join("home/testuser"); + std::fs::create_dir_all(&home).expect("home"); + std::os::unix::fs::chown(&home, Some(1000), Some(1000)).expect("chown home"); + std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); + let spool = root.join("var/mail/testuser"); + let target = root.join("srv-mailbox"); + if link { + std::fs::write(&target, "mail").expect("link target"); + std::os::unix::fs::chown(&target, Some(owner), Some(owner)).expect("chown target"); + std::os::unix::fs::symlink(&target, &spool).expect("spool link"); + } else { + std::fs::write(&spool, "mail").expect("spool"); + std::os::unix::fs::chown(&spool, Some(owner), Some(owner)).expect("chown spool"); + } + SpoolCase { + dir, + home, + spool, + target, + } +} + +fn run_spool_case(case: &SpoolCase, flags: &[&str]) -> crate::common::Output { + let prefix = case.dir.path().to_str().expect("non-UTF-8 temp path"); + let mut command_line = vec!["-P", prefix]; + command_line.extend_from_slice(flags); + command_line.push("testuser"); + crate::common::run("userdel", &command_line) +} + +/// A spool that is not the user's is kept, said on stderr, exit 12; the +/// account and the home go all the same. Ubuntu 26.04's `userdel -r` does so. +#[test] +fn test_remove_keeps_a_mail_spool_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case(false, 0); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(12); + assert!(out.stdout.is_empty(), "stdout: {:?}", out.stdout); + assert_eq!( + messages(&out), + [format!( + "{} not owned by testuser, not removing", + case.spool.display() + )] + ); + assert!(case.spool.exists(), "the spool should have been kept"); + assert!(!case.home.exists(), "the home should have been removed"); + assert!(!read_passwd(&case.dir).contains("testuser:")); +} + +/// `-f` removes a spool that is not the user's, without a word. +#[test] +fn test_remove_force_removes_a_mail_spool_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case(false, 0); + let out = run_spool_case(&case, &["-r", "-f"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(!case.spool.exists(), "the spool should have been removed"); + assert!(!case.home.exists(), "the home should have been removed"); +} + +/// A spool that is a symlink to someone else's file is judged by that file: +/// the link is kept, and so is the file, exit 12. +#[test] +fn test_remove_keeps_a_spool_link_to_a_file_the_user_does_not_own() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case(true, 0); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(12); + assert_eq!( + messages(&out), + [format!( + "{} not owned by testuser, not removing", + case.spool.display() + )] + ); + let meta = std::fs::symlink_metadata(&case.spool).expect("the link should be kept"); + assert!(meta.file_type().is_symlink()); + assert!(case.target.exists(), "the link target should be untouched"); + assert!(!case.home.exists(), "the home should have been removed"); + assert!(!read_passwd(&case.dir).contains("testuser:")); +} + +/// `-f` removes the link to someone else's file, never the file itself. +#[test] +fn test_remove_force_removes_a_spool_link_but_not_its_target() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case(true, 0); + let out = run_spool_case(&case, &["-r", "-f"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(std::fs::symlink_metadata(&case.spool).is_err()); + assert!(case.target.exists(), "the link target should be untouched"); +} + +/// A symlink to the user's own file is removed even though the link itself is +/// root's, and the file it points at stays, exit 0. +#[test] +fn test_remove_removes_a_spool_link_to_the_users_own_file() { + if crate::common::skip_unless_root() { + return; + } + + let case = spool_case(true, 1000); + let out = run_spool_case(&case, &["-r"]); + out.assert_code(0); + assert!(out.stderr.is_empty(), "stderr: {:?}", out.stderr); + assert!(std::fs::symlink_metadata(&case.spool).is_err()); + assert!(case.target.exists(), "the link target should be untouched"); + assert!(!case.home.exists(), "the home should have been removed"); +} + +/// The account is gone before the spool is looked at, so keeping the spool +/// must not skip what follows the removal: the audit record, the last of those +/// steps, is still written, and exit 12 comes after it. +#[test] +fn test_remove_keeping_the_spool_still_records_the_deletion() { + if crate::common::skip_unless_root() { + return; + } + let Some(listener) = crate::common::SyslogListener::bind() else { + return; + }; + + // A login of its own: other tests running alongside log about `testuser`. + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let root = dir.path(); + std::fs::create_dir_all(root.join("etc")).expect("etc"); + std::fs::write( + root.join("etc/passwd"), + "root:x:0:0:root:/root:/bin/bash\nspoolaudit:x:1000:1000::/home/spoolaudit:/bin/sh\n", + ) + .expect("passwd"); + std::fs::write(root.join("etc/group"), "root:x:0:\n").expect("group"); + let home = root.join("home/spoolaudit"); + std::fs::create_dir_all(&home).expect("home"); + std::os::unix::fs::chown(&home, Some(1000), Some(1000)).expect("chown home"); + std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); + let spool = root.join("var/mail/spoolaudit"); + std::fs::write(&spool, "mail").expect("spool"); + + let prefix = root.to_str().expect("non-UTF-8 temp path"); + let out = crate::common::run("userdel", &["-P", prefix, "-r", "spoolaudit"]); + out.assert_code(12); + assert!(spool.exists(), "the spool should have been kept"); + assert!(!home.exists(), "the home should have been removed"); + let passwd = std::fs::read_to_string(root.join("etc/passwd")).expect("read passwd"); + assert!(!passwd.contains("spoolaudit:"), "{passwd}"); + let line = listener.line_about("spoolaudit"); + assert!(line.contains("op=DEL_USER"), "{line}"); + assert!(line.contains("res=success"), "{line}"); +} diff --git a/tests/by-util/test_usermod.rs b/tests/by-util/test_usermod.rs index a8bf6670..6a726e60 100644 --- a/tests/by-util/test_usermod.rs +++ b/tests/by-util/test_usermod.rs @@ -1354,82 +1354,6 @@ fn test_rechown_home_that_cannot_be_walked() { } } -/// Listens on `/dev/log` for the life of a test, and removes it afterwards. -/// -/// Sending to a full datagram socket blocks, and every test in this process -/// that logs sends to this one while it exists, this test's own `usermod` -/// included. So a thread keeps it drained the whole time. -struct SyslogListener { - lines: std::sync::Arc>>, - stop: std::sync::Arc, - reader: Option>, -} - -impl SyslogListener { - const PATH: &'static str = "/dev/log"; - - /// `None` where a real syslog daemon already owns the socket: taking it - /// over would lose that daemon's log, and its messages cannot be read here. - fn bind() -> Option { - use std::sync::atomic::Ordering; - - if std::fs::symlink_metadata(Self::PATH).is_ok() { - return None; - } - let socket = std::os::unix::net::UnixDatagram::bind(Self::PATH).expect("bind /dev/log"); - socket - .set_read_timeout(Some(std::time::Duration::from_millis(50))) - .expect("set timeout"); - let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let reader = { - let lines = std::sync::Arc::clone(&lines); - let stop = std::sync::Arc::clone(&stop); - std::thread::spawn(move || { - let mut buf = [0u8; 2048]; - while !stop.load(Ordering::Relaxed) { - if let Ok(n) = socket.recv(&mut buf) { - lines - .lock() - .expect("lines lock") - .push(String::from_utf8_lossy(&buf[..n]).into_owned()); - } - } - }) - }; - Some(Self { - lines, - stop, - reader: Some(reader), - }) - } - - /// The first line about `login`. Tests run in parallel in this process and - /// log too, so lines about other accounts are expected here. - fn line_about(&self, login: &str) -> String { - let needle = format!("acct=\"{login}\""); - for _ in 0..1000 { - let lines = self.lines.lock().expect("lines lock"); - if let Some(line) = lines.iter().find(|line| line.contains(&needle)) { - return line.clone(); - } - drop(lines); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - panic!("no syslog line about {login}"); - } -} - -impl Drop for SyslogListener { - fn drop(&mut self) { - self.stop.store(true, std::sync::atomic::Ordering::Relaxed); - if let Some(reader) = self.reader.take() { - let _ = reader.join(); - } - let _ = std::fs::remove_file(Self::PATH); - } -} - /// The account files are written either way, but a home that could not be /// re-owned means the change did not complete, and exit 12 says so: the audit /// trail must not record the same run as a success. @@ -1438,7 +1362,7 @@ fn test_audit_records_a_failed_home_rechown_as_failed() { if crate::common::skip_unless_root() { return; } - let Some(listener) = SyslogListener::bind() else { + let Some(listener) = crate::common::SyslogListener::bind() else { return; }; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4df7601b..773334a9 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -137,3 +137,97 @@ pub fn run_cmd(cmd: &mut std::process::Command) -> Output { stderr: String::from_utf8_lossy(&out.stderr).into_owned(), } } + +/// Listens on `/dev/log` for the life of a test, and removes it afterwards. +/// +/// Sending to a full datagram socket blocks, and every test in this process +/// that logs sends to this one while it exists, the test's own tool included. +/// So a thread keeps it drained the whole time. +/// +/// There is one `/dev/log`, so tests that listen take turns: a second one +/// waits for the first to drop its listener, where it would otherwise find the +/// socket taken and skip. +pub struct SyslogListener { + lines: std::sync::Arc>>, + stop: std::sync::Arc, + reader: Option>, + // Fields drop after `drop` has run, so the next test waits for the socket to go. + _turn: std::sync::MutexGuard<'static, ()>, +} + +impl SyslogListener { + const PATH: &'static str = "/dev/log"; + + /// `None` where a real syslog daemon already owns the socket: taking it + /// over would lose that daemon's log, and its messages cannot be read here. + #[must_use] + pub fn bind() -> Option { + use std::sync::atomic::Ordering; + + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + // A test that panicked while listening still removed the socket. + let turn = TURN + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if std::fs::symlink_metadata(Self::PATH).is_ok() { + return None; + } + let socket = std::os::unix::net::UnixDatagram::bind(Self::PATH).expect("bind /dev/log"); + socket + .set_read_timeout(Some(std::time::Duration::from_millis(50))) + .expect("set timeout"); + let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let reader = { + let lines = std::sync::Arc::clone(&lines); + let stop = std::sync::Arc::clone(&stop); + std::thread::spawn(move || { + let mut buf = [0u8; 2048]; + while !stop.load(Ordering::Relaxed) { + if let Ok(n) = socket.recv(&mut buf) { + lines + .lock() + .expect("lines lock") + .push(String::from_utf8_lossy(&buf[..n]).into_owned()); + } + } + }) + }; + Some(Self { + lines, + stop, + reader: Some(reader), + _turn: turn, + }) + } + + /// The first line about `login`. Tests run in parallel in this process and + /// log too, so lines about other accounts are expected here. + /// + /// # Panics + /// + /// Panics if no such line arrives within ten seconds. + #[must_use] + pub fn line_about(&self, login: &str) -> String { + let needle = format!("acct=\"{login}\""); + for _ in 0..1000 { + let lines = self.lines.lock().expect("lines lock"); + if let Some(line) = lines.iter().find(|line| line.contains(&needle)) { + return line.clone(); + } + drop(lines); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + panic!("no syslog line about {login}"); + } +} + +impl Drop for SyslogListener { + fn drop(&mut self) { + self.stop.store(true, std::sync::atomic::Ordering::Relaxed); + if let Some(reader) = self.reader.take() { + let _ = reader.join(); + } + let _ = std::fs::remove_file(Self::PATH); + } +}