Files
oam/knowledge base/sudo.md
2024-02-03 15:37:44 +01:00

3.6 KiB

Sudo

  1. TL;DR
  2. Drop privileges
  3. Avoid the need of providing a password
  4. Only allow specific commands
  5. Execute commands as a specific user
  6. Troubleshooting
    1. I modified a sudoers file manually, messed it up, and now I cannot use sudo anymore
  7. Sources

TL;DR

Avoid modifying the sudoers files manually, and execute visudo instead.
It will check the syntax on save, preventing you from screwing up the file.

Defaults:

Path Type OS
/etc/sudoers file All
/etc/sudoers.d included directory Linux
/private/etc/sudoers.d included directory Mac OS X

Sudoers files use the Extended Backus-Naur Form (EBNF) grammar.

Files in included directories are loaded in sorted lexical order.
Files which name ends in ~ or contains . are skipped to avoid causing problems with package manager or temporary or backup files.

When multiple entries match for the same user, they are applied in order.
Where there are multiple matches, the last match is used (which is not necessarily the most specific one).

# Make changes to a sudoers file.
visudo
visudo -f '/etc/sudoers.d/custom'

# Check the syntax of a sudoers file.
visudo -c
visudo -csf '/etc/sudoers.d/lana'

Drop privileges

# Invalidate the user's cached credentials.
sudo -k

# Ignore the user's cached credentials for the given command only.
sudo -k ls

Avoid the need of providing a password

# file '/etc/sudoers.d/adam'
adam ALL=(ALL:ALL) NOPASSWD: ALL

Only allow specific commands

# file '/etc/sudoers.d/ginny'
Cmnd_Alias UPGRADE_CMND  = /usr/bin/apt update, /usr/bin/apt list --upgradable, /usr/bin/apt upgrade
Cmnd_Alias SHUTDOWN_CMND = /sbin/shutdown
ginny ALL=(ALL:ALL) SHUTDOWN_CMND, UPGRADE_CMND, ls

Execute commands as a specific user

Invoke a login shell using the -i, --login option.
When not specifying a command, a login shell prompt is returned; otherwise, the output of the given command is returned:

% sudo -i -u 'johnny'
$ whoami
johnny

% sudo -i -u 'cynthia' whoami
cynthia

Troubleshooting

I modified a sudoers file manually, messed it up, and now I cannot use sudo anymore

Should you see something similar to this when using sudo:

$ sudo visudo
>>> /etc/sudoers: syntax error near line 28 <<<
sudo: parse error in /etc/sudoers near line 28
sudo: no valid sudoers sources found, quitting

try using another access method like PolicyKit and fix the file up:

pkexec visudo -f '/etc/sudoers.d/michael'

Sources