Linux sudoers Explained: How sudo Really Works (and How to Lock It Down)


Every Linux user knows sudo. You type it, enter your password, and suddenly you can do anything. But what actually happens between typing the command and getting root? And why do so many security guides call a badly configured sudoers file one of the easiest privilege-escalation paths on a system? Once you understand the mechanism, the mistakes become obvious — and easy to fix.

How sudo Decides

When you run sudo, the program checks a file called /etc/sudoers and any files in /etc/sudoers.d/. That file lists which users and groups may run which commands, as which user, and whether a password is required. If your name is not in there, you get the famous "user is not in the sudoers file" message.

The most common entry looks like this:

youruser ALL=(ALL:ALL) ALL

It means: this user, on all hosts, may run all commands as any user and any group. The first ALL is the host, (ALL:ALL) is the user and group to run as, and the final ALL is the command list. Groups work the same way — the %sudo group entry is how most distributions give admin rights.

The Rules You Should Never Break

  • Always edit with visudo, never with a text editor. visudo checks your syntax before saving. One typo in /etc/sudoers can lock every admin out of sudo, and fixing that usually means booting into recovery mode.
  • Never give NOPASSWD to a whole user or group. NOPASSWD: ALL means anyone who reaches that account — through a stolen session, a running process, or a misconfigured service — gets root without a password.
  • Do not allow sudo for text editors, shells, or pagers. Giving someone sudo vim or sudo less is the same as giving them root, because those programs can spawn a shell with :shell or !bash.
  • Prefer specific commands over ALL. If a user only needs to restart one service, write youruser ALL=(root) /bin/systemctl restart nginx instead of a blanket grant.

Checking and Hardening Your Own Box

Run sudo -l to see exactly what your account can do — it prints your effective permissions. Then check for the classic problems:

# Who has passwordless sudo?
sudo grep -r NOPASSWD /etc/sudoers /etc/sudoers.d/

# Who is in the sudo group?
getent group sudo

# Tighten the password timeout (default is 15 minutes)
echo 'Defaults timestamp_timeout=5' | sudo tee /etc/sudoers.d/timeout

Shortening the timeout means a stolen terminal session gives an attacker minutes, not a quarter of an hour. And if a user no longer needs admin rights, remove them from the sudo group immediately — old accounts with sudo are one of the most common findings in real audits.

sudo is a powerful tool, but it is only as safe as its configuration. Spend ten minutes reading your own sudoers file today. What you find might surprise you.

Comments

Popular Posts