Skip to content

sudo best practices — granular grants, audit trails, and visudo discipline

Sudo is what gates privilege escalation on every Linux host. Used carefully, it gives you fine-grained, auditable access. Used carelessly, it is a passwordless root keystroke away.

sudo is the mechanism that gates privilege escalation on every Linux host. Used carefully, it gives you fine-grained, auditable access: this user can restart this specific service on this specific host, full stop. Used carelessly — typically a single %sudo ALL=(ALL:ALL) NOPASSWD: ALL — it is a single keystroke from any operator’s shell to root. This article documents the operational patterns we apply across the fleet.

How to verify

Inventory who can do what right now.

sudo -ll                                   # list rules for current user (long form)
sudo -lU alice                             # list rules that apply to alice
ls -la /etc/sudoers.d/
sudo grep -rE '^[^#]' /etc/sudoers /etc/sudoers.d/
grep -E '^(%sudo|%wheel|%admin)' /etc/sudoers

sudo -lU <user> is the single most useful query: it prints exactly what that user is allowed to run, with which target user, and whether a password is required.

What’s happening

sudo reads its policy from /etc/sudoers plus every file in /etc/sudoers.d/ (the latter is enabled by an #includedir directive in /etc/sudoers). Each line in those files is either a Defaults directive (global behaviour) or a rule of the form:

who  where=(target_user[:target_group])  [tag1, tag2 ...]  command_list

For example:

ops    ALL=(root)    NOPASSWD: /bin/systemctl restart nginx, /bin/systemctl reload nginx
alice  web-01,web-02 = (root)    /usr/bin/journalctl

The where is the host (relevant only if you ship a fleet-wide sudoers); the target_user is whom the command will run as; NOPASSWD skips the password prompt; the command list is the literal set of binaries this rule permits.

The two operational concerns are: keeping the policy auditable (no gigantic blanket grants), and editing safely (one bad file in /etc/sudoers.d/ breaks sudo for everyone until single-user-mode rescue).

The procedure

  1. Always edit with visudo. It validates syntax before saving. For files in /etc/sudoers.d/, use visudo -f.

    sudo visudo                         # edit /etc/sudoers
    sudo visudo -f /etc/sudoers.d/20-app-restart

    visudo aborts the save if the file has a syntax error, which is the only thing standing between you and a broken sudo on every host.

  2. Keep /etc/sudoers as the distro shipped it. Put all customization in drop-ins under /etc/sudoers.d/. The drop-in directory makes individual changes auditable and revertable without surgery on the monolithic file.

  3. Grant by least privilege. Resist ALL=(ALL) NOPASSWD: ALL even for operator accounts. The pattern we use:

    # /etc/sudoers.d/30-ops-base
    # Operators get full sudo with password
    %ops    ALL=(ALL:ALL)    ALL
    
    # /etc/sudoers.d/40-app-automation
    # CI deploy bot can only restart its own services, no password
    deploy  ALL=(root)       NOPASSWD: /bin/systemctl restart app.service, \
                                        /bin/systemctl reload nginx, \
                                        /usr/bin/journalctl -u app

    The deploy bot can do exactly two things plus a log read. If the deploy account is compromised, the blast radius is narrow.

  4. Use Cmnd_Alias for clarity. When the same command list appears in multiple rules, factor it.

    Cmnd_Alias APP_RESTART = /bin/systemctl restart app.service, /bin/systemctl reload nginx
    Cmnd_Alias LOG_READ    = /usr/bin/journalctl -u app, /bin/cat /var/log/app/*.log
    
    deploy  ALL=(root) NOPASSWD: APP_RESTART
    sre     ALL=(root)           APP_RESTART, LOG_READ

    Easier to audit, easier to extend.

  5. Force a password prompt on every command if the account is a primary operator. Defaults directive:

    Defaults timestamp_timeout=15
    Defaults:%ops timestamp_timeout=5

    The default is 15 minutes — once you sudo, you have 15 minutes of grace. For higher-sensitivity accounts, cut it to 5 minutes or 0.

  6. Configure sudo to log to the journal and to a dedicated file. sudo writes to auth.log/secure by default, but a dedicated log makes audit easier.

    Defaults logfile=/var/log/sudo.log
    Defaults log_year, log_host
    Defaults !syslog                       # if you do not want syslog in addition
    Defaults loglinelen=0                  # do not truncate

    Then:

    sudo tail -F /var/log/sudo.log
    sudo journalctl -t sudo --since today
  7. Test before declaring victory. After editing a drop-in, verify it parses and applies.

    sudo visudo -c                         # check syntax of all sudoers files
    sudo -lU deploy                        # show what deploy can do
    sudo -lU alice

    visudo -c is the dry-run check. It exits non-zero if any file is invalid.

  8. For automation, use distinct accounts not human accounts. A CI runner that needs to restart an application should not be running as a human operator. A dedicated deploy service account with a narrowly-scoped sudoers entry is the auditable answer.

  9. Audit periodically. Once a quarter (or after a personnel change), enumerate the policy across the fleet.

    ansible all -m shell -a "sudo -ll 2>&1 | head -30"

    Any rule that grants more than the role needs is a finding; tighten it.

  10. Remove rules cleanly. When an operator leaves, removing their key is half the job — removing their sudoers entry is the other half.

    sudo rm /etc/sudoers.d/30-alice
    sudo visudo -c
    sudo -lU alice                         # should now say "not allowed"

Common pitfalls

  • Editing /etc/sudoers with nano or vim directly. One syntax error and you cannot sudo to fix it. Always visudo.
  • A sudoers drop-in with mode 0644 or 0664 — sudo silently ignores it. Must be 0440, owner root:root.
  • NOPASSWD: ALL for an operator account — the password prompt is your last line of defence against an unattended terminal.
  • Forgetting that sudo caches authentication per terminal — sudo -K invalidates the cache for the current session if you need to test re-prompting.
  • Wildcards in command paths can be tricky: NOPASSWD: /bin/systemctl restart * lets the user restart any service including critical ones; tighten the wildcard or list explicit services.
  • Adding a Defaults env_keep for variables like LD_LIBRARY_PATH — opens a privilege-escalation hole. Only add env_keep for variables you have audited.

In our managed engagements, sudoers entries are checked into the same Git repo that holds the operator-key inventory and reviewed at the same cadence. New entries require a pull request with two approvers. The result is that a question like “who, on which host, can restart Postgres without a password” has a one-line answer pulled straight from the source of truth — that auditability is part of the Managed Operations access posture.