CoursesLinux hardeningAccess hardening

Hardening sudo

Narrow rules, logging, and the escape hatches.

Intermediate10 min · lesson 4 of 16

The essentials course introduced sudo for least privilege; hardening it means tightening the rules and closing the escape hatches. Two defaults are worth turning on everywhere: log every sudo command’s I/O for an audit trail, and require re-authentication rather than long password-free windows. But the real work is auditing what your sudoers actually grant, because a too-broad rule quietly turns least privilege back into blanket root.

/etc/sudoers.d/hardening
Defaults logfile=/var/log/sudo.log
Defaults log_input, log_output # record what was typed/output
Defaults timestamp_timeout=5 # re-auth after 5 min, not the default 15
Defaults !visiblepw, use_pty # never accept a password on a visible tty
Defaults requiretty # sudo only from a real terminal

The GTFOBins problem

The subtle danger in sudoers is granting a command that can be turned into a shell. Many ordinary programs — vi, less, find, tar, awk, even man — can spawn a shell or run arbitrary commands from inside them, so "user may run vi as root" is really "user may become root." This class of escape is catalogued (GTFOBins), and the lesson is to be extremely wary of granting sudo to any program that can execute other programs or edit arbitrary files. Prefer purpose-built, non-interactive commands.

terminal
# why "sudo less /var/log/x" is dangerous — less can spawn a root shell:
# (inside less) !sh → you are now root
# so NEVER grant sudo to less, vi, find, tar, awk, systemctl edit, etc. as a catch-all.
# audit what is granted:
$ sudo grep -rE 'ALL|NOPASSWD' /etc/sudoers /etc/sudoers.d/

Narrow, specific, no wildcards

A safe sudo rule names a specific binary with specific, safe arguments and no wildcards that an attacker can exploit. "Restart nginx" should be exactly /bin/systemctl restart nginx, not /bin/systemctl * (which would allow systemctl to run arbitrary units or edit them). Every wildcard and every shell-capable target widens the grant beyond what you intended. Review sudoers with the same suspicion you apply to SUID binaries — both answer "how does an ordinary user become root?"

A broad sudo rule is a root shell with extra steps
The most common privilege-escalation finding on real Linux hosts is not a kernel exploit — it is a sudoers rule that grants a shell-capable command, a wildcard, or NOPASSWD: ALL. Any process running as that user inherits the path to root. Grant the narrowest possible command, avoid shell-capable programs, ban wildcards, and treat the sudoers file as one of the highest-value security configs on the box.