diff --git a/CHANGELOG.md b/CHANGELOG.md index cd8e761e..9cb8a82e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 count and `-1` behave as before, and an impossible `YYYY-MM-DD` such as `2023-02-29` is still refused where upstream rolls it over (#365) +- `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) + - `chfn` writes the "other" GECOS sub-field, and the comma before it, only when it is not empty, as upstream does. `chfn -f NewName` on an empty GECOS wrote `NewName,,,,` instead of `NewName,,,`, so every change left a trailing empty field diff --git a/docs/man/groupadd.8.md b/docs/man/groupadd.8.md index 9c55f7fe..7b0b5bf0 100644 --- a/docs/man/groupadd.8.md +++ b/docs/man/groupadd.8.md @@ -54,6 +54,14 @@ 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 7cf4adc4..181f9554 100644 --- a/docs/man/groupmod.8.md +++ b/docs/man/groupmod.8.md @@ -46,6 +46,11 @@ 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 name it +refuses is exit status 3. + ## EXIT STATUS **0** diff --git a/docs/man/newusers.8.md b/docs/man/newusers.8.md index 56c1d283..9c623788 100644 --- a/docs/man/newusers.8.md +++ b/docs/man/newusers.8.md @@ -67,6 +67,13 @@ 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 line that creates a group of +the user's own name, with an empty or new numeric GID field, also needs a group +name that follows the rule of **groupadd**(8). 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 4d33b2ec..11ec299f 100644 --- a/docs/man/useradd.8.md +++ b/docs/man/useradd.8.md @@ -109,6 +109,14 @@ 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/usermod.8.md b/docs/man/usermod.8.md index d5cbe524..f50cbc91 100644 --- a/docs/man/usermod.8.md +++ b/docs/man/usermod.8.md @@ -139,6 +139,11 @@ 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 name it +refuses 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 260a7424..b3e88492 100644 --- a/fuzz/fuzz_targets/fuzz_validate_username.rs +++ b/fuzz/fuzz_targets/fuzz_validate_username.rs @@ -5,14 +5,15 @@ //! Fuzz target for username validation. //! -//! Ensures `validate_username` never panics on arbitrary string input. +//! Ensures the user and group name checks never panic 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 — errors are fine. - let _ = shadow_core::validate::validate_username(s); + // 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); } }); diff --git a/src/shadow-core/src/validate.rs b/src/shadow-core/src/validate.rs index edcc4020..63337877 100644 --- a/src/shadow-core/src/validate.rs +++ b/src/shadow-core/src/validate.rs @@ -10,18 +10,22 @@ use crate::error::ShadowError; -/// Maximum username length on Linux. -const MAX_USERNAME_LEN: usize = 32; +/// 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; /// 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. /// -/// 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`). +/// 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. #[must_use] pub fn is_valid_account_name(name: &str, max_len: usize) -> bool { let body = name.strip_suffix('$').unwrap_or(name); @@ -44,67 +48,31 @@ pub fn is_valid_account_name(name: &str, max_len: usize) -> bool { .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')) } -/// Validate a username or group name. -/// -/// 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(), - )); - } - - // 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(), - )); - } +/// 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) +} - if body.chars().all(|c| c == '.') { - return Err(ShadowError::Validation( - format!("username '{name}' must not consist only of periods").into(), - )); - } +/// Whether `useradd`, `usermod -l` and `newusers` may give a user this name, +/// without `--badname`. +/// +/// 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) +} - Ok(()) +/// 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) } /// Reject a value that would corrupt a colon-separated account file. @@ -156,95 +124,37 @@ 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_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()); + 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))); } - // upstream shadow accepts these (verified against useradd(8)); refusing - // them made us reject accounts that exist on real systems. + /// Groups follow the user rule but stop at 32 characters, `$` included. #[test] - 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()); + 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)))); } // ------------------------------------------------------------------- diff --git a/src/uu/groupadd/src/groupadd.rs b/src/uu/groupadd/src/groupadd.rs index 4ba46130..3bc4e25e 100644 --- a/src/uu/groupadd/src/groupadd.rs +++ b/src/uu/groupadd/src/groupadd.rs @@ -149,8 +149,12 @@ fn do_groupadd(matches: &clap::ArgMatches) -> UResult<()> { } // Validate the group name. - validate::validate_username(&group_name) - .map_err(|e| GroupaddError::BadArgument(format!("{e}")))?; + if !validate::is_valid_group_name(&group_name) { + return Err(GroupaddError::BadArgument(format!( + "'{group_name}' is not a valid group name" + )) + .into()); + } let group_path = root.group_path(); diff --git a/src/uu/groupmod/src/groupmod.rs b/src/uu/groupmod/src/groupmod.rs index c99cd0db..de2ef9c6 100644 --- a/src/uu/groupmod/src/groupmod.rs +++ b/src/uu/groupmod/src/groupmod.rs @@ -125,9 +125,10 @@ 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::validate_username(name) - .map_err(|e| GroupmodError::BadArgument(format!("{e}")))?; + if let Some(name) = new_name + && !shadow_core::validate::is_valid_group_name(name) + { + return Err(GroupmodError::BadArgument(format!("invalid group name '{name}'")).into()); } // Parse new GID if provided. u32::MAX is (gid_t)-1, the "no change" @@ -317,7 +318,10 @@ pub fn uu_app() -> Command { .short('n') .long("new-name") .value_name("NEW_GROUP") - .help("Rename the group to 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), ) .arg( Arg::new(options::NON_UNIQUE) diff --git a/src/uu/grpck/src/grpck.rs b/src/uu/grpck/src/grpck.rs index 8f25b45e..9f0948b1 100644 --- a/src/uu/grpck/src/grpck.rs +++ b/src/uu/grpck/src/grpck.rs @@ -145,9 +145,6 @@ 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| { @@ -287,7 +284,10 @@ 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, MAX_GROUP_NAME_LEN) { + if !shadow_core::validate::is_valid_account_name( + &entry.name, + shadow_core::validate::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 09d6100d..ccf1ca74 100644 --- a/src/uu/newusers/src/newusers.rs +++ b/src/uu/newusers/src/newusers.rs @@ -171,8 +171,10 @@ fn validate(line: &Line, relaxed: bool) -> Result<(), NewusersError> { line.number, line.name ))); } - } else { - shadow_core::validate::validate_username(&line.name).map_err(bad)?; + } 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")); } shadow_core::validate::validate_field("GECOS", &line.gecos).map_err(bad)?; @@ -237,7 +239,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { return Ok(()); } - apply(&root, &defs, &lines, system, method) + apply(&root, &defs, &lines, system, relaxed, method) } /// Build the clap `Command` for `newusers`. @@ -303,6 +305,7 @@ 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 @@ -329,7 +332,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_min, gid_max) = uid_alloc::gid_range(defs, system); + let gid_range = uid_alloc::gid_range(defs, system); let mut homes = Vec::new(); @@ -346,7 +349,7 @@ fn apply( .ok_or_else(|| line_error(line, &format!("invalid user ID '{given}'")))?, }; - let gid = resolve_gid(&mut group, line, uid, gid_min, gid_max, system, scope)?; + let gid = resolve_gid(&mut group, line, uid, gid_range, system, scope, relaxed)?; match existing { Some(i) => { @@ -420,10 +423,10 @@ fn resolve_gid( group: &mut LockedFile, line: &Line, uid: u32, - gid_min: u32, - gid_max: u32, + (gid_min, gid_max): (u32, 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 @@ -431,7 +434,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.name, gid); + push_group(group, line, gid, relaxed)?; } return Ok(gid); } @@ -465,19 +468,33 @@ fn resolve_gid( } else { uid }; - push_group(group, &line.name, gid); + push_group(group, line, gid, relaxed)?; Ok(gid) } -/// 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) { +/// 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")); + } group.entries_mut().push(GroupEntry { - name: name.to_string(), + name: line.name.clone(), passwd: "x".to_string(), gid, members: Vec::new(), }); + Ok(()) } /// Write the account's hash and aging fields. @@ -653,10 +670,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 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:::"] { + // 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:::"] { 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 84366f6f..314f3de9 100644 --- a/src/uu/pwck/src/pwck.rs +++ b/src/uu/pwck/src/pwck.rs @@ -171,9 +171,6 @@ 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| { @@ -492,7 +489,10 @@ fn check_passwd_entries( )); errors += 1; } else if !badname - && !shadow_core::validate::is_valid_account_name(&entry.name, MAX_USER_NAME_LEN) + && !shadow_core::validate::is_valid_account_name( + &entry.name, + shadow_core::validate::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 a5359e08..05a1ae9a 100644 --- a/src/uu/useradd/src/useradd.rs +++ b/src/uu/useradd/src/useradd.rs @@ -595,9 +595,12 @@ fn do_useradd(opts: &UseraddOptions) -> UResult<()> { } validate::validate_field("login name", &opts.login) .map_err(|e| UseraddError::CannotUpdatePasswd(e.to_string()))?; - } else { - validate::validate_username(&opts.login) - .map_err(|e| UseraddError::BadName(format!("{e}")))?; + } else if !validate::is_valid_user_name(&opts.login) { + return Err(UseraddError::BadName(format!( + "invalid user name '{}': use --badname to ignore", + opts.login + )) + .into()); } // Step 2: Block signals for the lock→write critical section only. diff --git a/src/uu/usermod/src/usermod.rs b/src/uu/usermod/src/usermod.rs index 5c47c088..f5f4e082 100644 --- a/src/uu/usermod/src/usermod.rs +++ b/src/uu/usermod/src/usermod.rs @@ -716,7 +716,7 @@ fn check_value( if badname { validate::validate_field("login name", value) .map_err(|e| bad(format!("invalid login name: {e}")))?; - } else if validate::validate_username(value).is_err() { + } else if !validate::is_valid_user_name(value) { 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 d04dac5c..be2920c9 100644 --- a/tests/by-util/test_fuzz_corpus.rs +++ b/tests/by-util/test_fuzz_corpus.rs @@ -113,6 +113,11 @@ fn test_subid_corpus_round_trips() { #[test] fn test_username_corpus_is_answered() { for text in inputs("fuzz_validate_username") { - let _ = shadow_core::validate::validate_username(&text); + // 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" + ); } } diff --git a/tests/by-util/test_groupadd.rs b/tests/by-util/test_groupadd.rs index 867d9d1e..79cdf6e3 100644 --- a/tests/by-util/test_groupadd.rs +++ b/tests/by-util/test_groupadd.rs @@ -443,3 +443,50 @@ 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 d0e3da31..2c38cdac 100644 --- a/tests/by-util/test_groupmod.rs +++ b/tests/by-util/test_groupmod.rs @@ -505,3 +505,33 @@ 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 c819dd5b..32389f99 100644 --- a/tests/by-util/test_newusers.rs +++ b/tests/by-util/test_newusers.rs @@ -418,3 +418,88 @@ 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"); +} + +/// Where `useradd -U` creates a 33-character group, `newusers` holds the +/// group it creates for a line to the group rule, as upstream does: the line +/// is refused, exit 1, and nothing is written. +#[test] +fn test_refuses_a_33_character_group() { + if skip_unless_root() { + return; + } + + let dir = prefix(); + let before: Vec = ["passwd", "shadow", "group"] + .iter() + .map(|f| read(&dir, f)) + .collect(); + let name = "a".repeat(33); + let out = newusers(&dir, &[], &format!("{name}:pw:::::/bin/sh\n")); + out.assert_code(1); + assert_eq!( + messages(&out), + [ + format!("invalid group name '{name}'"), + "line 1: can't create group".to_string(), + ] + ); + let after: Vec = ["passwd", "shadow", "group"] + .iter() + .map(|f| read(&dir, f)) + .collect(); + assert_eq!(before, after, "nothing should be written"); +} diff --git a/tests/by-util/test_useradd.rs b/tests/by-util/test_useradd.rs index 79ecb378..6318d87f 100644 --- a/tests/by-util/test_useradd.rs +++ b/tests/by-util/test_useradd.rs @@ -1084,3 +1084,59 @@ 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" + )); + } +} + +/// A user name may be longer than a group name, but `useradd -U` does not +/// hold the group it creates to the 32-character group rule: Ubuntu 26.04's +/// `useradd -U` with a 33-character name creates the user and a group of the +/// same 33-character name. +#[test] +fn test_user_group_takes_a_33_character_name() { + if crate::common::skip_unless_root() { + return; + } + + let dir = setup_root_dir(); + let name = "a".repeat(33); + assert_eq!(run_with_root(&dir, &["-M", "-U", &name]), 0); + let passwd = read_passwd(&dir); + assert!(passwd.contains(&format!("\n{name}:x:")), "got: {passwd}"); + let group = read_group(&dir); + assert!(group.contains(&format!("\n{name}:x:")), "got: {group}"); +} diff --git a/tests/by-util/test_usermod.rs b/tests/by-util/test_usermod.rs index 675bfbb6..a8bf6670 100644 --- a/tests/by-util/test_usermod.rs +++ b/tests/by-util/test_usermod.rs @@ -2274,3 +2274,36 @@ 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" + )); + } +}