sudo & least privilege
Grant exactly what is needed, attributably.
You rarely log in as root — instead you run individual commands as root with sudo. This is a core security practice for two reasons: it means people work as their normal, limited selves by default and only elevate for the specific action that needs it, and every sudo use is logged with who ran what, when. sudo turns "root did something" into "deploy ran this exact command as root at 10:04," which is the accountability the previous lesson demanded.
$ sudo systemctl restart nginx # run one command as root; prompts for YOUR password$ sudo -l # what am I allowed to run with sudo?$ sudo -u postgres psql # run as a specific user, not just root# every use is recorded:$ sudo grep sudo /var/log/auth.log | tail -1... deploy : TTY=pts/0 ; PWD=/home/deploy ; USER=root ; COMMAND=/bin/systemctl restart nginx
Who can sudo, and to do what
Sudo rights are granted by membership in a group (sudo on Debian/Ubuntu, wheel on RHEL) or by explicit rules in /etc/sudoers. The important idea is that sudoers can be as narrow as you like: instead of "deploy can run anything as root," you can grant "deploy can run exactly systemctl restart nginx and nothing else." That is least privilege applied to administration — give each person or service account the specific elevated commands their job needs, not a blanket root.
# grant a narrow, specific privilege — not blanket rootdeploy ALL=(root) NOPASSWD: /bin/systemctl restart nginx, /bin/systemctl reload nginx# edit sudoers ONLY with visudo, which syntax-checks before saving# $ sudo visudo -f /etc/sudoers.d/deploy
Always edit sudoers with visudo
The sudoers file controls who can become root, so a syntax error in it can lock everyone out of admin access. visudo exists to prevent that: it opens the file, and validates the syntax before saving, refusing to write a broken file. Never edit /etc/sudoers directly with a plain editor — always use visudo (or drop files into /etc/sudoers.d/ via visudo -f), so a typo cannot leave you unable to fix your own mistake.