Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 7 additions & 1 deletion docs/man/userdel.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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*
Expand All @@ -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.

Expand Down
98 changes: 77 additions & 21 deletions src/uu/userdel/src/userdel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -201,17 +202,21 @@ 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,
saved_home,
saved_uid,
force,
home_shared_by_other,
)?;
}
)
} else {
Ok(())
};

if selinux_user {
shadow_core::selinux::remove_login(login)
Expand All @@ -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]
Expand Down Expand Up @@ -286,37 +291,88 @@ 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,
home: &str,
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
}

// ---------------------------------------------------------------------------
Expand Down
181 changes: 181 additions & 0 deletions tests/by-util/test_userdel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
Loading