diff --git a/CHANGELOG.md b/CHANGELOG.md index 3462bf39..ab2a04ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- `chage -E`/`-d`, `usermod -e` and `useradd -e` take the date forms upstream reads + with its date parser, not only `YYYY-MM-DD`: `01/02/2030`, `2030/01/02`, `1/2/30`, + `2 Jan 2030`, `January 2, 2030`, `tomorrow`, with any time of day dropped. They are + read with `parse_datetime`, a new dependency of `shadow-core`. `YYYY-MM-DD`, a day + 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) + - `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/Cargo.lock b/Cargo.lock index afd2c31b..e9c6b122 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -77,6 +77,12 @@ dependencies = [ "serde", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.1" @@ -194,6 +200,37 @@ dependencies = [ "libc", ] +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -357,6 +394,60 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "jiff" +version = "0.2.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "landlock" version = "0.4.7" @@ -380,6 +471,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" @@ -392,7 +489,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "cfg_aliases", "libc", @@ -428,6 +525,32 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "parse_datetime" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb51967a779ef73b125a243688e53e4bb2474f91cae72734ee5051e857fb2645" +dependencies = [ + "jiff", + "num-traits", + "winnow", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -454,7 +577,7 @@ checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set", "bit-vec", - "bitflags", + "bitflags 2.13.1", "chacha20", "core_detect", "num-traits", @@ -530,7 +653,7 @@ version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.13.1", "errno", "libc", "linux-raw-sys", @@ -1047,8 +1170,10 @@ name = "uu_shadow_core" version = "0.6.0" dependencies = [ "clap", + "jiff", "landlock", "libc", + "parse_datetime", "proptest", "rustix", "subtle", diff --git a/Cargo.toml b/Cargo.toml index 9aaa23aa..15650575 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,10 @@ uucore = "0.12" # Error handling thiserror = "2" +# Dates +parse_datetime = "0.17" +jiff = { version = "0.2", default-features = false, features = ["std"] } + # Unix/Linux rustix = { version = "1", features = ["event", "fs", "param", "process", "pty", "rand", "termios"] } libc = "0.2" diff --git a/docs/man/chage.1.md b/docs/man/chage.1.md index f5f2cbdb..1885f56a 100644 --- a/docs/man/chage.1.md +++ b/docs/man/chage.1.md @@ -33,12 +33,17 @@ nothing is written. This is for root only. **-d**, **--lastday** *LAST_DAY* : Record *LAST_DAY* as the date of the last password change. Accepts - **YYYY-MM-DD** or a number of days since the epoch. **-1** clears the - field. A last day of **0** forces a password change at the next login. + **YYYY-MM-DD**, a number of days since the epoch, or another date form + **date**(1) **-d** reads, such as **01/02/2030**, **2030/01/02**, + **2 Jan 2030**, **January 2, 2030** or **tomorrow**, read in the local time + zone with any time of day dropped. A **YYYY-MM-DD** date that does not + exist, such as **2025-02-29**, is refused rather than rolled over, and so is + a date before 1970. **-1** clears the field. A last day of **0** forces a + password change at the next login. **-E**, **--expiredate** *EXPIRE_DATE* -: Expire the account on *EXPIRE_DATE*, in the same two forms. **-1** removes - the expiry. An expired account is refused a login even with a valid +: Expire the account on *EXPIRE_DATE*, in the same forms as **-d**. **-1** + removes the expiry. An expired account is refused a login even with a valid password. **-I**, **--inactive** *INACTIVE* diff --git a/docs/man/useradd.8.md b/docs/man/useradd.8.md index 11b4c285..4d33b2ec 100644 --- a/docs/man/useradd.8.md +++ b/docs/man/useradd.8.md @@ -37,7 +37,9 @@ default values used for creating new accounts. **-e**, **--expiredate** *EXPIRE_DATE* : Set the expiration date of the new account (YYYY-MM-DD). **-1** leaves it - unset. + unset. A number of days since the epoch, and the other date forms + **date**(1) **-d** reads (**01/02/2030**, **2 Jan 2030**, **tomorrow**), + are accepted as for **chage**(1) **-E**. **-f**, **--inactive** *INACTIVE* : Set the password inactivity period of the new account. **-1** leaves it diff --git a/docs/man/usermod.8.md b/docs/man/usermod.8.md index bccbfe51..d5cbe524 100644 --- a/docs/man/usermod.8.md +++ b/docs/man/usermod.8.md @@ -33,7 +33,9 @@ changes that are specified on the command line. **-e**, **--expiredate** *EXPIRE_DATE* : Set the account expiration date, as YYYY-MM-DD or a number of days since the - epoch. **-1** removes the date. + epoch, or another date form **date**(1) **-d** reads (**01/02/2030**, + **2 Jan 2030**, **tomorrow**), as for **chage**(1) **-E**. **-1** removes the + date. **-f**, **--inactive** *INACTIVE* : Set the password inactive period, in days. **-1** removes it. diff --git a/src/shadow-core/Cargo.toml b/src/shadow-core/Cargo.toml index a5a8876a..39f01381 100644 --- a/src/shadow-core/Cargo.toml +++ b/src/shadow-core/Cargo.toml @@ -19,7 +19,12 @@ path = "src/lib.rs" [dependencies] clap = { workspace = true } +# `Zoned::now()` reads the local zone: `tz-system` reads TZ and /etc/localtime, +# and `tzdb-zoneinfo` resolves a zone name such as TZ=Europe/Paris against +# /usr/share/zoneinfo. Without them the zone silently behaves as UTC. +jiff = { workspace = true, features = ["tz-system", "tzdb-zoneinfo"] } libc = { workspace = true } +parse_datetime = { workspace = true } rustix = { workspace = true } thiserror = { workspace = true } uucore = { workspace = true } diff --git a/src/shadow-core/src/date.rs b/src/shadow-core/src/date.rs index deca4295..401b5350 100644 --- a/src/shadow-core/src/date.rs +++ b/src/shadow-core/src/date.rs @@ -6,8 +6,9 @@ //! Calendar arithmetic for the account-expiry and aging fields. //! //! `/etc/shadow` stores those fields as days since the Unix epoch, while the -//! tools accept the `YYYY-MM-DD` form their man pages document. Both live -//! here so `useradd`, `usermod` and `chage` agree on what a date is. +//! tools accept the `YYYY-MM-DD` form their man pages document and the other +//! forms GNU `date -d` reads. Both live here so `useradd`, `usermod` and +//! `chage` agree on what a date is. use crate::error::ShadowError; @@ -56,6 +57,11 @@ pub fn days_in_month(year: i64, month: i64) -> i64 { /// expressed in days since the epoch. Impossible dates (month 13, 31 April, /// 29 February in a common year) are rejected rather than normalised. /// +/// Anything else goes to the general date parser, which reads what GNU +/// `date -d` reads, as upstream does: `01/02/2030`, `2030/01/02`, `1/2/30`, +/// `2 Jan 2030`, `January 2, 2030`, `tomorrow`. A time of day is dropped, and +/// a date before 1970 is rejected like a pre-epoch `YYYY-MM-DD`. +/// /// # Errors /// /// Returns `ShadowError::Validation` describing the malformed value. @@ -64,6 +70,18 @@ pub fn parse_expire_date(s: &str) -> Result, ShadowError> { return Ok(None); } + // Every value accepted before the general parser was added is made of + // digits, signs and dashes, and keeps its strict reading here. The + // general parser would take "2024-02" for a time with a UTC offset and + // roll 2023-02-29 over into March; a malformed day count or date stays + // an error instead. + if !s + .bytes() + .all(|b| b.is_ascii_digit() || b == b'-' || b == b'+') + { + return parse_free_form_date(s, jiff::Zoned::now()); + } + // A bare integer is already days since the epoch. if !s.contains('-') { return s.parse::().map(Some).map_err(|_| { @@ -100,6 +118,31 @@ pub fn parse_expire_date(s: &str) -> Result, ShadowError> { Ok(Some(days_from_civil(year, month, day))) } +/// Read a date in any form GNU `date -d` takes, in the time zone of `now`, +/// and return its day number. The time of day is dropped: the field holds a +/// day. Relative forms such as `tomorrow` count from `now`, which the caller +/// reads once so that every relative form is resolved against one instant. +fn parse_free_form_date(s: &str, now: jiff::Zoned) -> Result, ShadowError> { + let invalid = || ShadowError::Validation(format!("invalid date '{s}'").into()); + + let zoned = parse_datetime::parse_datetime_at_date(now, s) + .map_err(|_| invalid())? + .into_zoned() + .ok_or_else(invalid)?; + let date = zoned.date(); + let year = i64::from(date.year()); + if year < 1970 { + return Err(ShadowError::Validation( + format!("invalid date '{s}' (before 1970-01-01)").into(), + )); + } + Ok(Some(days_from_civil( + year, + i64::from(date.month()), + i64::from(date.day()), + ))) +} + /// The range of day counts this module will turn back into a calendar date. /// /// The aging fields are read from a file anyone with write access to @@ -216,6 +259,99 @@ mod tests { assert_eq!(parse_expire_date("19782").unwrap(), Some(19782)); } + #[test] + fn test_parse_expire_date_accepts_the_upstream_date_forms() { + // Upstream reads every one of these as 2030-01-02, day 21916. + for form in [ + "01/02/2030", + "2030/01/02", + "1/2/30", + "2 Jan 2030", + "January 2, 2030", + // A time of day is dropped: the field holds a day. + "2030-01-02 23:30", + "2030-01-02 00:30", + ] { + assert_eq!( + parse_expire_date(form).unwrap(), + Some(21916), + "'{form}' should be 2030-01-02" + ); + } + } + + #[test] + fn test_parse_expire_date_accepts_relative_dates() { + // Relative forms are resolved against one fixed instant, so the test + // does not depend on when it runs. 23:59:59 makes a parser that read + // the clock again, or kept the time of day, land on the wrong day. + let now = jiff::civil::date(2030, 1, 2) + .at(23, 59, 59, 0) + .to_zoned(jiff::tz::TimeZone::UTC) + .unwrap(); + // 2030-01-02 is day 21916. + for (form, day) in [ + ("today", 21916), + ("now", 21916), + ("tomorrow", 21917), + ("yesterday", 21915), + ("next week", 21923), + ("+3 days", 21919), + ] { + assert_eq!( + parse_free_form_date(form, now.clone()).unwrap(), + Some(day), + "'{form}' from 2030-01-02 23:59:59" + ); + } + } + + #[test] + fn test_parse_expire_date_reads_the_clock_for_relative_dates() { + // The public entry point resolves "today" against the system clock. + // The local date is within a day of the UTC date at any instant. If + // a UTC midnight falls between the two readings, the local date read + // just before it is the old UTC day or the new one, so the bound + // holds whenever this runs. + let today = parse_expire_date("today").unwrap().unwrap(); + let utc_today = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + / 86_400; + let utc_today = i64::try_from(utc_today).unwrap(); + assert!( + (today - utc_today).abs() <= 1, + "today {today}, UTC {utc_today}" + ); + } + + #[test] + fn test_parse_expire_date_numeric_forms_are_unchanged() { + // Anything made only of digits and dashes is read as before: a day + // count or a strict YYYY-MM-DD, never handed to the general parser, + // which would read "2024-02" as a time with a UTC offset and roll + // impossible dates over. + assert_eq!(parse_expire_date("2030-1-2").unwrap(), Some(21916)); + assert_eq!(parse_expire_date("0").unwrap(), Some(0)); + for bad in ["-5", "99999999999999999999", "2024-02", "2023-02-29"] { + assert!( + parse_expire_date(bad).is_err(), + "'{bad}' should be rejected" + ); + } + } + + #[test] + fn test_parse_expire_date_rejects_what_no_parser_reads() { + for bad in ["garbage", "2030-01-02T25:00", "1969/12/31", "31 Dec 1969"] { + assert!( + parse_expire_date(bad).is_err(), + "'{bad}' should be rejected" + ); + } + } + #[test] fn test_civil_from_days_round_trips() { for (y, m, d) in [ diff --git a/src/uu/chage/src/chage.rs b/src/uu/chage/src/chage.rs index 7f616dbb..e67bf88d 100644 --- a/src/uu/chage/src/chage.rs +++ b/src/uu/chage/src/chage.rs @@ -114,7 +114,8 @@ impl UError for ChageError { // Date parsing // --------------------------------------------------------------------------- -/// Parse a date argument: `YYYY-MM-DD`, days since the epoch, or `-1`. +/// Parse a date argument: `YYYY-MM-DD`, days since the epoch, another form +/// `date -d` reads (`01/02/2030`, `tomorrow`), or `-1`. /// /// `-1` reaches the caller as `-1` rather than `None`, because chage(1) uses /// it to clear the field and the caller has to tell "clear it" from "leave it diff --git a/src/uu/useradd/src/useradd.rs b/src/uu/useradd/src/useradd.rs index fe6537a3..a5359e08 100644 --- a/src/uu/useradd/src/useradd.rs +++ b/src/uu/useradd/src/useradd.rs @@ -1591,8 +1591,15 @@ mod tests { } #[test] - fn test_parse_expire_date_invalid_format() { - assert!(parse_expire_date("2025/01/01").is_err()); + fn test_parse_expire_date_other_forms() { + // Upstream's date parser reads these too. + assert_eq!(parse_expire_date("2025/01/01").expect("Y/M/D"), Some(20089)); + assert_eq!(parse_expire_date("01/01/2025").expect("M/D/Y"), Some(20089)); + assert_eq!( + parse_expire_date("1 Jan 2025").expect("D Mon Y"), + Some(20089) + ); + assert!(parse_expire_date("not a date").is_err()); } #[test] diff --git a/src/uu/usermod/src/usermod.rs b/src/uu/usermod/src/usermod.rs index fcdd57d4..5c47c088 100644 --- a/src/uu/usermod/src/usermod.rs +++ b/src/uu/usermod/src/usermod.rs @@ -679,7 +679,8 @@ fn check_value( return Err(bad("homedir must be an absolute path".into())); } } - // usermod(8) documents YYYY-MM-DD; days since the epoch stays accepted. + // usermod(8) documents YYYY-MM-DD; days since the epoch and the other + // forms `date -d` reads are accepted too, as upstream. options::EXPIREDATE => { values.expire_date = Some(shadow_core::date::parse_expire_date(value).map_err(|e| bad(e.to_string()))?); diff --git a/tests/by-util/test_chage.rs b/tests/by-util/test_chage.rs index 8d348172..29eb5db1 100644 --- a/tests/by-util/test_chage.rs +++ b/tests/by-util/test_chage.rs @@ -158,6 +158,30 @@ fn test_each_field_option_writes_its_own_field() { } } +/// -E and -d take the date forms upstream's date parser reads, not only +/// YYYY-MM-DD. +#[test] +fn test_dates_in_other_forms_are_accepted() { + if crate::common::skip_unless_root() { + return; + } + for date in [ + "01/02/2030", + "2030/01/02", + "1/2/30", + "2 Jan 2030", + "January 2, 2030", + ] { + let dir = prefix("testuser:$6$hash:19500:0:99999:7:::\n"); + chage(&dir, &["-E", date, "-d", date, "testuser"]).assert_code(0); + assert_eq!( + shadow_line(&dir), + "testuser:$6$hash:21916:0:99999:7::21916:", + "after chage -E/-d '{date}'" + ); + } +} + /// -1 clears a field rather than storing a negative number. #[test] fn test_minus_one_clears_a_field() { diff --git a/tests/by-util/test_useradd.rs b/tests/by-util/test_useradd.rs index 3b97e59d..79ecb378 100644 --- a/tests/by-util/test_useradd.rs +++ b/tests/by-util/test_useradd.rs @@ -624,6 +624,41 @@ fn test_create_user_with_key_gid_range_for_user_group() { ); } +/// -e takes the date forms upstream's date parser reads, as well as +/// YYYY-MM-DD and a day count, and -1 leaves the expire field blank. +#[test] +fn test_expiredate_accepts_other_date_forms() { + if crate::common::skip_unless_root() { + return; + } + + // 2030-01-02 is 21916 days after the epoch. + for (date, expire) in [ + ("01/02/2030", "21916"), + ("2030/01/02", "21916"), + ("1/2/30", "21916"), + ("2 Jan 2030", "21916"), + ("January 2, 2030", "21916"), + ("2030-01-02", "21916"), + ("21916", "21916"), + ("-1", ""), + ] { + let dir = setup_root_dir(); + let code = run_with_root(&dir, &["-e", date, "expuser"]); + assert_eq!(code, 0, "useradd -e '{date}' must be accepted"); + + let shadow = read_shadow(&dir); + let line = shadow + .lines() + .find(|l| l.starts_with("expuser:")) + .expect("expuser shadow entry"); + // name:passwd:lstchg:min:max:warn:inactive:expire:reserved + let fields: Vec<&str> = line.split(':').collect(); + assert_eq!(fields.len(), 9, "after useradd -e '{date}': {line}"); + assert_eq!(fields[7], expire, "after useradd -e '{date}': {line}"); + } +} + #[test] fn test_create_user_with_key_pass_max_days() { if crate::common::skip_unless_root() { diff --git a/tests/by-util/test_usermod.rs b/tests/by-util/test_usermod.rs index b973040e..675bfbb6 100644 --- a/tests/by-util/test_usermod.rs +++ b/tests/by-util/test_usermod.rs @@ -1053,6 +1053,35 @@ fn test_expiredate_accepts_iso_date() { ); } +#[test] +fn test_expiredate_accepts_other_date_forms() { + if crate::common::skip_unless_root() { + return; + } + + for date in [ + "01/02/2030", + "2030/01/02", + "1/2/30", + "2 Jan 2030", + "January 2, 2030", + ] { + let dir = setup_prefix( + "alice:x:1000:1000:Alice:/home/alice:/bin/bash\n", + "alice:$6$h:19500:0:99999:7:::\n", + "alice:x:1000:\n", + ); + // 2030-01-02 is 21916 days after the epoch. + let code = run_with_prefix(&dir, &["-e", date, "alice"]); + assert_eq!(code, 0, "usermod -e '{date}' must be accepted"); + assert_eq!( + read_shadow(&dir).trim_end(), + "alice:$6$h:19500:0:99999:7::21916:", + "after usermod -e '{date}'" + ); + } +} + #[test] fn test_negative_one_blanks_inactive_and_expiredate() { if crate::common::skip_unless_root() {