Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 95 ยท System Administration

PAM, sudoers and Account Policies

Understand PAM stacks and control flags, write safe sudoers rules with visudo, enforce password quality and aging, and lock out repeated login failures.

Who may log in, how strong their password must be, what happens after five wrong guesses, and which commands a user may run as root: on Linux these are not decided by one program. They are decided by small, replaceable building blocks that you configure with text files. PAM (Pluggable Authentication Modules) handles authentication, account checks, password changes and session setup for almost every program that logs a user in. sudo decides who may run which command with whose privileges. Together with the password-aging fields in /etc/shadow, they form the account policy of a server.

This lesson explains the structure of a PAM stack and its control flags, how to enforce a password policy and an account lockout, how to write a sudoers file that is both useful and safe, and how to review it. It builds on Users, Groups and sudo and Packages, Services and systemd. The sandbox has no sudo, no visudo and no root, so the real policy commands are read-only; the runnable examples evaluate the same rules in Bash and read files that exist in the sandbox.

PAM: one library, many programs

Programs such as login, sshd, su, sudo, passwd and your desktop login screen do not contain password-checking code. They call the PAM library and name a service, for example sshd. PAM then reads the matching file /etc/pam.d/sshd and runs the modules listed there. Changing the policy for every program at once means editing one shared file, usually included by the others (common-auth on Debian and Ubuntu, system-auth and password-auth on RHEL and Fedora).

PAM splits the work into four management groups:

Group Question it answers Example modules
auth Who are you? (password, key, token) pam_unix, pam_faillock, pam_google_authenticator
account May this account log in now? (expired, locked, time of day) pam_unix, pam_nologin, pam_time
password Change the credential, and is the new one acceptable? pam_pwquality, pam_unix
session Set up and clean up the session (limits, home directory, logging) pam_limits, pam_mkhomedir, pam_systemd

Every line of a file in /etc/pam.d/ has the form type control module [arguments]. This is a real file from the sandbox (comments removed); the whitespace is tabs:

Bash Reading a real PAM file and account defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the three auth lines as a recipe. pam_unix.so nullok_secure checks the password against /etc/shadow. Its control field [success=1 default=ignore] means "if this succeeds, skip the next 1 line; otherwise carry on". The next line, pam_deny.so, always fails, so it is only reached when the password check failed. The last line, pam_permit.so, always succeeds and is reached only when the check skipped the deny. This hand-built if/else is typical for Debian-family systems.

Control flags

The control field decides what a module's result means for the whole stack. The four classic keywords are:

Control If the module fails If the module succeeds
required stack will fail in the end, but the remaining modules still run (so an attacker learns nothing from timing) stack can still succeed
requisite stack fails immediately continue
sufficient ignored stack succeeds immediately, unless an earlier required module failed
optional ignored ignored (matters only if it is the only module)

The bracket form [value=action ...] gives full control; common actions are ok, ignore, bad, die, done, and a number to skip that many lines. The order of lines matters enormously, and a single misplaced sufficient can let everyone in. Always keep a root shell open in a second terminal while you edit PAM files, because a broken file can lock you out of the machine.

flowchart TD
    S["Start of the auth stack"] --> A["pam_faillock (required)"]
    A -->|"fail: remember"| B
    A -->|"ok"| B["pam_unix (sufficient)"]
    B -->|"password correct and nothing failed before"| OK["Stack succeeds - login allowed"]
    B -->|"wrong password, or an earlier required module failed"| D["pam_deny (required)"]
    D --> F["Stack fails - login refused"]

A RHEL-style auth stack: sufficient ends the stack early only when no required module has failed yet.

You can see those rules at work in this evaluator. It takes a stack and the result of each module, and applies the four keywords exactly as the table says:

Bash Evaluating a PAM stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Case 3 is the important one: the user typed the right password, pam_unix succeeded, but because the earlier required lockout module had failed, sufficient did not end the stack early, and pam_deny finished the job. That is how a lockout works without telling the attacker which part was wrong.

Password quality and aging

Strong passwords are enforced at the moment they are changed, by a password module. On modern systems this is pam_pwquality, configured in /etc/security/pwquality.conf (older systems used pam_cracklib):

TEXT
# /etc/security/pwquality.conf
minlen = 12          # at least 12 characters
minclass = 3         # at least 3 of: lowercase, uppercase, digits, other
maxrepeat = 3        # no more than 3 identical characters in a row
dictcheck = 1        # reject dictionary words
usercheck = 1        # reject passwords that contain the user name
retry = 3            # three attempts per passwd run

Debian-family systems activate it with a line like password requisite pam_pwquality.so retry=3 in common-password. Current guidance (for example from NIST) favours length and a blocklist of known-bad passwords over complicated composition rules and frequent forced changes, so a sensible policy is a minimum length of 12 or more, no common passwords, and changes only after a suspected compromise.

Password aging lives in /etc/shadow and is managed with chage:

CONSOLE
$ sudo chage -l maria
Last password change                 : Jan 10, 2026
Password expires                     : Apr 10, 2026
Password inactive                    : never
Account expires                      : never
Minimum number of days between password change : 1
Maximum number of days between password change : 90
Number of days of warning before password expires : 7
$ sudo chage -M 90 -m 1 -W 7 maria      # max, min, warning days
$ sudo chage -E 2026-12-31 contractor   # the account itself expires on a date
$ sudo chage -d 0 maria                 # force a password change at next login

The dates in /etc/shadow are stored as days since 1970-01-01, which is why a shadow line looks like maria:$6$...:20463:1:90:7:::. The defaults for new accounts come from PASS_MAX_DAYS, PASS_MIN_DAYS and PASS_WARN_AGE in /etc/login.defs, as in the first example above. This script turns such a number into real dates and checks sample passwords against a small policy:

Bash Password aging dates and a quality check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first three candidates fail on length, variety and the user name; the fourth fails the blocklist even though it looks complex, and only the last passes because it is long, mixes classes and contains no known-bad word. In the aging half, shadow day 20463 is 2026-01-10, the password expires 90 days later on April 10, and on April 5 only 5 days remain, which is inside the 7-day warning window.

Account lockout

Repeated wrong guesses are the signature of password-guessing attacks. pam_faillock (the successor of pam_tally2) counts failed attempts per account and locks it for a while. On RHEL-family systems it is configured in /etc/security/faillock.conf:

TEXT
deny = 5               # lock after 5 consecutive failures
fail_interval = 900    # ...that happened within 15 minutes
unlock_time = 600      # stay locked for 10 minutes (0 = until an admin unlocks)
even_deny_root         # also lock root (remote logins)

and it appears in the stack before and after pam_unix (as preauth and authfail). Inspect and reset with faillock --user maria and faillock --user maria --reset. Lockouts protect against guessing but can be abused to lock real users out, so many sites combine a short lock with rate limiting and SSH keys (see Server Hardening Checklist). Related account tools: passwd -l maria or usermod -L maria locks the password, usermod -e 1 maria expires the account, and a login shell of /usr/sbin/nologin makes a service account unusable for logins (see Users, Groups and sudo).

sudo and the sudoers file

sudo lets selected users run selected commands as another user (usually root) after typing their own password, and logs every use. Its policy is in /etc/sudoers plus files in /etc/sudoers.d/. Never edit these with an ordinary editor. A syntax error can lock everyone out of root access, so use visudo, which locks the file, opens your editor and refuses to save a broken file. For drop-in files use sudo visudo -f /etc/sudoers.d/deploy, and check everything with sudo visudo -c.

A rule has the form who where = (as_whom) what:

TEXT
# /etc/sudoers.d/team   (read-only example)
Defaults  env_reset, use_pty, timestamp_timeout=5, logfile=/var/log/sudo.log

%admin   ALL=(ALL:ALL) ALL                         # group admin: anything, as anyone
deploy   web1=(root) /bin/systemctl restart app, /bin/systemctl status app
backup   ALL=(root) NOPASSWD: /usr/bin/rsync *
alice    ALL=(www-data) /usr/bin/php /srv/app/artisan *
Part Meaning
who a user name, a %group, or an alias
where the host name the rule applies to (ALL for any)
(as_whom) the user (and optional :group) that the command may run as
NOPASSWD: tag: do not ask for a password
what a comma-separated list of full paths, with optional arguments, or ALL

The last matching rule wins, so put general rules first and exceptions last. Users and admins then work with sudo -l (list what I may run), sudo -u www-data command and sudo -k (forget the cached password). Prefer sudoedit /etc/file to sudo vim /etc/file: it edits a copy as you and writes the result back, so the editor never runs as root.

The checker below parses rules written in that syntax, takes a request (user, groups, host, target user, command line) and applies the last-match rule. It also demonstrates the most famous trap:

Bash Evaluating sudoers rules (and a wildcard trap)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at the last two lines. The rule rsync * was meant to allow backups, but the * also matches -e 'sh -c id', and rsync -e runs an arbitrary program, which means this "backup" user effectively has a root shell and no password prompt. The same applies to commands that can open a shell, such as vim, less, find -exec, awk, git, tar --checkpoint-action and systemctl in a pager: sudo on those is sudo on everything. Safe sudoers rules name exact commands with exact arguments, avoid wildcards in argument lists, avoid NOPASSWD for humans, use sudoedit, and grant a dedicated wrapper script instead of a general tool.

Review checklist

  • sudo visudo -c passes, and every file in /etc/sudoers.d/ has mode 0440 and no dots or ~ in its name (such files are ignored).
  • Nobody has ALL unless they are an administrator; service accounts have exact commands.
  • Defaults use_pty and a logfile (or journal logging) are on; env_reset is kept.
  • Run sudo -l -U username to see what a person can really do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a PAM auth stack, a sufficient module succeeds but an earlier required module has already failed. What happens?

    sufficient ends the stack with success only if no required module failed before it. Otherwise the stack continues, and the earlier failure still makes the overall result a failure.
  2. 2. What is the difference between required and requisite when the module fails?

    Both lead to a failed stack. requisite returns immediately, required continues so that the failure does not reveal which module refused.
  3. 3. Why should you use visudo instead of editing /etc/sudoers with a normal editor?

    A syntax error in sudoers makes sudo refuse to work at all. visudo validates before saving, and locks the file against concurrent edits.
  4. 4. The rule backup ALL=(root) NOPASSWD: /usr/bin/rsync * is dangerous because:

    rsync -e accepts a remote-shell command. Because the wildcard matches any arguments, the user can make rsync start a shell as root, without a password.
  5. 5. pam_faillock is configured with deny = 5 and unlock_time = 600. What does it do?

    deny sets the number of failures that triggers the lock and unlock_time is how long the account stays locked, in seconds. 600 seconds is 10 minutes.

Summary

  • PAM moves authentication out of programs: /etc/pam.d/SERVICE lists modules in four groups (auth, account, password, session), each line type control module args.
  • Controls: required (fail at the end), requisite (fail now), sufficient (succeed now if nothing required failed), optional; [success=N ...] skips lines. Keep a root shell open when editing PAM.
  • Enforce password quality with pam_pwquality (/etc/security/pwquality.conf), aging with chage and /etc/login.defs, lockout with pam_faillock. Shadow dates are days since 1970.
  • Lock accounts with passwd -l, usermod -L, chage -E, or a nologin shell.
  • sudoers rules read who where = (as_whom) what; the last match wins. Edit only with visudo, grant exact commands, use sudoedit, and check people with sudo -l -U.
  • Wildcards and shell-capable programs (vim, less, find, rsync -e) turn a narrow sudo rule into full root access.

Next: Server Hardening Checklist