diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eca028c..e0148af3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,18 +71,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- `useradd`, `usermod -l`, `groupadd`, `groupmod -n` and `newusers` take the names - upstream takes: a name may start with a digit or a dot, end with a dot, and a user - name may run to 255 characters. They refused `0abc`, `.abc`, `a.` and anything - over 32. A name that reads as a number (`123`, `0x1a`, `0o7`), a leading `-`, `.` - and `..` stay refused, now with upstream's message, and `groupmod -n -x` is exit 3, - not a usage error. `newusers` refuses to create a group over 32 characters, as - upstream does (#391) - -- `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) - - `gpasswd -a`, `-A` and `-M` accept a user that only the name service knows, such as one from LDAP or SSSD, as upstream does. They refused anyone missing from /etc/passwd, exit 3 (#381) diff --git a/docs/man/groupadd.8.md b/docs/man/groupadd.8.md index 7b0b5bf0..9c55f7fe 100644 --- a/docs/man/groupadd.8.md +++ b/docs/man/groupadd.8.md @@ -54,14 +54,6 @@ The new group will be entered into the system files (/etc/group and the exit status is 10 and no group is created. An empty name is not a user: an empty list and a stray comma are refused too. -## GROUP NAMES - -A group name is up to 32 characters, the `$` included, of ASCII letters, digits, -`_`, `.` and `-`, with one `$` allowed at the end. It may start with a digit or a -dot, but not with `-`, and it may not be `.`, `..`, or something that reads as a -number, decimal (`123`), hexadecimal (`0x1a`) or octal (`0o7`), which would be taken -for a group ID. Any other name is exit status 3. - ## EXIT STATUS **0** diff --git a/docs/man/groupmod.8.md b/docs/man/groupmod.8.md index cf7854ac..7cf4adc4 100644 --- a/docs/man/groupmod.8.md +++ b/docs/man/groupmod.8.md @@ -46,15 +46,6 @@ databases. Otherwise the exit status is 10 and nothing changes. An empty name is not a user: an empty list and a stray comma are refused too. -## GROUP NAMES - -The new name given with **-n** follows the rule of **groupadd**(8). A group name is -up to 32 characters, the `$` included, of ASCII letters, digits, `_`, `.` and `-`, -with one `$` allowed at the end. It may start with a digit or a dot, but not with -`-`, and it may not be `.`, `..`, or something that reads as a number, decimal -(`123`), hexadecimal (`0x1a`) or octal (`0o7`), which would be taken for a group ID. -Any other name is exit status 3. - ## EXIT STATUS **0** diff --git a/docs/man/newusers.8.md b/docs/man/newusers.8.md index e10241ae..56c1d283 100644 --- a/docs/man/newusers.8.md +++ b/docs/man/newusers.8.md @@ -67,19 +67,6 @@ surprise than a missing directory. directory; otherwise the directory is created with mode 0700, owned by the new account, and /etc/skel is copied into it. -## NAMES - -The login name follows the rule of **useradd**(8). A user name is up to 255 -characters of ASCII letters, digits, `_`, `.` and `-`, with one `$` allowed at the -end for a Samba machine account. It may start with a digit or a dot, but not with -`-`, and it may not be `.`, `..`, or something that reads as a number, decimal -(`123`), hexadecimal (`0x1a`) or octal (`0o7`), which would be taken for a user ID. - -A line that creates a group of the user's own name, with an empty or new numeric -GID field, also needs a valid group name, as **groupadd**(8) does: no longer than 32 -characters. Either refusal is exit status 1, before anything is written, unless -**--badname** is given. - ## OPTIONS **-b**, **--badname** diff --git a/docs/man/useradd.8.md b/docs/man/useradd.8.md index e8e037db..11b4c285 100644 --- a/docs/man/useradd.8.md +++ b/docs/man/useradd.8.md @@ -107,14 +107,6 @@ default values used for creating new accounts. not on btrfs the exit status is 12, with the account written. Without **-m** it does nothing. -## USER NAMES - -A user name is up to 255 characters of ASCII letters, digits, `_`, `.` and `-`, with -one `$` allowed at the end for a Samba machine account. It may start with a digit or -a dot, but not with `-`, and it may not be `.`, `..`, or something that reads as a -number, decimal (`123`), hexadecimal (`0x1a`) or octal (`0o7`), which would be taken -for a user ID. Any other name is exit status 19, unless **--badname** is given. - ## EXIT STATUS **0** diff --git a/docs/man/userdel.8.md b/docs/man/userdel.8.md index 7f495ab0..f9f04120 100644 --- a/docs/man/userdel.8.md +++ b/docs/man/userdel.8.md @@ -33,10 +33,6 @@ is also removed from membership lists in /etc/group and /etc/gshadow. the removal is committed, as upstream prints it. On a kernel older than 6.10, which does not tell the subvolume's ID, the line is not printed. - A mail spool or home that is not there is not an error: *LOGIN mail spool - (PATH) not found* and *LOGIN home directory (PATH) not found* are printed on - standard error, in that order, and the exit status is unchanged. - **-R**, **--root** *CHROOT_DIR* : Apply changes in the *CHROOT_DIR* directory. diff --git a/docs/man/usermod.8.md b/docs/man/usermod.8.md index 53c3635d..bccbfe51 100644 --- a/docs/man/usermod.8.md +++ b/docs/man/usermod.8.md @@ -137,15 +137,6 @@ a name, and an administrator who renames the account re-grants it if that is what they meant. Because **-V** is this option, **--version** has no short form. -## USER NAMES - -The new name given with **-l** follows the rule of **useradd**(8). A user name is up -to 255 characters of ASCII letters, digits, `_`, `.` and `-`, with one `$` allowed -at the end for a Samba machine account. It may start with a digit or a dot, but not -with `-`, and it may not be `.`, `..`, or something that reads as a number, decimal -(`123`), hexadecimal (`0x1a`) or octal (`0o7`), which would be taken for a user ID. -Any other name is exit status 3, unless **-b** is given. - ## EXIT STATUS **0** diff --git a/fuzz/fuzz_targets/fuzz_validate_username.rs b/fuzz/fuzz_targets/fuzz_validate_username.rs index b3e88492..260a7424 100644 --- a/fuzz/fuzz_targets/fuzz_validate_username.rs +++ b/fuzz/fuzz_targets/fuzz_validate_username.rs @@ -5,15 +5,14 @@ //! Fuzz target for username validation. //! -//! Ensures the user and group name checks never panic on arbitrary string input. +//! Ensures `validate_username` never panics on arbitrary string input. #![no_main] use libfuzzer_sys::fuzz_target; fuzz_target!(|data: &[u8]| { if let Ok(s) = std::str::from_utf8(data) { - // Must not panic on any input; either answer is fine. - let _ = shadow_core::validate::is_valid_user_name(s); - let _ = shadow_core::validate::is_valid_group_name(s); + // Must not panic on any input — errors are fine. + let _ = shadow_core::validate::validate_username(s); } }); diff --git a/src/shadow-core/src/validate.rs b/src/shadow-core/src/validate.rs index 63337877..edcc4020 100644 --- a/src/shadow-core/src/validate.rs +++ b/src/shadow-core/src/validate.rs @@ -10,22 +10,18 @@ use crate::error::ShadowError; -/// Longest user name: upstream's `useradd`, `usermod -l` and `newusers` take -/// 255 characters, and `pwck` passes as many. -pub const MAX_USER_NAME_LEN: usize = 255; - -/// Longest group name: upstream's `groupadd`, `groupmod -n`, `newusers` and -/// `grpck` stop at 32 characters. -pub const MAX_GROUP_NAME_LEN: usize = 32; +/// Maximum username length on Linux. +const MAX_USERNAME_LEN: usize = 32; /// Whether a name already in an account file passes the checks of `pwck` and /// `grpck`, which take `max_len`: a user name may run to 255, a group name to 32. /// -/// The rule is what Ubuntu 26.04's `pwck` and `grpck` were seen to do: ASCII -/// letters, digits, `_`, `.` and `-`, with one `$` at the end, and not `.`, -/// `..`, or something that reads as a number in base 10, 8 or 16 (`123`, -/// `0o7`, `0xABC`), which would be taken for an ID. A leading digit is fine: -/// `1abc` is a name, `123` is a UID. +/// This is wider than [`validate_username`], which judges a new account: `1abc` +/// or 40 letters may be on a system already, and calling them bad would fail the +/// whole check there. The rule is what Ubuntu 26.04's `pwck` and `grpck` were +/// seen to do: ASCII letters, digits, `_`, `.` and `-`, with one `$` at the end, +/// and not `.`, `..`, or something that reads as a number in base 10, 8 or 16 +/// (`123`, `0o7`, `0xABC`). #[must_use] pub fn is_valid_account_name(name: &str, max_len: usize) -> bool { let body = name.strip_suffix('$').unwrap_or(name); @@ -48,31 +44,67 @@ pub fn is_valid_account_name(name: &str, max_len: usize) -> bool { .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')) } -/// Whether a new or renamed account may take `name`: the rule of -/// [`is_valid_account_name`], and not starting with `-`, which every tool -/// downstream would read as an option. Ubuntu 26.04's `useradd`, `usermod -l`, -/// `groupadd`, `groupmod -n` and `newusers` were seen to refuse a leading `-` -/// that `pwck` and `grpck` let pass in a file. -fn is_valid_new_name(name: &str, max_len: usize) -> bool { - !name.starts_with('-') && is_valid_account_name(name, max_len) -} - -/// Whether `useradd`, `usermod -l` and `newusers` may give a user this name, -/// without `--badname`. +/// Validate a username or group name. /// -/// Upper case, a leading digit or dot, a trailing dot and a Samba machine -/// account's trailing `$` are all accepted, as upstream does; lower case is -/// the recommendation, not a rule. -#[must_use] -pub fn is_valid_user_name(name: &str) -> bool { - is_valid_new_name(name, MAX_USER_NAME_LEN) -} +/// Rules, from the CAVEATS of useradd(8) and groupadd(8): +/// - must not be empty, and at most 32 characters +/// - first character is a letter or underscore +/// - the rest are letters, digits, underscores, hyphens or periods +/// - a single trailing `$` is allowed, which is how Samba names machine +/// accounts (`MACHINE$`) +/// - must not end with a period, and must not consist only of periods +/// +/// Upper case is accepted: `useradd Alice` succeeds on upstream shadow +/// (verified), and rejecting it made us refuse accounts that already exist on +/// real systems. Lower case remains the recommendation, not a rule. +/// +/// # Errors +/// +/// Returns `ShadowError::Validation` if the name violates any rule. +pub fn validate_username(name: &str) -> Result<(), ShadowError> { + if name.len() > MAX_USERNAME_LEN { + return Err(ShadowError::Validation( + format!("username '{name}' exceeds maximum length of {MAX_USERNAME_LEN} characters") + .into(), + )); + } -/// Whether `groupadd`, `groupmod -n` and `newusers` may give a group this -/// name: the user name rule, at most 32 characters. -#[must_use] -pub fn is_valid_group_name(name: &str) -> bool { - is_valid_new_name(name, MAX_GROUP_NAME_LEN) + // A single trailing '$' is part of the name but not of the character set. + let body = name.strip_suffix('$').unwrap_or(name); + + let mut chars = body.chars(); + // Reject empty names by requiring a first character here. + let Some(first) = chars.next() else { + return Err(ShadowError::Validation("username must not be empty".into())); + }; + + if !first.is_ascii_alphabetic() && first != '_' { + return Err(ShadowError::Validation( + format!("username '{name}' must start with a letter or underscore").into(), + )); + } + + for ch in chars { + if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' && ch != '.' { + return Err(ShadowError::Validation( + format!("username '{name}' contains invalid character '{ch}'").into(), + )); + } + } + + if body.ends_with('.') { + return Err(ShadowError::Validation( + format!("username '{name}' must not end with a period").into(), + )); + } + + if body.chars().all(|c| c == '.') { + return Err(ShadowError::Validation( + format!("username '{name}' must not consist only of periods").into(), + )); + } + + Ok(()) } /// Reject a value that would corrupt a colon-separated account file. @@ -124,37 +156,95 @@ fn describe_char(c: char) -> String { mod tests { use super::*; - /// What Ubuntu 26.04's `useradd`, `usermod -l` and `newusers` were seen - /// to accept and refuse. #[test] - fn test_user_names_follow_the_probe() { - for name in [ - "root", "_apt", "user123", "Alice", "MACHINE$", "0abc", "1e5", "1-1", "_abc", ".abc", - "a.", "...", "a$", "1$", "123$", ".$", "0xg", "0X1", "0b1", "1.5", "0x1$", "a-", - "a..b", "0abc.", - ] { - assert!(is_valid_user_name(name), "{name} should be accepted"); - } - for name in [ - "", "123", "0", "00", "0x", "0x1a", "0o7", "-abc", "-x", "-", ".", "..", "$", "a$b", - "a$$", "ma$chine", "a@b", "a+b", "a b", "a:b", "é", "café", "\0user", - ] { - assert!(!is_valid_user_name(name), "{name:?} should be refused"); - } - assert!(is_valid_user_name(&"a".repeat(255))); - assert!(!is_valid_user_name(&"a".repeat(256))); + fn test_valid_usernames() { + assert!(validate_username("root").is_ok()); + assert!(validate_username("_apt").is_ok()); + assert!(validate_username("user123").is_ok()); + assert!(validate_username("test-user").is_ok()); + assert!(validate_username("test.user").is_ok()); + assert!(validate_username("a").is_ok()); + } + + #[test] + fn test_empty_username() { + assert!(validate_username("").is_err()); + } + + #[test] + fn test_too_long() { + let long_name = "a".repeat(33); + assert!(validate_username(&long_name).is_err()); + let max_name = "a".repeat(32); + assert!(validate_username(&max_name).is_ok()); + } + + #[test] + fn test_invalid_first_char() { + assert!(validate_username("1user").is_err()); + assert!(validate_username("-user").is_err()); + assert!(validate_username(".user").is_err()); + } + + #[test] + fn test_invalid_chars() { + assert!(validate_username("user@name").is_err()); + assert!(validate_username("user name").is_err()); + assert!(validate_username("user:name").is_err()); + } + + #[test] + fn test_trailing_period() { + assert!(validate_username("user.").is_err()); + } + + // ------------------------------------------------------------------- + // Issue #16: additional edge case tests + // ------------------------------------------------------------------- + + #[test] + fn test_unicode_username_rejected() { + assert!(validate_username("café").is_err()); + } + + #[test] + fn test_null_byte_rejected() { + assert!(validate_username("\0user").is_err()); + } + + #[test] + fn test_max_length_32_ok() { + let name = "a".repeat(32); + assert!(validate_username(&name).is_ok()); + } + + #[test] + fn test_length_33_rejected() { + let name = "a".repeat(33); + assert!(validate_username(&name).is_err()); + } + + #[test] + fn test_only_dots_rejected() { + assert!(validate_username("..").is_err()); + assert!(validate_username("...").is_err()); + } + + #[test] + fn test_hyphen_start_rejected() { + assert!(validate_username("-user").is_err()); } - /// Groups follow the user rule but stop at 32 characters, `$` included. + // upstream shadow accepts these (verified against useradd(8)); refusing + // them made us reject accounts that exist on real systems. #[test] - fn test_group_names_follow_the_probe() { - assert!(is_valid_group_name("0abc")); - assert!(!is_valid_group_name("123")); - assert!(!is_valid_group_name("-x")); - assert!(is_valid_group_name(&"a".repeat(32))); - assert!(!is_valid_group_name(&"a".repeat(33))); - assert!(is_valid_group_name(&format!("{}$", "a".repeat(31)))); - assert!(!is_valid_group_name(&format!("{}$", "a".repeat(32)))); + fn test_uppercase_and_machine_accounts_accepted() { + assert!(validate_username("Alice").is_ok()); + assert!(validate_username("DevOps").is_ok()); + assert!(validate_username("MACHINE$").is_ok()); + // The '$' is only meaningful as the last character. + assert!(validate_username("ma$chine").is_err()); + assert!(validate_username("$").is_err()); } // ------------------------------------------------------------------- diff --git a/src/uu/groupadd/src/groupadd.rs b/src/uu/groupadd/src/groupadd.rs index 3bc4e25e..4ba46130 100644 --- a/src/uu/groupadd/src/groupadd.rs +++ b/src/uu/groupadd/src/groupadd.rs @@ -149,12 +149,8 @@ fn do_groupadd(matches: &clap::ArgMatches) -> UResult<()> { } // Validate the group name. - if !validate::is_valid_group_name(&group_name) { - return Err(GroupaddError::BadArgument(format!( - "'{group_name}' is not a valid group name" - )) - .into()); - } + validate::validate_username(&group_name) + .map_err(|e| GroupaddError::BadArgument(format!("{e}")))?; let group_path = root.group_path(); diff --git a/src/uu/groupmod/src/groupmod.rs b/src/uu/groupmod/src/groupmod.rs index de2ef9c6..c99cd0db 100644 --- a/src/uu/groupmod/src/groupmod.rs +++ b/src/uu/groupmod/src/groupmod.rs @@ -125,10 +125,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let root = SysRoot::new(prefix); // Validate new name if provided. - if let Some(name) = new_name - && !shadow_core::validate::is_valid_group_name(name) - { - return Err(GroupmodError::BadArgument(format!("invalid group name '{name}'")).into()); + if let Some(name) = new_name { + shadow_core::validate::validate_username(name) + .map_err(|e| GroupmodError::BadArgument(format!("{e}")))?; } // Parse new GID if provided. u32::MAX is (gid_t)-1, the "no change" @@ -318,10 +317,7 @@ pub fn uu_app() -> Command { .short('n') .long("new-name") .value_name("NEW_GROUP") - .help("Rename the group to NEW_GROUP") - // Taken as the name, as upstream does, and refused as one: exit - // 3 and not a usage error. - .allow_hyphen_values(true), + .help("Rename the group to NEW_GROUP"), ) .arg( Arg::new(options::NON_UNIQUE) diff --git a/src/uu/grpck/src/grpck.rs b/src/uu/grpck/src/grpck.rs index 9f0948b1..8f25b45e 100644 --- a/src/uu/grpck/src/grpck.rs +++ b/src/uu/grpck/src/grpck.rs @@ -145,6 +145,9 @@ fn report(message: fmt::Arguments<'_>) { let _ = writeln!(std::io::stdout(), "{message}"); } +/// The longest group name `grpck` takes, as seen on Ubuntu 26.04's. +const MAX_GROUP_NAME_LEN: usize = 32; + /// Core logic, separated from argument parsing. fn run_checks(opts: &GrpckOptions) -> UResult<()> { let group_lines = read_raw_lines(&opts.group_path).map_err(|e| { @@ -284,10 +287,7 @@ fn check_names_are_valid(entries: &[GroupEntry]) -> u32 { let mut errors: u32 = 0; for entry in entries { - if !shadow_core::validate::is_valid_account_name( - &entry.name, - shadow_core::validate::MAX_GROUP_NAME_LEN, - ) { + if !shadow_core::validate::is_valid_account_name(&entry.name, MAX_GROUP_NAME_LEN) { report(format_args!("invalid group name '{}'", entry.name)); errors += 1; } diff --git a/src/uu/newusers/src/newusers.rs b/src/uu/newusers/src/newusers.rs index ccf1ca74..09d6100d 100644 --- a/src/uu/newusers/src/newusers.rs +++ b/src/uu/newusers/src/newusers.rs @@ -171,10 +171,8 @@ fn validate(line: &Line, relaxed: bool) -> Result<(), NewusersError> { line.number, line.name ))); } - } else if !shadow_core::validate::is_valid_user_name(&line.name) { - // Upstream names the fault, then the line it gave up on. - uucore::show_error!("invalid user name '{}': use --badname to ignore", line.name); - return Err(line_error(line, "can't create user")); + } else { + shadow_core::validate::validate_username(&line.name).map_err(bad)?; } shadow_core::validate::validate_field("GECOS", &line.gecos).map_err(bad)?; @@ -239,7 +237,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { return Ok(()); } - apply(&root, &defs, &lines, system, relaxed, method) + apply(&root, &defs, &lines, system, method) } /// Build the clap `Command` for `newusers`. @@ -305,7 +303,6 @@ fn apply( defs: &LoginDefs, lines: &[Line], system: bool, - relaxed: bool, method: shadow_core::crypt::CryptMethod, ) -> UResult<()> { // Hash before taking any lock: crypt(3) is deliberately slow, and a batch @@ -332,7 +329,7 @@ fn apply( NewusersError::UnexpectedFailure(format!("cannot determine the current date: {e}")) })?; let (uid_min, uid_max) = uid_alloc::uid_range(defs, system); - let gid_range = uid_alloc::gid_range(defs, system); + let (gid_min, gid_max) = uid_alloc::gid_range(defs, system); let mut homes = Vec::new(); @@ -349,7 +346,7 @@ fn apply( .ok_or_else(|| line_error(line, &format!("invalid user ID '{given}'")))?, }; - let gid = resolve_gid(&mut group, line, uid, gid_range, system, scope, relaxed)?; + let gid = resolve_gid(&mut group, line, uid, gid_min, gid_max, system, scope)?; match existing { Some(i) => { @@ -423,10 +420,10 @@ fn resolve_gid( group: &mut LockedFile, line: &Line, uid: u32, - (gid_min, gid_max): (u32, u32), + gid_min: u32, + gid_max: u32, system: bool, scope: Scope, - relaxed: bool, ) -> Result { // A number names a group directly. If no group has it, one is created // carrying the user's name -- otherwise the account would be left pointing @@ -434,7 +431,7 @@ fn resolve_gid( // what grpck then reports. if let Some(gid) = parse_id(&line.gid) { if !group.entries().iter().any(|g| g.gid == gid) { - push_group(group, line, gid, relaxed)?; + push_group(group, &line.name, gid); } return Ok(gid); } @@ -468,33 +465,19 @@ fn resolve_gid( } else { uid }; - push_group(group, line, gid, relaxed)?; + push_group(group, &line.name, gid); Ok(gid) } -/// Add a group named after the line's user, with no members: the user's -/// primary group is recorded in `/etc/passwd`, not in the member list. -/// -/// The name has passed the user rule, but a group name stops at 32 -/// characters, so a longer one is refused here as upstream refuses it, unless -/// `relaxed` (`--badname`). -fn push_group( - group: &mut LockedFile, - line: &Line, - gid: u32, - relaxed: bool, -) -> Result<(), NewusersError> { - if !relaxed && !shadow_core::validate::is_valid_group_name(&line.name) { - uucore::show_error!("invalid group name '{}'", line.name); - return Err(line_error(line, "can't create group")); - } +/// Add a group with no members: the user's primary group is recorded in +/// `/etc/passwd`, not in the member list. +fn push_group(group: &mut LockedFile, name: &str, gid: u32) { group.entries_mut().push(GroupEntry { - name: line.name.clone(), + name: name.to_string(), passwd: "x".to_string(), gid, members: Vec::new(), }); - Ok(()) } /// Write the account's hash and aging fields. @@ -670,10 +653,10 @@ mod tests { /// name from corrupting the file or being read as an option. #[test] fn test_badname_relaxes_only_the_portability_rules() { - // Both are refused by the portability rules and neither can corrupt a - // file: a name that reads as a UID, and the domain-qualified form an - // Active Directory join produces. - for odd in ["1234:pw:1000:1000:::", "alice@corp:pw:1000:1000:::"] { + // Both are refused by the portability rules and both turn up on real + // systems: a name starting with a digit, and the domain-qualified form + // an Active Directory join produces. Neither can corrupt a file. + for odd in ["3dprint:pw:1000:1000:::", "alice@corp:pw:1000:1000:::"] { assert!( validate(&line(odd), false).is_err(), "the strict rules should refuse {odd:?}" diff --git a/src/uu/pwck/src/pwck.rs b/src/uu/pwck/src/pwck.rs index 314f3de9..84366f6f 100644 --- a/src/uu/pwck/src/pwck.rs +++ b/src/uu/pwck/src/pwck.rs @@ -171,6 +171,9 @@ fn report(message: fmt::Arguments<'_>) { let _ = writeln!(std::io::stdout(), "{message}"); } +/// The longest user name `pwck` takes, as seen on Ubuntu 26.04's. +const MAX_USER_NAME_LEN: usize = 255; + /// Core logic, separated from argument parsing to keep `uumain` short. fn run_checks(opts: &PwckOptions) -> UResult<()> { let passwd_lines = read_raw_lines(&opts.passwd_path).map_err(|e| { @@ -489,10 +492,7 @@ fn check_passwd_entries( )); errors += 1; } else if !badname - && !shadow_core::validate::is_valid_account_name( - &entry.name, - shadow_core::validate::MAX_USER_NAME_LEN, - ) + && !shadow_core::validate::is_valid_account_name(&entry.name, MAX_USER_NAME_LEN) { report(format_args!( "invalid user name '{}': use --badname to ignore", diff --git a/src/uu/useradd/src/useradd.rs b/src/uu/useradd/src/useradd.rs index a5001094..fe6537a3 100644 --- a/src/uu/useradd/src/useradd.rs +++ b/src/uu/useradd/src/useradd.rs @@ -595,12 +595,9 @@ fn do_useradd(opts: &UseraddOptions) -> UResult<()> { } validate::validate_field("login name", &opts.login) .map_err(|e| UseraddError::CannotUpdatePasswd(e.to_string()))?; - } else if !validate::is_valid_user_name(&opts.login) { - return Err(UseraddError::BadName(format!( - "invalid user name '{}': use --badname to ignore", - opts.login - )) - .into()); + } else { + validate::validate_username(&opts.login) + .map_err(|e| UseraddError::BadName(format!("{e}")))?; } // Step 2: Block signals for the lock→write critical section only. diff --git a/src/uu/userdel/src/userdel.rs b/src/uu/userdel/src/userdel.rs index b8cf4718..e895965f 100644 --- a/src/uu/userdel/src/userdel.rs +++ b/src/uu/userdel/src/userdel.rs @@ -201,16 +201,17 @@ 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. + // 7. Optionally remove the home directory and mail spool. if remove_home { - remove_spool_and_home( - &root, - login, - saved_home, - saved_uid, - force, - home_shared_by_other, - )?; + if !saved_home.is_empty() { + let home = root.resolve(saved_home); + safe_remove_home(&home, saved_uid, force, home_shared_by_other)?; + } + + let mail = root.resolve(&format!("/var/mail/{login}")); + if mail.exists() { + let _ = std::fs::remove_file(&mail); + } } if selinux_user { @@ -279,43 +280,6 @@ pub fn uu_app() -> Command { ) } -// --------------------------------------------------------------------------- -// Mail spool and home removal -// --------------------------------------------------------------------------- - -/// 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. -fn remove_spool_and_home( - root: &SysRoot, - login: &str, - home: &str, - uid: u32, - force: bool, - shared_by_other: bool, -) -> Result<(), UserdelError> { - let mail = root.resolve(&format!("/var/mail/{login}")); - if mail.exists() { - let _ = std::fs::remove_file(&mail); - } else { - uucore::show_error!("{login} mail spool ({}) not found", mail.display()); - } - - 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(()) - } -} - // --------------------------------------------------------------------------- // Safe home directory removal // --------------------------------------------------------------------------- @@ -326,7 +290,7 @@ const PROTECTED_DIRS: &[&str] = &[ "/proc", "/root", "/run", "/sbin", "/srv", "/sys", "/tmp", "/usr", "/var", ]; -/// Safely remove a home directory that exists, with multiple safeguards: +/// Safely remove a home directory with multiple safeguards: /// - Refuse a home shared with another account, or not owned by the user, /// unless `force` (userdel(8) ties both to `-f`). /// - Refuse to remove protected system directories. @@ -338,6 +302,10 @@ fn safe_remove_home( force: bool, shared_by_other: bool, ) -> Result<(), UserdelError> { + if !home.exists() { + return Ok(()); + } + if shared_by_other && !force { return Err(UserdelError::CantRemoveHome(format!( "not removing '{}': it is used by another user (use -f to force)", diff --git a/src/uu/usermod/src/usermod.rs b/src/uu/usermod/src/usermod.rs index f2489e19..fcdd57d4 100644 --- a/src/uu/usermod/src/usermod.rs +++ b/src/uu/usermod/src/usermod.rs @@ -715,7 +715,7 @@ fn check_value( if badname { validate::validate_field("login name", value) .map_err(|e| bad(format!("invalid login name: {e}")))?; - } else if !validate::is_valid_user_name(value) { + } else if validate::validate_username(value).is_err() { return Err(bad(format!( "invalid user name '{value}': use --badname to ignore" ))); diff --git a/tests/by-util/test_fuzz_corpus.rs b/tests/by-util/test_fuzz_corpus.rs index be2920c9..d04dac5c 100644 --- a/tests/by-util/test_fuzz_corpus.rs +++ b/tests/by-util/test_fuzz_corpus.rs @@ -113,11 +113,6 @@ fn test_subid_corpus_round_trips() { #[test] fn test_username_corpus_is_answered() { for text in inputs("fuzz_validate_username") { - // A group name is a user name that fits in 32 characters. - let group = shadow_core::validate::is_valid_group_name(&text); - assert!( - !group || shadow_core::validate::is_valid_user_name(&text), - "{text:?} is a valid group name but not a valid user name" - ); + let _ = shadow_core::validate::validate_username(&text); } } diff --git a/tests/by-util/test_groupadd.rs b/tests/by-util/test_groupadd.rs index 79cdf6e3..867d9d1e 100644 --- a/tests/by-util/test_groupadd.rs +++ b/tests/by-util/test_groupadd.rs @@ -443,50 +443,3 @@ fn test_password_with_a_colon_exits_10_and_creates_nothing() { assert_eq!(run_with_prefix(&dir, &["-p", "a:b", "devs"]), 10); assert_eq!(read_group(&dir), "root:x:0:\n"); } - -/// The names Ubuntu 26.04's `groupadd` was seen to take and refuse: the user -/// name rules, but no longer than 32 characters. -#[test] -fn test_group_names_follow_upstream() { - if crate::common::skip_unless_root() { - return; - } - - let dir = setup_prefix("root:x:0:\n", "GID_MIN 1000\nGID_MAX 60000\n"); - let prefix = dir.path().to_str().expect("non-UTF-8 temp path"); - let longest = "a".repeat(32); - let longest_machine = format!("{}$", "b".repeat(31)); - for name in [ - "0abc", - "1e5", - ".abc", - "a.", - "123$", - &longest, - &longest_machine, - ] { - crate::common::run("groupadd", &["-P", prefix, "--", name]).assert_code(0); - assert!( - read_group(&dir).contains(&format!("\n{name}:x:")), - "groupadd should have created {name}" - ); - } - - let too_long = "c".repeat(33); - let too_long_machine = format!("{}$", "d".repeat(32)); - for name in [ - "123", - "0x1a", - "0o7", - "-x", - ".", - "..", - "a@b", - &too_long, - &too_long_machine, - ] { - crate::common::run("groupadd", &["-P", prefix, "--", name]) - .assert_code(3) - .assert_stderr_contains(&format!("'{name}' is not a valid group name")); - } -} diff --git a/tests/by-util/test_groupmod.rs b/tests/by-util/test_groupmod.rs index 2c38cdac..d0e3da31 100644 --- a/tests/by-util/test_groupmod.rs +++ b/tests/by-util/test_groupmod.rs @@ -505,33 +505,3 @@ fn test_password_with_a_colon_exits_10() { assert_eq!(run(&["groupmod", "-p", "a:b", "-P", prefix, "mygrp"]), 10); assert_eq!(read_gshadow(&dir), "mygrp:!::\n"); } - -/// `groupmod -n` takes the names upstream's `groupadd` takes. -#[test] -fn test_rename_follows_upstream_name_rules() { - if crate::common::skip_unless_root() { - return; - } - - let dir = setup_root( - "oldgrp:x:1000:\n", - "oldgrp:!::\n", - "root:x:0:0:root:/root:/bin/bash\n", - ); - let prefix = dir.path().to_str().expect("non-UTF-8 temp path"); - let mut current = String::from("oldgrp"); - for name in ["0abc", "1e5", ".abc", "a.", "123$", &"a".repeat(32)] { - crate::common::run("groupmod", &["-P", prefix, "-n", name, ¤t]).assert_code(0); - assert!( - read_group(&dir).starts_with(&format!("{name}:x:1000:")), - "groupmod -n should have renamed {current} to {name}" - ); - current = name.to_string(); - } - - for name in ["123", "0x1a", "0o7", "-x", ".", "a@b", &"a".repeat(33)] { - crate::common::run("groupmod", &["-P", prefix, "-n", name, ¤t]) - .assert_code(3) - .assert_stderr_contains(&format!("invalid group name '{name}'")); - } -} diff --git a/tests/by-util/test_newusers.rs b/tests/by-util/test_newusers.rs index 9c64e981..c819dd5b 100644 --- a/tests/by-util/test_newusers.rs +++ b/tests/by-util/test_newusers.rs @@ -418,57 +418,3 @@ fn test_help_exits_zero() { .assert_code(0) .assert_stdout_contains("Usage:"); } - -/// The messages of a run, without the program name each line starts with. -fn messages(out: &Output) -> Vec<&str> { - out.stderr - .lines() - .map(|l| l.split_once(": ").map_or(l, |(_, rest)| rest)) - .collect() -} - -/// `newusers` judges the login name as upstream's `useradd` does, and the -/// group it creates for a new GID as `groupadd` does, so a 40-character name -/// is a fine user but not a fine group. Each refusal names the fault, then -/// the line, as upstream does. -#[test] -fn test_names_follow_upstream() { - if skip_unless_root() { - return; - } - - let dir = prefix(); - for name in ["0abc", "1e5", ".abc", "a.", "123$"] { - newusers(&dir, &[], &format!("{name}:pw:::::/bin/sh\n")).assert_code(0); - assert!(has_entry(&dir, "passwd", name), "{name} should exist"); - } - let long = "a".repeat(40); - newusers(&dir, &[], &format!("{long}:pw::2000:::/bin/sh\n")).assert_code(0); - assert!(has_entry(&dir, "passwd", &long), "{long} should exist"); - - for name in ["123", "0x1a", "0o7", "-x", ".", "a@b"] { - let out = newusers(&dir, &[], &format!("{name}:pw::2000:::/bin/sh\n")); - out.assert_code(1); - assert_eq!( - messages(&out), - [ - format!("invalid user name '{name}': use --badname to ignore"), - "line 1: can't create user".to_string(), - ] - ); - assert!(!has_entry(&dir, "passwd", name), "{name} should not exist"); - } - - let long = "b".repeat(40); - let out = newusers(&dir, &[], &format!("{long}:pw::3000:::/bin/sh\n")); - out.assert_code(1); - assert_eq!( - messages(&out), - [ - format!("invalid group name '{long}'"), - "line 1: can't create group".to_string(), - ] - ); - assert!(!has_entry(&dir, "passwd", &long), "{long} should not exist"); - assert!(!has_entry(&dir, "group", &long), "no group {long} either"); -} diff --git a/tests/by-util/test_useradd.rs b/tests/by-util/test_useradd.rs index 3b4ba2ce..3b97e59d 100644 --- a/tests/by-util/test_useradd.rs +++ b/tests/by-util/test_useradd.rs @@ -1049,40 +1049,3 @@ fn test_selinux_range_needs_selinux_user() { let dir = setup_new_options(); assert_eq!(add(&dir, &["-M", "--selinux-range", "s0", "u4"]), 2); } - -/// The names Ubuntu 26.04's `useradd` was seen to take and refuse. A leading -/// digit is fine; what is refused is a name that reads as a number (a UID), -/// a leading `-` (an option), `.` and `..` (paths), and anything outside the -/// portable set. A user name may run to 255 characters. -#[test] -fn test_user_names_follow_upstream() { - if crate::common::skip_unless_root() { - return; - } - - let dir = setup_root_dir(); - let prefix = dir.path().to_str().expect("non-UTF-8 temp path"); - let long = "a".repeat(255); - for name in [ - "0abc", "1e5", "1-1", ".abc", "a.", "...", "1$", "123$", "0xg", "0b1", "1.5", &long, - ] { - crate::common::run("useradd", &["-P", prefix, "-M", "--", name]).assert_code(0); - assert!( - std::fs::read_to_string(dir.path().join("etc/passwd")) - .expect("read passwd") - .contains(&format!("\n{name}:")), - "useradd should have created {name}" - ); - } - - let too_long = "a".repeat(256); - for name in [ - "123", "0", "00", "0x", "0x1a", "0o7", "-x", ".", "..", "$", "a$b", "a@b", &too_long, - ] { - crate::common::run("useradd", &["-P", prefix, "-M", "--", name]) - .assert_code(19) - .assert_stderr_contains(&format!( - "invalid user name '{name}': use --badname to ignore" - )); - } -} diff --git a/tests/by-util/test_userdel.rs b/tests/by-util/test_userdel.rs index b7bcf2cf..ced9c507 100644 --- a/tests/by-util/test_userdel.rs +++ b/tests/by-util/test_userdel.rs @@ -567,91 +567,3 @@ fn test_last_private_group_in_gshadow_goes_with_the_file() { ); assert!(!etc.join("gshadow").exists()); } - -/// The messages of a run, without the program name each line starts with. -fn messages(out: &crate::common::Output) -> Vec { - out.stderr - .lines() - .map(|l| l.split_once(": ").map_or(l, |(_, rest)| rest).to_string()) - .collect() -} - -/// `userdel -r` says so when the mail spool or the home is not there, mail -/// spool first, on standard error and with exit 0, as Ubuntu 26.04's does. -#[test] -fn test_remove_reports_a_missing_mail_spool_and_home() { - if crate::common::skip_unless_root() { - return; - } - - // Neither is there. - let dir = setup_root_dir(); - let root = dir.path(); - let prefix = root.to_str().expect("non-UTF-8 temp path"); - let out = crate::common::run("userdel", &["-P", prefix, "-r", "testuser"]); - out.assert_code(0); - assert!(out.stdout.is_empty(), "stdout: {:?}", out.stdout); - assert_eq!( - messages(&out), - [ - format!( - "testuser mail spool ({}) not found", - root.join("var/mail/testuser").display() - ), - format!( - "testuser home directory ({}) not found", - root.join("home/testuser").display() - ), - ] - ); - assert!(!read_passwd(&dir).contains("testuser:")); - - // Only the home is missing: the spool goes without a word. - let dir = setup_root_dir(); - let root = dir.path(); - let prefix = root.to_str().expect("non-UTF-8 temp path"); - let spool = root.join("var/mail/testuser"); - std::fs::create_dir_all(root.join("var/mail")).expect("mail dir"); - std::fs::write(&spool, "").expect("spool"); - std::os::unix::fs::chown(&spool, Some(1000), Some(1000)).expect("chown spool"); - let out = crate::common::run("userdel", &["-P", prefix, "-r", "testuser"]); - out.assert_code(0); - assert_eq!( - messages(&out), - [format!( - "testuser home directory ({}) not found", - root.join("home/testuser").display() - )] - ); - assert!(!spool.exists(), "the mail spool should have been removed"); - - // Only the spool is missing: the home goes without a word. - let dir = setup_root_dir(); - let root = dir.path(); - let prefix = root.to_str().expect("non-UTF-8 temp path"); - 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"); - let out = crate::common::run("userdel", &["-P", prefix, "-r", "testuser"]); - out.assert_code(0); - assert_eq!( - messages(&out), - [format!( - "testuser mail spool ({}) not found", - root.join("var/mail/testuser").display() - )] - ); - assert!(!home.exists(), "the home should have been removed"); - - // An empty home field is reported as an empty path, as upstream does. - let dir = setup_root_dir(); - let passwd = read_passwd(&dir).replace("/home/testuser", ""); - std::fs::write(dir.path().join("etc/passwd"), passwd).expect("rewrite passwd"); - let prefix = dir.path().to_str().expect("non-UTF-8 temp path"); - let out = crate::common::run("userdel", &["-P", prefix, "-r", "testuser"]); - out.assert_code(0); - assert_eq!( - messages(&out)[1..], - ["testuser home directory () not found".to_string()] - ); -} diff --git a/tests/by-util/test_usermod.rs b/tests/by-util/test_usermod.rs index 1a61f5e7..b973040e 100644 --- a/tests/by-util/test_usermod.rs +++ b/tests/by-util/test_usermod.rs @@ -2245,36 +2245,3 @@ fn test_selinux_user_needs_a_selinux_kernel() { fn test_selinux_range_needs_selinux_user() { assert_eq!(run(&["usermod", "--selinux-range", "s0", "root"]), 2); } - -/// `usermod -l` takes the names upstream's `useradd` takes: a leading digit -/// is fine, a name that reads as a number is not. -#[test] -fn test_rename_follows_upstream_name_rules() { - if crate::common::skip_unless_root() { - return; - } - - let dir = setup_prefix( - "root:x:0:0:root:/root:/bin/bash\ntestuser:x:1000:1000::/home/testuser:/bin/sh\n", - "root:!:19000:0:99999:7:::\ntestuser:!:19000:0:99999:7:::\n", - "root:x:0:\n", - ); - let prefix = dir.path().to_str().expect("non-UTF-8 temp path"); - let mut current = String::from("testuser"); - for name in ["0abc", "1e5", ".abc", "a.", "123$", &"b".repeat(255)] { - crate::common::run("usermod", &["-P", prefix, "-l", name, ¤t]).assert_code(0); - assert!( - read_passwd(&dir).contains(&format!("\n{name}:x:1000:")), - "usermod -l should have renamed {current} to {name}" - ); - current = name.to_string(); - } - - for name in ["123", "0x1a", "0o7", "-x", ".", "a@b", &"b".repeat(256)] { - crate::common::run("usermod", &["-P", prefix, "-l", name, ¤t]) - .assert_code(3) - .assert_stderr_contains(&format!( - "invalid user name '{name}': use --badname to ignore" - )); - } -}