HackBlue

Tools · Linux command line for security · 06 / 28

How to configure sudo safely: visudo, sudoers.d, and least privilege

Edit sudoers without locking yourself out, grant one command instead of ALL, avoid rules that hand out a root shell, and audit who can sudo.

11 min read · practice only with authorization

Edit with visudo

Never edit /etc/sudoers with a plain editor. visudo locks the file and checks syntax before saving, so a typo does not leave you without sudo. Prefer drop-in files under /etc/sudoers.d/, edited with visudo -f /etc/sudoers.d/name, so each grant is a small reviewable file.

A rule reads: who, on which hosts, as which user, may run which commands. alice ALL=(root) /usr/bin/systemctl restart nginx lets alice restart nginx as root and nothing else.

Snippet
sudo visudo -f /etc/sudoers.d/web-ops
# contents
%webops ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx

sudo visudo -c

Rules that grant more than they say

Many programs can start other programs. A rule allowing vim, less, find, awk, python, tar, or git as root effectively grants a root shell, because each can execute commands. Wildcards are another trap: /usr/bin/systemctl * includes systemctl edit, which opens an editor as root.

NOPASSWD removes the re-authentication step. Use it only for automation accounts with narrow commands, never for broad grants to people.

Lab: audit and tighten

On a lab VM, give a test user the broad rule ALL=(ALL) NOPASSWD: ALL, then replace it with a narrow rule for one service restart. As the test user, run sudo -l to see what is allowed, confirm the restart works, and confirm sudo less /etc/shadow is refused.

Then list everyone who can use sudo: members of the sudo or wheel group plus any user or group named in sudoers files. That list belongs in your access review.

Snippet
sudo -l -U testuser
getent group sudo wheel
sudo grep -rhv "^#" /etc/sudoers /etc/sudoers.d/ | grep -v "^
quot; journalctl _COMM=sudo --since today

Log every use

sudo logs each command to the authentication log or the journal, including the user, terminal, working directory, and command. Forward those logs off the host. Defaults log_output plus sudoreplay can record full session I/O for high-risk accounts.

Alert on sudo from accounts that rarely use it and on sudo su or sudo -i, which open root shells and make later commands harder to attribute.

Diagram

A broad sudo grant versus a narrow one

Both let the web team restart nginx.

Broad

Rule. %webops ALL=(ALL) NOPASSWD: ALL

Effect. Any command as root without a password.

Audit. Every member is effectively root.

Narrow

Rule. %webops ALL=(root) /usr/bin/systemctl restart nginx

Effect. One command, with password.

Audit. Easy to review and log.

Check yourself

1. Why use visudo instead of editing /etc/sudoers directly?

2. Why is allowing sudo less effectively granting root?

3. Which command shows what a specific user may run with sudo?