Skip to content
Merged
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/man/groupadd.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
5 changes: 5 additions & 0 deletions docs/man/groupmod.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
7 changes: 7 additions & 0 deletions docs/man/newusers.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
8 changes: 8 additions & 0 deletions docs/man/useradd.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
5 changes: 5 additions & 0 deletions docs/man/usermod.8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
7 changes: 4 additions & 3 deletions fuzz/fuzz_targets/fuzz_validate_username.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
214 changes: 62 additions & 152 deletions src/shadow-core/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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.
Expand Down Expand Up @@ -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))));
}

// -------------------------------------------------------------------
Expand Down
8 changes: 6 additions & 2 deletions src/uu/groupadd/src/groupadd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
12 changes: 8 additions & 4 deletions src/uu/groupmod/src/groupmod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
Loading