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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `chage LOGIN` takes a line of blanks as an answer that does not parse, exit 1 with
nothing written, as upstream does; only an empty line keeps a value (#387)

- A lock file left by shadow-utils (the pid followed by a NUL) is read as held, not
deleted as stale, and ours are written the same way (#399)

- `userdel` removes a user whose private group is the last entry in /etc/gshadow.
It exited 10 with the account already gone from /etc/passwd

Expand Down
127 changes: 121 additions & 6 deletions src/shadow-core/src/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
//!
//! * a `.lock` file (e.g. `/etc/passwd.lock`), created atomically with
//! `O_CREAT | O_EXCL` via the classic link trick and carrying the holder's
//! PID for stale detection. This is what shadow-utils uses.
//! PID for stale detection. This is what shadow-utils uses, and the content
//! is byte-identical to its: the decimal PID followed by one NUL byte.
//! * `/etc/.pwd.lock`, held with an `fcntl` open-file-description write lock —
//! the lock `lckpwdf(3)` provides and that `vipw`, `pwconv`, `libuser`,
//! `systemd-sysusers` and `pam_unix` all take. Without it a concurrent
Expand Down Expand Up @@ -322,8 +323,10 @@ fn write_pid_file(tmp_path: &Path) -> Result<(), ShadowError> {
}
};

// The PID and a terminating NUL, byte for byte what shadow-utils writes,
// so its tools read our locks exactly as they read their own.
let pid = rustix::process::getpid();
write!(file, "{pid}").map_err(|e| {
write!(file, "{pid}\0").map_err(|e| {
ShadowError::Lock(format!("cannot write {}: {e}", tmp_path.display()).into())
})?;

Expand All @@ -337,13 +340,27 @@ fn write_pid_file(tmp_path: &Path) -> Result<(), ShadowError> {
Ok(())
}

/// The holder PID recorded in a lock file's contents.
///
/// A lock is a PID optionally followed by a NUL and/or whitespace in any
/// order: shadow-utils terminates it with a NUL (`"633201\0"`), older
/// shadow-rs wrote it bare, and a hand-made one may end in a newline.
/// Anything else, including a NUL before or inside the digits, is `None`.
fn parse_lock_pid(contents: &str) -> Option<i32> {
contents
.trim_start()
.trim_end_matches(|c: char| c == '\0' || c.is_whitespace())
.parse()
.ok()
}

/// Check if an existing lock file is stale (held by a dead process).
fn is_stale_lock(lock_path: &Path) -> bool {
let Ok(contents) = fs::read_to_string(lock_path) else {
return false;
};

let Ok(pid) = contents.trim().parse::<i32>() else {
let Some(pid) = parse_lock_pid(&contents) else {
// Cannot parse PID — treat as stale.
return true;
};
Expand Down Expand Up @@ -432,6 +449,54 @@ mod tests {
lock.release().unwrap();
}

// shadow-utils writes its locks as the pid followed by a NUL byte
// (`/etc/passwd.lock` held by pid 83 reads `8 3 \0`). A lock in that
// form whose holder is alive must be waited on, not deleted as stale.
#[test]
fn test_live_nul_terminated_lock_is_not_stale() {
let dir = tempfile::tempdir().unwrap();
let lock_path = dir.path().join("test_file.lock");
let live = format!("{}\0", std::process::id());
fs::write(&lock_path, &live).unwrap();

assert!(!is_stale_lock(&lock_path));
}

#[test]
fn test_live_nul_terminated_lock_excludes() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("test_file");
fs::write(&file, "data").unwrap();
let lock_path = dir.path().join("test_file.lock");
let live = format!("{}\0", std::process::id());
fs::write(&lock_path, &live).unwrap();

let result = FileLock::acquire_with_timeout(&file, Duration::from_millis(300));
assert!(
result.is_err(),
"a lock held by a live process must not be taken over"
);
assert_eq!(
fs::read(&lock_path).unwrap(),
live.as_bytes(),
"the holder's lock file must be left in place"
);
}

// The same lock form, once its holder is gone, is stale and cleaned up.
#[test]
fn test_dead_nul_terminated_lock_is_stale() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("test_file");
fs::write(&file, "data").unwrap();
let lock_path = dir.path().join("test_file.lock");
fs::write(&lock_path, "999999999\0").unwrap();

assert!(is_stale_lock(&lock_path));
let lock = FileLock::acquire_with_timeout(&file, Duration::from_millis(300)).unwrap();
lock.release().unwrap();
}

#[test]
fn test_lock_file_has_cloexec() {
use std::os::unix::io::AsFd;
Expand Down Expand Up @@ -540,10 +605,60 @@ mod tests {
fs::write(&file, "data").unwrap();

let lock = FileLock::acquire(&file).unwrap();
let contents = fs::read_to_string(&lock.lock_path).unwrap();
let pid: i32 = contents.trim().parse().unwrap();
assert_eq!(pid, i32::try_from(std::process::id()).unwrap());
// Byte-identical to shadow-utils: the decimal PID and one NUL.
assert_eq!(
fs::read(&lock.lock_path).unwrap(),
format!("{}\0", std::process::id()).into_bytes()
);

lock.release().unwrap();
}

#[test]
fn test_parse_lock_pid_accepted_forms() {
// shadow-utils: PID and a NUL.
assert_eq!(parse_lock_pid("633201\0"), Some(633_201));
// Bare PID, as shadow-rs used to write it.
assert_eq!(parse_lock_pid("633201"), Some(633_201));
// Trailing newline, as `echo $$ > file.lock` leaves it.
assert_eq!(parse_lock_pid("633201\n"), Some(633_201));
// NUL and whitespace mixed in the tail, and leading whitespace as
// before.
assert_eq!(parse_lock_pid("633201\0\n"), Some(633_201));
assert_eq!(parse_lock_pid("633201\n\0"), Some(633_201));
assert_eq!(parse_lock_pid("633201\0\0"), Some(633_201));
assert_eq!(parse_lock_pid(" 42 \t\r\n"), Some(42));
}

#[test]
fn test_parse_lock_pid_rejects_garbage() {
for garbage in [
"",
"\0",
"\n",
"abc",
"abc\0",
"12abc\0",
"0x1F\0",
// A NUL before or inside the digits is not a terminator.
"\x00633201",
"63\x003201",
"633201\0junk",
"633201\0 12",
"1 2",
// Out of range for a pid_t.
"99999999999\0",
] {
assert_eq!(parse_lock_pid(garbage), None, "{garbage:?}");
}
}

// Garbage in a lock file is still treated as stale and swept away.
#[test]
fn test_garbage_lock_is_stale() {
let dir = tempfile::tempdir().unwrap();
let lock_path = dir.path().join("test_file.lock");
fs::write(&lock_path, "not a pid\0").unwrap();
assert!(is_stale_lock(&lock_path));
}
}
52 changes: 52 additions & 0 deletions tests/e2e/deploy-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,57 @@ E
rm -f /usr/local/bin/ed-append /usr/local/bin/ed-slow
}

# ── Lock files: the upstream on-disk form ──────────────────────────

# shadow-utils writes a lock as the holder's pid followed by one NUL byte
# (`/etc/group.lock` held by pid 99 is `9 9 \0`). Both suites must read each
# other's locks: one that took a live upstream lock for a stale one would
# delete it and edit the file under the other's feet.
test_lock_interop() {
section "lock files — the upstream pid-and-NUL form"

groupdel lk_team 2>/dev/null || true
rm -f /etc/group.lock

# What we write, captured while vigr holds the lock: its pid and a NUL.
cat > /usr/local/bin/ed-copylock <<'E'
#!/bin/sh
cp /etc/group.lock "$LOCKCOPY"
E
chmod +x /usr/local/bin/ed-copylock
local copy
copy=$(mktemp)
env LOCKCOPY="$copy" EDITOR=ed-copylock vigr -q &
local vigr_pid=$!
wait "$vigr_pid"
assert_ok "the lock holds the holder's pid and a NUL, as upstream writes it" \
cmp "$copy" <(printf '%d\0' "$vigr_pid")
rm -f "$copy" /usr/local/bin/ed-copylock

# A live lock in that form is waited on, not swept away as stale.
sleep 30 &
local holder=$!
printf '%d\0' "$holder" > /etc/group.lock
groupadd lk_team &
local adder=$!
sleep 1
assert_ok "groupadd waits on a live upstream-form lock" kill -0 "$adder"
assert_ok "and leaves the holder's lock in place" \
cmp /etc/group.lock <(printf '%d\0' "$holder")
assert_file_not_contains "and has not touched /etc/group" /etc/group '^lk_team:'

# Once the holder is gone (and reaped), the same lock is stale.
kill "$holder"
wait "$holder" 2>/dev/null
local rc=0
wait "$adder" || rc=$?
assert_ok "groupadd proceeds once the holder has exited" test "$rc" -eq 0
assert_file_contains "the group was added" /etc/group '^lk_team:'
assert_ok "no lock is left behind" bash -c "! test -e /etc/group.lock"

groupdel lk_team 2>/dev/null || true
}

# ── newusers: batch account creation ───────────────────────────────

test_newusers() {
Expand Down Expand Up @@ -1538,6 +1589,7 @@ main() {
test_chgpasswd
test_newusers
test_vipw
test_lock_interop
test_pwconv_family
test_login
test_idmap
Expand Down