What least privilege means
Least privilege means every user, service and script has only the minimum rights it needs, for as long as it needs them. When an account is compromised, the damage is limited to what that account could do. On Linux this means:
- Do not log in and work as
root; use a personal account andsudowhen needed. - Run each service under its own system account (
nginx,postgres) with the shell/usr/sbin/nologin. - Remove or lock unused accounts (
sudo usermod -L olduser) and set expiry dates on temporary ones.
Granting sudo under control
Sudo rights live in /etc/sudoers and in files under /etc/sudoers.d/. Always edit them with visudo, which locks the file and checks the syntax before saving: one syntax error in sudoers can lock you out of admin rights.
# /etc/sudoers.d/deploy
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp
%devops ALL=(ALL:ALL) ALL
The first line lets user deploy restart exactly one service without a password. The second gives group devops full rights but still asks for a password. Granting specific commands is much safer than ALL.
flowchart LR
U["user deploy"] -- "sudo systemctl restart myapp" --> S{"sudoers"}
S -- "rule matches" --> OK["Runs as root"]
S -- "other command" --> NO["Denied and logged"]
Common traps
- Allowing commands that can spawn a shell, such as
vim,less,findorbash, through sudo: the user can escape to a root shell. The GTFOBins project lists such programs. - Using relative paths in rules; always write absolute paths such as
/usr/bin/systemctl. - Editing
/etc/sudoersdirectly withnano, saving a broken file and then having no sudo left to fix it.
| Command | Meaning |
|---|---|
sudo -l |
Which commands you may run through sudo |
sudo visudo -f /etc/sudoers.d/deploy |
Safely edit a separate sudoers file |
sudo -u postgres psql |
Run a command as another user, not root |
sudo journalctl _COMM=sudo |
Review the history of sudo use |