Build a User Account Audit Report
This project builds useraudit.sh, a script that audits the user accounts of a Linux system and prints a report. It lists the accounts that can log in, shows how old each password is and who has administrator rights, and flags the settings that security reviewers look for first: a second account with root rights, empty passwords, shared user IDs, service accounts with a login shell, stale passwords and missing home directories. Its exit status tells a calling script whether any serious problem was found.
Lesson 154 introduced script security and lesson 159 introduced least privilege. This project applies both ideas to the most basic security question on a server: who can log in, and with what rights? The script is read-only. It never changes an account.
What the Script Should Do
- Read
/etc/passwd,/etc/shadowand/etc/group, or the same files below another root directory (-r), so that a backup or a test copy can be audited safely. - List the normal accounts (UID 1000 and above, with a real login shell) with password state, password age, administrator groups and shell.
- Flag problems as
HIGH(needs immediate action),WARN(should be reviewed) orINFO(worth knowing). - Run without root when needed, and say clearly which checks were skipped.
- Exit with status 1 if there is at least one
HIGHfinding.
Where Account Data Is Stored
/etc/passwd
Each line describes one account with seven colon-separated fields:
alice:x:1000:1000:Alice:/home/alice:/bin/bash
| Field | Example | Meaning |
|---|---|---|
| 1 | alice | User name |
| 2 | x | Password placeholder; the real hash is in /etc/shadow |
| 3 | 1000 | User ID (UID). UID 0 is root, with unlimited rights |
| 4 | 1000 | Primary group ID |
| 5 | Alice | Comment (full name) |
| 6 | /home/alice | Home directory |
| 7 | /bin/bash | Login shell |
The file is readable by everyone because many programs need to translate IDs to names. By convention, UIDs below 1000 belong to system and service accounts, and UIDs from 1000 up are real people. (Some distributions start at 500; the script has the -u option for that.) The account nobody with UID 65534 is a special unprivileged account and is not counted as a person.
/etc/shadow
The shadow file holds the password hashes and the ageing rules, so only root can read it. It has nine fields:
bob:$6$salt$hash:20400:0:99999:7:::
| Field | Meaning |
|---|---|
| 1 | User name |
| 2 | Password hash. Empty means no password. A value starting with ! or equal to * means the password login is locked |
| 3 | Day of the last password change, counted in days since 1 January 1970 |
| 4, 5, 6, 7 | Minimum age, maximum age, warning period and inactivity period in days |
| 8 | Day on which the account expires (empty means never) |
| 9 | Reserved |
Because the dates are days since 1970, the age of a password is a plain subtraction: today's day number ($(( $(date +%s) / 86400 ))) minus field 3. No date parsing is needed.
An empty hash field is the dangerous case: on many systems an account with an empty password can log in without typing anything.
/etc/group
sudo:x:27:alice,carol
The last field lists the members. On Debian and Ubuntu, members of sudo can run commands as root; on Red Hat based systems the group is called wheel; some older systems use admin. The script checks all three names.
Design Decisions
Parsing Files with read and IFS
Lesson 114 showed while read. Setting IFS=: for the read command (only for that command) splits each line at the colons:
while IFS=: read -r name _ uid _ _ home shell; do
echo "$name has UID $uid and shell $shell"
done < /etc/passwd
Expected output (shortened):
root has UID 0 and shell /bin/bash
daemon has UID 1 and shell /usr/sbin/nologin
The underscore _ is an ordinary variable name used by convention for "a field I do not need". read assigns the first field to name, the second to _, and so on. Because no external program like cut or awk is started, reading even a very long file is fast.
Associative Arrays as Lookup Tables
The script loads the account data once into associative arrays (lesson 102), keyed by user name, and afterwards every check is a cheap lookup:
declare -A uid_of shell_of home_of owners
uid_of[$name]=$uid
owners[$uid]+="${owners[$uid]:+ }$name"
The last line collects all names that share a UID in one string. ${owners[$uid]:+ } expands to a space only when the entry already has a value (lesson 45), so the names are separated by single spaces and there is no leading space. Afterwards, a UID with more than one name is a duplicate, which means two accounts have the same rights over files.
Recording Findings in the Current Shell
Every check calls a small function that stores one line and updates the counters:
finding() {
findings+=("$(printf '%-5s %s' "$1" "$2")")
case $1 in
HIGH) high=$((high + 1)) ;;
WARN) warn=$((warn + 1)) ;;
esac
}
The function is called directly and never inside $( ). A command substitution runs in a subshell, and counter changes made there would disappear (the same effect as in lessons 93 and 197). The printf inside $( ) in the first line is fine, because it only produces text.
Deciding Who Can Log In
An account can only be used interactively if its shell is a real shell. Service accounts normally have /usr/sbin/nologin or /bin/false. The can_login function tests the shell name with case:
can_login() {
case ${1##*/} in
''|nologin|false|sync|shutdown|halt) return 1 ;;
*) return 0 ;;
esac
}
${1##*/} removes everything up to the last slash, so /usr/sbin/nologin becomes nologin. A shell field that is empty is also treated as "cannot log in" by the function, which keeps the check simple. A service account such as backup with /bin/bash is reported because an attacker who obtains its credentials gets an interactive shell.
Quiet Mode and a Clean Exit Status
The -q option omits the account table and prints only findings, which is the right output for a cron job that mails a report. The last line of the script, (( high == 0 )), is true when there are no HIGH findings, so the script exits with 0 or 1 without an explicit exit, as in lesson 197.
The Complete Script
#!/usr/bin/env bash
#
# useraudit.sh - audit the user accounts of a Linux system
#
# Usage: useraudit.sh [-r ROOT] [-a DAYS] [-u UID] [-q]
#
# Options:
# -r ROOT audit the files under ROOT instead of / (for tests and backups)
# -a DAYS warn when a password is older than DAYS days (default: 90)
# -u UID first UID of normal (human) accounts (default: 1000)
# -q quiet: print only the findings, not the account table
# -h show this help
#
# Reads ROOT/etc/passwd, ROOT/etc/shadow and ROOT/etc/group. Reading the
# shadow file needs root privileges; without it the password checks are skipped.
#
# Exit status: 0 no serious findings, 1 at least one HIGH finding, 2 usage error.
set -euo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,17s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit 2
}
root=/ max_age=90 min_uid=1000 quiet=0
while getopts ':r:a:u:qh' opt; do
case $opt in
r) root=$OPTARG ;;
a) max_age=$OPTARG ;;
u) min_uid=$OPTARG ;;
q) quiet=1 ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $max_age =~ ^[0-9]+$ && $min_uid =~ ^[0-9]+$ ]] || die "-a and -u need whole numbers"
root=${root%/}
passwd_file=$root/etc/passwd shadow_file=$root/etc/shadow group_file=$root/etc/group
[[ -r $passwd_file ]] || die "cannot read $passwd_file"
[[ -r $group_file ]] || die "cannot read $group_file"
high=0 warn=0
findings=()
# finding LEVEL TEXT - record a finding (a function that changes the counters
# must run in the current shell, so it is never called inside $( ))
finding() {
findings+=("$(printf '%-5s %s' "$1" "$2")")
case $1 in
HIGH) high=$((high + 1)) ;;
WARN) warn=$((warn + 1)) ;;
esac
}
# can_login SHELL - succeed when the shell allows an interactive login
can_login() {
case ${1##*/} in
''|nologin|false|sync|shutdown|halt) return 1 ;;
*) return 0 ;;
esac
}
# --- read the three files ------------------------------------------------------
declare -A uid_of shell_of home_of owners
names=()
while IFS=: read -r name _ uid _ _ home shell; do
[[ -z $name || $name == \#* ]] && continue
names+=("$name")
uid_of[$name]=$uid
shell_of[$name]=$shell
home_of[$name]=$home
owners[$uid]+="${owners[$uid]:+ }$name"
done < "$passwd_file"
declare -A members=() # privileged group -> space-separated members
while IFS=: read -r gname _ gid list; do
case $gname in
sudo|wheel|admin) members[$gname]=${list//,/ } ;;
esac
done < "$group_file"
declare -A pw_state=() pw_age=() expired=()
have_shadow=0
today=$(( $(date +%s) / 86400 )) # days since 1970-01-01, like the shadow file
if [[ -r $shadow_file ]]; then
have_shadow=1
while IFS=: read -r name hash changed _ _ _ _ expire _; do
[[ -z $name ]] && continue
case $hash in
'') pw_state[$name]=EMPTY ;;
'!'*|'*') pw_state[$name]=locked ;;
*) pw_state[$name]=set ;;
esac
[[ $changed =~ ^[0-9]+$ ]] && pw_age[$name]=$(( today - changed ))
[[ $expire =~ ^[0-9]+$ ]] && (( expire <= today )) && expired[$name]=1
done < "$shadow_file"
else
finding WARN "cannot read $shadow_file: password checks skipped (run with sudo)"
fi
# --- checks ---------------------------------------------------------------------
for uid in "${!owners[@]}"; do
read -ra who <<< "${owners[$uid]}"
if (( uid == 0 && ${#who[@]} > 1 )); then
finding HIGH "several accounts have UID 0 (root rights): ${owners[$uid]}"
elif (( ${#who[@]} > 1 )); then
finding HIGH "UID $uid is shared by: ${owners[$uid]}"
fi
done
humans=()
for name in "${names[@]}"; do
uid=${uid_of[$name]}
login=0
can_login "${shell_of[$name]}" && login=1
if (( uid >= min_uid && uid != 65534 && login )); then
humans+=("$name")
elif (( uid > 0 && uid < min_uid && login )); then
finding WARN "system account '$name' (UID $uid) has a login shell: ${shell_of[$name]}"
fi
if (( have_shadow )); then
if [[ ${pw_state[$name]:-} == EMPTY ]]; then
finding HIGH "account '$name' has an empty password"
fi
if (( login )) && [[ ${pw_state[$name]:-} == set ]] && (( ${pw_age[$name]:-0} > max_age )); then
finding WARN "password of '$name' is ${pw_age[$name]} days old (limit $max_age)"
fi
if [[ -n ${expired[$name]:-} ]] && [[ ${pw_state[$name]:-} != locked ]]; then
finding WARN "account '$name' has expired but is not locked"
fi
fi
done
for name in "${humans[@]}"; do
[[ -d $root${home_of[$name]} ]] || finding WARN "home directory of '$name' is missing: ${home_of[$name]}"
done
for g in "${!members[@]}"; do
for name in ${members[$g]}; do
finding INFO "'$name' can administer the system through group '$g'"
done
done
# --- report ---------------------------------------------------------------------
printf 'User account audit of %s (%s)\n\n' "${root:-/}" "$(date '+%Y-%m-%d %H:%M')"
if (( ! quiet )); then
printf '%-12s %-6s %-9s %-8s %-12s %s\n' ACCOUNT UID PASSWORD AGE GROUPS SHELL
for name in "${humans[@]}"; do
groups_of=
for g in "${!members[@]}"; do
[[ " ${members[$g]} " == *" $name "* ]] && groups_of+="${groups_of:+,}$g"
done
age=-
[[ -n ${pw_age[$name]:-} ]] && age="${pw_age[$name]}d"
printf '%-12s %-6s %-9s %-8s %-12s %s\n' "$name" "${uid_of[$name]}" \
"${pw_state[$name]:-?}" "$age" "${groups_of:--}" "${shell_of[$name]}"
done
printf '\n%d login-capable normal accounts (UID %d and above)\n\n' "${#humans[@]}" "$min_uid"
fi
if (( ${#findings[@]} == 0 )); then
echo "No findings."
else
printf 'Findings\n'
printf '%s\n' "${findings[@]}" | sort
printf '\n%d high, %d warnings\n' "$high" "$warn"
fi
(( high == 0 ))
Creating Test Data
An audit tool must be tested on data with known problems, and you should never test on a real /etc/shadow. The script below builds a small fake etc directory with typical problems. Dates in the shadow file are calculated from today, so the example stays valid at any time:
#!/usr/bin/env bash
# mkfixture.sh DIR - create a small fake /etc with typical audit problems
set -euo pipefail
dir=$1
today=$(( $(date +%s) / 86400 ))
mkdir -p "$dir/etc" "$dir/home/alice" "$dir/home/bob" "$dir/home/carol"
cat > "$dir/etc/passwd" <<EOT
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/bin/bash
alice:x:1000:1000:Alice:/home/alice:/bin/bash
bob:x:1001:1001:Bob:/home/bob:/bin/bash
carol:x:1002:1002:Carol:/home/carol:/bin/zsh
dave:x:1003:1003:Dave:/home/dave:/bin/bash
toor:x:0:0:second root:/root:/bin/sh
guest:x:1004:1004:Guest:/home/guest:/bin/bash
svc-app:x:1005:1005:Service:/srv/app:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
EOT
cat > "$dir/etc/group" <<EOT
root:x:0:
sudo:x:27:alice,carol
admin:x:110:dave
alice:x:1000:
EOT
cat > "$dir/etc/shadow" <<EOT
root:\$6\$salt\$hash:$((today - 20)):0:99999:7:::
daemon:*:$((today - 900)):0:99999:7:::
www-data:*:$((today - 900)):0:99999:7:::
backup:*:$((today - 900)):0:99999:7:::
alice:\$6\$salt\$hash:$((today - 12)):0:99999:7:::
bob:\$6\$salt\$hash:$((today - 240)):0:99999:7:::
carol:\$6\$salt\$hash:$((today - 45)):0:99999:7:::
dave:!\$6\$salt\$hash:$((today - 400)):0:99999:7::$((today - 30)):
toor:\$6\$salt\$hash:$((today - 5)):0:99999:7:::
guest::$((today - 3)):0:99999:7:::
svc-app:!:$((today - 100)):0:99999:7:::
nobody:*:$((today - 900)):0:99999:7:::
EOT
The fake system contains these problems on purpose:
toorhas UID 0, like root.guesthas an empty password.boblast changed his password 240 days ago.backupis a system account with/bin/bashas shell.davehas no home directory, has expired, and is locked.aliceandcarolare insudo,daveinadmin.
Running the Audit
$ ./mkfixture.sh fake
$ ./useraudit.sh -r fake; echo "status $?"
User account audit of fake (2026-12-02 17:38)
ACCOUNT UID PASSWORD AGE GROUPS SHELL
alice 1000 set 12d sudo /bin/bash
bob 1001 set 240d - /bin/bash
carol 1002 set 45d sudo /bin/zsh
dave 1003 locked 400d admin /bin/bash
guest 1004 EMPTY 3d - /bin/bash
5 login-capable normal accounts (UID 1000 and above)
Findings
HIGH account 'guest' has an empty password
HIGH several accounts have UID 0 (root rights): root toor
INFO 'alice' can administer the system through group 'sudo'
INFO 'carol' can administer the system through group 'sudo'
INFO 'dave' can administer the system through group 'admin'
WARN home directory of 'dave' is missing: /home/dave
WARN home directory of 'guest' is missing: /home/guest
WARN password of 'bob' is 240 days old (limit 90)
WARN system account 'backup' (UID 34) has a login shell: /bin/bash
2 high, 4 warnings
status 1
- The table lists only accounts that can log in and have a normal UID.
svc-app(shellnologin) andnobodydo not appear, andtoordoes not either, because its UID is 0, below 1000. The finding list still catches it, because the UID checks look at every account, not only at login-capable people. daveislocked, so the old password cannot be used, and the 400-day age does not produce a warning. Locked accounts are not a password risk, but the missing home directory is still reported.INFOlines are not problems. They answer the audit question who is an administrator? so that the list can be compared with the list of people who should be.- The findings are sorted with
sort, so lines that start with the same level are grouped together and the report looks the same on every run.HIGHhappens to come first alphabetically, so the serious lines are at the top.
Shorter Reports and Stricter Rules
-q prints only findings, and -a 30 shortens the password limit to 30 days. A second account that also uses UID 1001 is added to show the duplicate check:
$ cp -r fake fake2
$ echo 'ops:x:1001:1001:Ops:/home/ops:/bin/bash' >> fake2/etc/passwd
$ ./useraudit.sh -q -a 30 -r fake2
User account audit of fake2 (2026-12-02 17:38)
Findings
HIGH UID 1001 is shared by: bob ops
HIGH account 'guest' has an empty password
HIGH several accounts have UID 0 (root rights): root toor
INFO 'alice' can administer the system through group 'sudo'
INFO 'carol' can administer the system through group 'sudo'
INFO 'dave' can administer the system through group 'admin'
WARN home directory of 'dave' is missing: /home/dave
WARN home directory of 'guest' is missing: /home/guest
WARN home directory of 'ops' is missing: /home/ops
WARN password of 'bob' is 240 days old (limit 30)
WARN password of 'carol' is 45 days old (limit 30)
WARN system account 'backup' (UID 34) has a login shell: /bin/bash
3 high, 6 warnings
Two accounts with the same UID are, for the kernel, the same user. Both can read and delete each other's files, which is almost never intended. (The order of names inside a finding depends on how the system lists the file, so it can differ.)
Running Without Root
Without permission to read the shadow file, the script still works and says what it skipped. This run used the unprivileged user nobody:
$ ./useraudit.sh -q -r fake
User account audit of fake (2026-12-02 17:38)
Findings
HIGH several accounts have UID 0 (root rights): root toor
INFO 'alice' can administer the system through group 'sudo'
INFO 'carol' can administer the system through group 'sudo'
INFO 'dave' can administer the system through group 'admin'
WARN cannot read fake/etc/shadow: password checks skipped (run with sudo)
WARN home directory of 'dave' is missing: /home/dave
WARN home directory of 'guest' is missing: /home/guest
WARN system account 'backup' (UID 34) has a login shell: /bin/bash
1 high, 4 warnings
The empty password of guest and the old password of bob are not reported here, which is why the warning about the skipped checks is itself a finding. A report that silently skipped checks would look cleaner than reality.
Auditing a Real System
On a real machine run the script with sudo. This is the result on a minimal Ubuntu container:
$ sudo ./useraudit.sh -q
User account audit of / (2026-12-02 17:38)
Findings
INFO 'ubuntu' can administer the system through group 'sudo'
WARN system account 'claude' (UID 999) has a login shell: /bin/bash
WARN system account 'postgres' (UID 102) has a login shell: /bin/bash
0 high, 2 warnings
The exit status is 0 because there is no HIGH finding. The warnings are not necessarily errors: the postgres account needs a shell for some administration tasks. An audit shows facts for a human to judge, and the way to handle accepted exceptions is to document them.
Input Errors
$ ./useraudit.sh -a x
useraudit.sh: -a and -u need whole numbers
$ ./useraudit.sh -r /nope
useraudit.sh: cannot read /nope/etc/passwd
Both exit with status 2.
Scheduling the Audit
Run the audit once a week as root, keep a dated copy of each report, and send the mail only when there is something serious (lesson 170 and lesson 173):
0 6 * * 1 /usr/local/bin/useraudit.sh -q > /var/log/useraudit-$(date +\%F).txt || /usr/local/bin/notify.sh "Account audit: HIGH findings on $(hostname)" < /var/log/useraudit-$(date +\%F).txt
Inside a crontab, the percent sign has a special meaning, so it must be written as \%. Keeping the dated reports lets you compare two weeks with diff, which shows exactly which account or group membership has changed:
diff /var/log/useraudit-2026-11-24.txt /var/log/useraudit-2026-12-01.txt
A new line under INFO that nobody can explain is the kind of change an audit exists to catch.
Ideas for Extending the Project
- Last login. The
lastlogcommand shows when each account was last used. Accounts that have not logged in for 180 days are candidates for locking. - SSH keys. Count the lines in each
~/.ssh/authorized_keysand report accounts with keys but without a recent login. - Password policy. Read fields 4 to 7 of the shadow file and warn when a login-capable account has no maximum age (field 5 equal to 99999).
- Sudoers files. Add a check for entries in
/etc/sudoers.dthat grantNOPASSWDrights. - Baseline comparison. Store an approved list of administrators in a file and report every difference, so that the audit answers "who changed?" instead of "who exists?".