EMZETT.
Login

sudo and root: Borrowing privileges selectively

In short: With sudo an ordinary user runs individual commands with the rights of another user (usually root) after identifying with their own password.

In more detail: The user root may do everything on Linux and can therefore also break everything. That is why you work with a normal account in everyday use and get administrator rights only for individual commands: sudo (“superuser do”). That way it is traceable who did what, and a typing error only takes effect where you deliberately elevate.

In Depth

Basic use

sudo apt update              # run a command as root
sudo -u postgres psql        # as another user
sudo -i                      # interactive root shell (use sparingly)
sudo -l                      # show what you may do
sudo !!                      # repeat last command, this time with sudo

The password is remembered for a few minutes. A good habit: read the “Permission denied” message, do not blindly put sudo in front, but check whether the command really needs these rights.

The configuration: sudoers

Who may use sudo is defined in /etc/sudoers and in files under /etc/sudoers.d/. Edit only with visudo, which checks the syntax, otherwise you can lock yourself out. Examples:

%sudo   ALL=(ALL:ALL) ALL                 # group sudo may do everything
anna    ALL=(root) /usr/bin/systemctl restart nginx   # only this command

On Debian/Ubuntu the first user belongs to the group sudo, on Fedora/RHEL to the group wheel.

Rules of caution

  • Work as root as little as possible (principle of least privilege).
  • Do not start graphical programs or scripts from untrusted sources with sudo.
  • With redirections sudo only affects the command, not the redirection: sudo echo x > /etc/file fails; the right way is echo x | sudo tee /etc/file.
  • All sudo calls end up in the log (journalctl _COMM=sudo or /var/log/auth.log).

Alternatives

su switches the user completely and asks for the target’s password. doas (OpenBSD, also on Linux) is a leaner replacement. For finer rights there are Linux capabilities, Polkit for graphical interfaces and role models such as SELinux. The root account itself is locked for login on many systems.

See also: Users, groups and file permissions, Principle of least privilege, SELinux and AppArmor