sudoers and visudo: Granting rights selectively
In short: In /etc/sudoers you define who may execute which commands as root; with visudo and files in /etc/sudoers.d you grant only the necessary rights instead of full root access.
In more detail: sudo runs commands with higher privileges and logs it. Whoever is in the group sudo (Debian/Ubuntu) or wheel (Fedora/Arch) may usually do everything. Finer control comes with the sudoers configuration.
In Depth
Editing only with visudo
sudo visudo (or sudo visudo -f /etc/sudoers.d/webadmin) checks the syntax before saving; an error in /etc/sudoers can lock sudo completely. Own rules belong in separate files under /etc/sudoers.d/ (permissions 0440).
Example rules
# User mia may do everything (with password)
mia ALL=(ALL:ALL) ALL
# Group webadmin may only reload nginx, without password
%webadmin ALL=(root) NOPASSWD: /bin/systemctl reload nginx, /bin/systemctl restart nginx
# User deploy may run a script as www-data
deploy ALL=(www-data) /usr/local/bin/deploy.sh
Format: who where=(as_whom) what. Give absolute paths, fix arguments (otherwise the command may take arbitrary arguments). NOPASSWD only for narrowly limited commands (automation).
Security pitfalls
- Allowing commands with shell escape (vim, less, find, python, git, tar) in sudo = effectively a root shell (see GTFOBins). Better
sudoedit. - Wildcards (
*) in commands are risky. - Writable scripts in sudo commands: whoever can change them becomes root.
ALL=(ALL) NOPASSWD: ALLonly in throwaway VMs.- Do not loosen environment (
env_reset,secure_path). - With
sudo -lshow your own rights,sudo -kresets the timestamp. - Logs:
/var/log/auth.logorjournalctl _COMM=sudo.
Practice and alternatives
Least privilege: services under own users (without login shell), do not put users blanketly into the sudo group. Disable root login via SSH, keys instead of passwords. Alternatives: doas (OpenBSD, lean), polkit (desktop actions), systemd-run, capabilities (setcap) for individual rights, containers/rootless. Regularly check who may sudo (getent group sudo).
See also: sudo and root rights, Least privilege, Users, groups and file permissions, SSH config