Sudo: Difference between revisions
m (fix link) |
NetSysFire (talk | contribs) (→Tips and tricks: - add #Using U2F) |
||
(108 intermediate revisions by 41 users not shown) | |||
Line 1: | Line 1: | ||
[[Category:Security]] | [[Category:Security]] | ||
[[Category:Commands]] | [[Category:Commands]] | ||
[[ | [[de:sudo]] | ||
[[es:Sudo]] | [[es:Sudo]] | ||
[[fr:Sudo]] | [[fr:Sudo]] | ||
[[ja:Sudo]] | [[ja:Sudo]] | ||
[[pt:Sudo]] | |||
[[ru:Sudo]] | [[ru:Sudo]] | ||
[[ | [[uk:Sudo]] | ||
[[zh-hans:Sudo]] | [[zh-hans:Sudo]] | ||
{{Related articles start}} | {{Related articles start}} | ||
{{Related|Users and groups}} | {{Related|Users and groups}} | ||
{{Related|su}} | {{Related|su}} | ||
{{Related|doas}} | |||
{{Related articles end}} | {{Related articles end}} | ||
[https://www.sudo.ws/sudo/ Sudo] allows a system administrator to delegate authority to give certain users—or groups of users—the ability to run commands as root or another user while providing an audit trail of the commands and their arguments. | [https://www.sudo.ws/sudo/ Sudo] allows a system administrator to delegate authority to give certain users—or groups of users—the ability to run commands as root or another user while providing an audit trail of the commands and their arguments. | ||
Sudo is an alternative to [[su]] for running commands as root. Unlike [[su]], which launches a root shell that allows all further commands root access, sudo instead grants temporary privilege | Sudo is an alternative to [[su]] for running commands as root. Unlike [[su]], which launches a root shell that allows all further commands root access, sudo instead grants temporary privilege elevation to a single command. By enabling root privileges only when needed, sudo usage reduces the likelihood that a typo or a bug in an invoked command will ruin the system. | ||
Sudo can also be used to run commands as other users; additionally, sudo logs all commands and failed access attempts for security auditing. | Sudo can also be used to run commands as other users; additionally, sudo logs all commands and failed access attempts for security auditing. | ||
Line 37: | Line 37: | ||
See {{man|8|sudo}} for more information. | See {{man|8|sudo}} for more information. | ||
=== Login shell === | |||
You cannot run every command as an other user simply by prepending ''sudo''. In particular when using a [[Wikipedia:Redirection_(computing)|redirection]] and [[Wikipedia:Command substitution|command substitution]], you must use a login shell, which can be easily accessed with {{ic|sudo -iu ''user''}} (one can omit {{ic|-u ''user''}} if the desired user is root). | |||
In the following example command substitution would work in a full shell, but fails with prepending ''sudo'': | |||
{{hc|$ sudo wpa_supplicant -B -i ''interface'' -c '''<('''wpa_passphrase ''MYSSID passphrase''''')'''| | |||
Successfully initialized wpa_supplicant | |||
Failed to open config file '/dev/fd/63', error: No such file or directory | |||
Failed to read or parse configuration '/dev/fd/63' | |||
}} | |||
== Configuration == | == Configuration == | ||
{{Expansion| | {{Expansion|Create an intro discussing {{ic|Defaults}}, perhaps with a table that lists common settings}} | ||
=== Defaults skeleton === | |||
{{man|5|sudoers|SUDOERS OPTIONS}} lists all the options that can be used with the {{ic|Defaults}} command in the {{ic|/etc/sudoers}} file. | |||
See [https://gist.github.com/AladW/7eca9799b9ea624eca31] for a list of options (parsed from the version 1.8.7 source code) in a format optimized for {{ic|sudoers}}. | |||
See {{man|5|sudoers}} for more information, such as configuring the password timeout. | See {{man|5|sudoers}} for more information, such as configuring the password timeout. | ||
Line 50: | Line 68: | ||
=== Using visudo === | === Using visudo === | ||
The configuration file for sudo is {{ic|/etc/sudoers}}. It should '''always''' be edited with the {{man|8|visudo}} command. | The configuration file for sudo is {{ic|/etc/sudoers}}. It should '''always''' be edited with the {{man|8|visudo}} command. ''visudo'' locks the {{ic|sudoers}} file, saves edits to a temporary file, and checks it for syntax errors before copying it to {{ic|/etc/sudoers}}. | ||
{{Warning| | {{Warning| | ||
* It is imperative that {{ic|sudoers}} be free of syntax errors! Any error makes sudo unusable. '''Always''' edit it with | * It is imperative that {{ic|sudoers}} be free of syntax errors! Any error makes sudo unusable. '''Always''' edit it with ''visudo'' to prevent errors. | ||
* | * {{man|8|visudo}} warns that configuring ''visudo'' to honor the user environment variables for their editor of choice may be a security hole, since it allows the user with ''visudo'' privileges to run arbitrary commands as root without logging simply by setting that variable to something else. | ||
}} | }} | ||
The default editor for visudo is {{ | The default editor for ''visudo'' is ''vi''. The {{Pkg|sudo}} package is compiled with {{ic|--with-env-editor}} and honors the use of the {{ic|SUDO_EDITOR}}, {{ic|VISUAL}} and {{ic|EDITOR}} variables. {{ic|EDITOR}} is not used when {{ic|VISUAL}} is set. | ||
To establish nano as the | To establish [[nano]] as the ''visudo'' editor for the duration of the current shell session, export {{ic|1=EDITOR=nano}}; to use a different editor just once simply set the variable before calling ''visudo'': | ||
# EDITOR=nano visudo | # EDITOR=nano visudo | ||
Alternatively you may edit a copy of the {{ic|/etc/sudoers}} file and check it using {{ic|visudo -c | Alternatively you may edit a copy of the {{ic|/etc/sudoers}} file and check it using {{ic|visudo -c ''/copy/of/sudoers''}}. This might come in handy in case you want to circumvent locking the file with ''visudo''. | ||
To change the editor permanently, see [[Environment variables#Per user]]. To change the editor of choice permanently system-wide only for | To change the editor permanently, see [[Environment variables#Per user]]. To change the editor of choice permanently system-wide only for ''visudo'', add the following to {{ic|/etc/sudoers}} (assuming [[nano]] is your preferred editor): | ||
# Set default EDITOR to restricted version of nano, and do not allow visudo to use EDITOR/VISUAL. | |||
Defaults editor=/usr/bin/rnano, !env_editor | |||
# Set default EDITOR to nano, and do not allow visudo to use EDITOR/VISUAL. | |||
Defaults editor=/usr/bin/ | |||
=== Example entries === | === Example entries === | ||
To allow a user to gain full root privileges when | To allow a user to gain full root privileges when they precede a command with {{ic|sudo}}, add the following line: | ||
USER_NAME ALL=(ALL) ALL | USER_NAME ALL=(ALL:ALL) ALL | ||
To allow a user to run all commands as any user but only on the machine with hostname {{ic|HOST_NAME}}: | To allow a user to run all commands as any user but only on the machine with hostname {{ic|HOST_NAME}}: | ||
USER_NAME HOST_NAME=(ALL) ALL | USER_NAME HOST_NAME=(ALL:ALL) ALL | ||
To allow members of group [[wheel]] sudo access: | |||
%wheel ALL=(ALL:ALL) ALL | |||
{{Tip|When creating new administrators, it is often desirable to enable sudo access for the {{ic|wheel}} group and [[Users and groups#Group management|add the user to it]], since by default [[Polkit#Administrator identities|Polkit]] treats the members of the {{ic|wheel}} group as administrators. If the user is not a member of {{ic|wheel}}, software using Polkit may ask to authenticate using the root password instead of the user password.}} | |||
To disable asking for a password for user {{ic|USER_NAME}}: | To disable asking for a password for user {{ic|USER_NAME}}: | ||
{{Warning|This will | {{Warning|This will allow any process running with your user name to use sudo without asking for permission.}} | ||
Defaults:USER_NAME !authenticate | Defaults:USER_NAME !authenticate | ||
Line 99: | Line 117: | ||
Enable explicitly defined commands only for user {{ic|USER_NAME}} on host {{ic|HOST_NAME}} without password: | Enable explicitly defined commands only for user {{ic|USER_NAME}} on host {{ic|HOST_NAME}} without password: | ||
USER_NAME HOST_NAME= NOPASSWD: /usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu | USER_NAME HOST_NAME= NOPASSWD: /usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu | ||
Line 111: | Line 130: | ||
== Tips and tricks == | == Tips and tricks == | ||
=== Disable password prompt timeout === | |||
A common annoyance is a long-running process that runs on a background terminal somewhere that runs with normal permissions and elevates only when needed. This leads to a sudo password prompt which goes unnoticed and times out, at which point the process dies and the work done is lost or, at best, cached. Common advice is to enable passwordless sudo, or extend the timeout of sudo remembering a password. Both of these have negative security implications. The '''prompt''' timeout can also be disabled and since that does not serve any reasonable security purpose it should be the solution here: | |||
Defaults passwd_timeout=0 | |||
=== Add terminal bell to the password prompt === | |||
To draw attention to a sudo prompt in a background terminal, users can simply make it echo a [[Wikipedia:Bell character|bell character]]: | |||
Defaults passprompt="<span style="color:#ebf1f5; background-color:#222222;">^G</span>[sudo] password for %p: " | |||
Note the {{ic|1=<span style="color:#ebf1f5; background-color:#222222;">^G</span>}} is a literal bell character. E.g. in [[vim]], insert using the sequence {{ic|Ctrl+v}} {{ic|Ctrl+g}}. If {{ic|Ctrl+v}} is mapped, e.g. for pasting, one can [https://unix.stackexchange.com/a/366875 usually] use {{ic|Ctrl+q}} instead. In [[nano]], {{ic|Alt+v}} {{ic|Ctrl+g}}. | |||
{{Expansion|Is it possible to preserve the localized prompt while using bell? The same question for the case when SUDO_PROMPT is used. Is there an alternative, for example by using "-B" option as default? }} | |||
Another option is to set the {{ic|SUDO_PROMPT}} [[environment variable]]. For example, add the following to your shell configuration file: | |||
export SUDO_PROMPT=$'\a[sudo] please enter a password: ' | |||
=== Passing aliases === | |||
Aliases in [[Zsh]] and [[Bash]] are normally only expanded for the first word in a command. This means that your aliases will not normally get expanded when running the {{ic|sudo}} command. One way to make the next word expand is to make an alias for sudo ending with a space. Add the following to your [[Command-line shell#Configuration files|shell's configuration file]]: | |||
alias sudo='sudo ' | |||
{{man|1|zshmisc|ALIASING}} describes how this works: | |||
: If the replacement text ends with a space, the next word in the shell input is always eligible for purposes of alias expansions. | |||
As well as {{man|1|bash|ALIASES}}: | |||
: If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion. | |||
=== Disable per-terminal sudo === | === Disable per-terminal sudo === | ||
Line 116: | Line 167: | ||
{{Warning|This will let any process use your sudo session.}} | {{Warning|This will let any process use your sudo session.}} | ||
If you are annoyed by sudo's defaults that require you to enter your password every time you open a new terminal, | If you are annoyed by sudo's defaults that require you to enter your password every time you open a new terminal, set {{ic|timestamp_type}} to {{ic|global}}: | ||
Defaults | Defaults timestamp_type=global | ||
=== Reduce the number of times you have to type a password === | |||
If you are annoyed that you have to re-enter your password every 5 minutes (default), you can change this by setting a longer value for {{ic|timestamp_timeout}} (in minutes): | |||
Defaults timestamp_timeout=10 | |||
If you are using a lot of sudo commands on a row, it is more logical to refresh the timeout every time you use sudo than | |||
to increase {{ic|timestamp_timeout}}. Refreshing the timeout can be done with {{ic|sudo -v}} (whereas {{ic|sudo -K}} revokes immediately). | |||
{{Accuracy|Default {{ic|sudo}} usage already refreshes timeout.|section=Remove alias recommendation in "Reduce the number of times you have to type a password"?}} | |||
You might want to automate this by adding the following to your [[Environment variables#Using shell initialization files|shell initialization files]]: | |||
alias sudo='sudo -v; sudo ' | |||
It is also possible to use a bash function; for more details see [https://unix.stackexchange.com/questions/584725/expand-certain-aliases-from-within-sudo-bash-function stackexchange]. | |||
=== Environment variables === | === Environment variables === | ||
If you have a lot of environment variables, or you export your proxy settings via {{ic|1=export http_proxy="..."}}, when using sudo these variables do not get passed to the root account unless you run sudo with the {{ic|-E}} option. | If you have a lot of environment variables, or you export your proxy settings via {{ic|1=export http_proxy="..."}}, when using sudo these variables do not get passed to the root account unless you run sudo with the {{ic|-E}}/{{ic|--preserve-env}} option. | ||
$ sudo -E pacman -Syu | $ sudo -E pacman -Syu | ||
Line 128: | Line 195: | ||
The recommended way of preserving environment variables is to append them to {{ic|env_keep}}: | The recommended way of preserving environment variables is to append them to {{ic|env_keep}}: | ||
{{hc|/etc/sudoers| | {{hc|/etc/sudoers|2= | ||
Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy" | Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy" | ||
}} | |||
=== Root password === | === Root password === | ||
Users can configure sudo to ask for the root password instead of the user password by adding {{ic|targetpw}} (target user, defaults to root) or {{ic|rootpw}} to the Defaults line in {{ic|/etc/sudoers}}: | Users can configure sudo to ask for the root password instead of the user password by adding {{ic|targetpw}} (target user, defaults to root) or {{ic|rootpw}} to the Defaults line in {{ic|/etc/sudoers}}: | ||
Defaults targetpw | Defaults targetpw | ||
To prevent exposing your root password to users, you can restrict this to a specific group: | To prevent exposing your root password to users, you can restrict this to a specific group: | ||
Defaults:%wheel targetpw | Defaults:%wheel targetpw | ||
%wheel ALL=(ALL) ALL | %wheel ALL=(ALL) ALL | ||
Line 153: | Line 216: | ||
{{Warning| | {{Warning| | ||
* Be careful, you may lock yourself out by disabling root login. Sudo is not automatically installed and its default configuration allows neither passwordless root access nor root access with your own password. Ensure a user is properly configured as a sudoer ''before'' disabling the root account! | * Be careful, you may lock yourself out by disabling root login. Sudo is not automatically installed and its default configuration allows neither passwordless root access nor root access with your own password. Ensure a user is properly configured as a sudoer ''before'' disabling the root account! | ||
* If you have changed your sudoers | * If you have changed your sudoers file to use rootpw as default, then do not disable root login with any of the following commands! | ||
* If you are already locked out, see [[Password recovery]] for help.}} | * If you are already locked out, see [[Password recovery]] for help. | ||
}} | |||
The account can be locked via {{ic|passwd}}: | The account can be locked via {{ic|passwd}}: | ||
Line 164: | Line 228: | ||
$ sudo passwd -u root | $ sudo passwd -u root | ||
Alternatively, edit {{ic|/etc/shadow}} and replace the root's encrypted password with | Alternatively, edit {{ic|/etc/shadow}} and replace the root's encrypted password with {{ic|!*}}: | ||
root:!:12345:::::: | root:!*:12345:::::: | ||
To enable root login again: | To enable root login again: | ||
Line 176: | Line 240: | ||
==== kdesu ==== | ==== kdesu ==== | ||
kdesu may be used under KDE to launch GUI applications with root privileges. It is possible that by default kdesu will try to use su even if the root account is disabled. Fortunately one can tell kdesu to use sudo instead of su. Create/edit the file {{ic|~/.config/kdesurc}}: | kdesu may be used under [[KDE]] to launch GUI applications with root privileges. It is possible that by default kdesu will try to use su even if the root account is disabled. Fortunately one can tell kdesu to use sudo instead of su. Create/edit the file {{ic|~/.config/kdesurc}}: | ||
[super-user-command] | [super-user-command] | ||
Line 185: | Line 249: | ||
$ kwriteconfig5 --file kdesurc --group super-user-command --key super-user-command sudo | $ kwriteconfig5 --file kdesurc --group super-user-command --key super-user-command sudo | ||
=== Harden with sudo example === | |||
Let us say you create 3 users: admin, devel, and archie. The user "admin" is used for journalctl, systemctl, mount, kill, and iptables; "devel" is used for installing packages, and editing configuration files; and "archie" is the user you log in with. To let "archie" reboot, shutdown, and use netctl we would do the following: | |||
Edit {{ic|/etc/pam.d/su}} and {{ic|/etc/pam.d/su-l}}. Require user be in the wheel group, but do not put anyone in it. | |||
#%PAM-1.0 | #%PAM-1.0 | ||
auth sufficient pam_rootok.so | auth sufficient pam_rootok.so | ||
Line 203: | Line 265: | ||
session required pam_unix.so | session required pam_unix.so | ||
Limit SSH login to the 'ssh' group. Only " | Limit SSH login to the 'ssh' group. Only "archie" will be part of this group. | ||
groupadd -r ssh | |||
gpasswd -a | # groupadd -r ssh | ||
echo 'AllowGroups ssh' >> /etc/ssh/sshd_config | # gpasswd -a archie ssh | ||
# echo 'AllowGroups ssh' >> /etc/ssh/sshd_config | |||
[[Restart]] {{ic|sshd.service}}. | [[Restart]] {{ic|sshd.service}}. | ||
Add users to other groups. | Add users to other groups. | ||
for g in power network ;do ;gpasswd -a | |||
for g in network power storage ;do ;gpasswd -a admin $g ;done | # for g in power network ;do ;gpasswd -a archie $g ;done | ||
# for g in network power storage ;do ;gpasswd -a admin $g ;done | |||
Set permissions on configs so devel can edit them. | Set permissions on configs so devel can edit them. | ||
chown -R devel:root /etc/{http,openvpn,cups,zsh,vim,screenrc} | |||
# chown -R devel:root /etc/{http,openvpn,cups,zsh,vim,screenrc} | |||
Cmnd_Alias POWER = /usr/bin/shutdown -h now, /usr/bin/halt, /usr/bin/poweroff, /usr/bin/reboot | Cmnd_Alias POWER = /usr/bin/shutdown -h now, /usr/bin/halt, /usr/bin/poweroff, /usr/bin/reboot | ||
Line 231: | Line 296: | ||
admin ALL = (root) SYSTEMD, KILL, FIREWALL | admin ALL = (root) SYSTEMD, KILL, FIREWALL | ||
devel ALL = (root) PKGMAN | devel ALL = (root) PKGMAN | ||
archie ALL = (devel) SHELL, (admin) SHELL | |||
With this setup, you will almost never need to login as the | With this setup, you will almost never need to login as the root user. | ||
" | "archie" can connect to their home WiFi. | ||
$ sudo netctl start home | |||
sudo | $ sudo poweroff | ||
"archie" can not use netctl as any other user. | |||
$ sudo -u admin -- netctl start home | |||
sudo - | |||
If " | When "archie" needs to use journalctl or kill run away process they can switch to that user. | ||
sudo -i -u admin | |||
admin | $ sudo -i -u devel | ||
admin | $ sudo -i -u admin | ||
But "archie" cannot switch to the root user. | |||
$ sudo -i -u root | |||
If "archie" want to start a gnu-screen session as admin they can do it like this: | |||
$ sudo -i -u admin | |||
[admin]$ chown admin:tty `echo $TTY` | |||
[admin]$ screen | |||
=== Configure sudo using drop-in files in /etc/sudoers.d === | === Configure sudo using drop-in files in /etc/sudoers.d === | ||
Line 261: | Line 331: | ||
* If there is a problem with a new entry, you can remove the offending file instead of editing {{ic|/etc/sudoers}} (but see the warning below). | * If there is a problem with a new entry, you can remove the offending file instead of editing {{ic|/etc/sudoers}} (but see the warning below). | ||
The format for entries in these drop-in files is the same as for {{ic|/etc/sudoers}} itself. To edit them directly, use {{ic|visudo -f /etc/sudoers.d/''somefile''}}. See | The format for entries in these drop-in files is the same as for {{ic|/etc/sudoers}} itself. To edit them directly, use {{ic|visudo -f /etc/sudoers.d/''somefile''}}. See {{man|5|sudoers|Including other files from within sudoers}} for details. | ||
The files in {{ic|/etc/sudoers.d/}} directory are parsed in lexicographical order, file names containing {{ic|.}} or {{ic|~}} are skipped. To avoid sorting problems, the file names should begin with two digits, e.g. {{ic|01_foo}}. | The files in {{ic|/etc/sudoers.d/}} directory are parsed in lexicographical order, file names containing {{ic|.}} or {{ic|~}} are skipped. To avoid sorting problems, the file names should begin with two digits, e.g. {{ic|01_foo}}. | ||
Line 271: | Line 341: | ||
=== Editing files === | === Editing files === | ||
{{ic|sudo | {{ic|sudo}} provides the {{ic|sudoedit}} command (equivalent to {{ic|sudo -e}}). This is useful for editing files which can be edited by root only while still running the editor as a normal user, and using that user’s configuration. | ||
To edit a file, set {{ic|SUDO_EDITOR}} to the name of the editor and pass the file name to {{ic|sudoedit}}. For example: | |||
$ SUDO_EDITOR=vim sudoedit /etc/file | |||
See [[#Using visudo]] and {{man|8|sudo|e}} for ways to set the editor, but beware of [[Security#Use sudo instead of su|possible security issues]]. | |||
If multiple names are passed to {{ic|sudo}}, all files are opened in the editor in a single invocation. A feature useful for merging files: | |||
$ SUDO_EDITOR=vimdiff sudoedit /etc/file /etc/file.pacnew | |||
=== Enable insults === | |||
Users can enable the insults easter egg in sudo by adding the following line in the {{ic|sudoers}} file with {{ic|visudo}}. | |||
{{hc|1=/etc/sudoers|2= | |||
Defaults insults | |||
}} | |||
Upon entering an incorrect password this will replace {{ic|Sorry, try again.}} message with humorous insults. | |||
=== Enable password input feedback === | |||
By default, there is no visual feedback when you input a password. That is done on purpose for extra security. However, if you wish to have visual input, you can enable it by adding this line: | |||
{{hc|/etc/sudoers|2= | |||
Defaults pwfeedback | |||
}} | |||
=== Colored password prompt === | |||
To customize the password prompt with colors and/or bold fonts, set the {{ic|SUDO_PROMPT}} [[environment variable]] in your shell initialization file and use {{man|1|tput}}. | |||
For example, to set the password prompt to display {{ic|Password: }} in bold red, use this: | |||
export SUDO_PROMPT="$(tput setaf 1 bold)Password:$(tput sgr0) " | |||
Or use different colors with the default message like so: | |||
export SUDO_PROMPT="$(tput setab 1 setaf 7 bold)[sudo]$(tput sgr0) $(tput setaf 6)password for$(tput sgr0) $(tput setaf 5)%p$(tput sgr0): " | |||
{{Merge|Color output in console|Not sudo-specific.}} | |||
{| | |||
|- | |||
| | |||
{| class="wikitable" | |||
|+ tput command line option cheatsheet | |||
|- | |||
! tput command !! Description | |||
|- | |||
| {{ic|tput bold}} || Bold text | |||
|- | |||
| {{ic|tput setaf [CODE]}} || Set foreground color | |||
|- | |||
| {{ic|tput setab [CODE]}} || Set background color | |||
|- | |||
| {{ic|tput rev}} || Inverse colors | |||
|- | |||
| {{ic|tput sgr0}} || Reset everything | |||
|} | |||
<br> | |||
<br> | |||
<br> | |||
|| || | |||
{| class="wikitable sortable" | |||
|+ tput color codes | |||
|- | |||
! tput color [CODE] !! Color | |||
|- | |||
| 0 || Black | |||
|- | |||
| 1 || Red | |||
|- | |||
| 2 || Green | |||
|- | |||
| 3 || Yellow | |||
|- | |||
| 4 || Blue | |||
|- | |||
| 5 || Magenta | |||
|- | |||
| 6 || Cyan | |||
|- | |||
| 7 || White | |||
|} | |||
|} | |||
=== Using U2F === | |||
U2F is great to use with sudo, as it can effectively eliminate the risk of [[Wikipedia:Shoulder surfing (computer security)|shoulder surfing]] in public areas while still giving you conscious control to approve the prompt with a simple physical touch. | |||
See [[Universal 2nd Factor#Passwordless sudo]]. | |||
== Troubleshooting == | == Troubleshooting == | ||
=== SSH TTY | === SSH problem without TTY === | ||
{{Merge|#Configuration}} | {{Merge|#Configuration}} | ||
SSH does not allocate a tty by default when running a remote command. Without | SSH does not allocate a tty by default when running a remote command. Without an allocated tty, sudo cannot prevent the password from being displayed. You can use ssh's {{ic|-t}} option to force it to allocate a tty. | ||
The {{ic|Defaults}} option {{ic|requiretty}} only allows the user to run sudo if they have a tty. | The {{ic|Defaults}} option {{ic|requiretty}} only allows the user to run sudo if they have a tty. | ||
Line 303: | Line 464: | ||
This sets sudo's umask to root's default umask (0022) and overrides the default behavior, always using the indicated umask regardless of what umask the user as set. | This sets sudo's umask to root's default umask (0022) and overrides the default behavior, always using the indicated umask regardless of what umask the user as set. | ||
Latest revision as of 05:33, 9 February 2024
Sudo allows a system administrator to delegate authority to give certain users—or groups of users—the ability to run commands as root or another user while providing an audit trail of the commands and their arguments.
Sudo is an alternative to su for running commands as root. Unlike su, which launches a root shell that allows all further commands root access, sudo instead grants temporary privilege elevation to a single command. By enabling root privileges only when needed, sudo usage reduces the likelihood that a typo or a bug in an invoked command will ruin the system.
Sudo can also be used to run commands as other users; additionally, sudo logs all commands and failed access attempts for security auditing.
Installation
Usage
To begin using sudo
as a non-privileged user, it must be properly configured. See #Configuration.
To use sudo, simply prefix a command and its arguments with sudo
and a space:
$ sudo cmd
For example, to use pacman:
$ sudo pacman -Syu
See sudo(8) for more information.
Login shell
You cannot run every command as an other user simply by prepending sudo. In particular when using a redirection and command substitution, you must use a login shell, which can be easily accessed with sudo -iu user
(one can omit -u user
if the desired user is root).
In the following example command substitution would work in a full shell, but fails with prepending sudo:
$ sudo wpa_supplicant -B -i interface -c <(wpa_passphrase MYSSID passphrase)
Successfully initialized wpa_supplicant Failed to open config file '/dev/fd/63', error: No such file or directory Failed to read or parse configuration '/dev/fd/63'
Configuration
Defaults skeleton
sudoers(5) § SUDOERS OPTIONS lists all the options that can be used with the Defaults
command in the /etc/sudoers
file.
See [1] for a list of options (parsed from the version 1.8.7 source code) in a format optimized for sudoers
.
See sudoers(5) for more information, such as configuring the password timeout.
View current settings
Run sudo -ll
to print out the current sudo configuration, or sudo -lU user
for a specific user.
Using visudo
The configuration file for sudo is /etc/sudoers
. It should always be edited with the visudo(8) command. visudo locks the sudoers
file, saves edits to a temporary file, and checks it for syntax errors before copying it to /etc/sudoers
.
- It is imperative that
sudoers
be free of syntax errors! Any error makes sudo unusable. Always edit it with visudo to prevent errors. - visudo(8) warns that configuring visudo to honor the user environment variables for their editor of choice may be a security hole, since it allows the user with visudo privileges to run arbitrary commands as root without logging simply by setting that variable to something else.
The default editor for visudo is vi. The sudo package is compiled with --with-env-editor
and honors the use of the SUDO_EDITOR
, VISUAL
and EDITOR
variables. EDITOR
is not used when VISUAL
is set.
To establish nano as the visudo editor for the duration of the current shell session, export EDITOR=nano
; to use a different editor just once simply set the variable before calling visudo:
# EDITOR=nano visudo
Alternatively you may edit a copy of the /etc/sudoers
file and check it using visudo -c /copy/of/sudoers
. This might come in handy in case you want to circumvent locking the file with visudo.
To change the editor permanently, see Environment variables#Per user. To change the editor of choice permanently system-wide only for visudo, add the following to /etc/sudoers
(assuming nano is your preferred editor):
# Set default EDITOR to restricted version of nano, and do not allow visudo to use EDITOR/VISUAL. Defaults editor=/usr/bin/rnano, !env_editor
Example entries
To allow a user to gain full root privileges when they precede a command with sudo
, add the following line:
USER_NAME ALL=(ALL:ALL) ALL
To allow a user to run all commands as any user but only on the machine with hostname HOST_NAME
:
USER_NAME HOST_NAME=(ALL:ALL) ALL
To allow members of group wheel sudo access:
%wheel ALL=(ALL:ALL) ALL
wheel
group and add the user to it, since by default Polkit treats the members of the wheel
group as administrators. If the user is not a member of wheel
, software using Polkit may ask to authenticate using the root password instead of the user password.To disable asking for a password for user USER_NAME
:
Defaults:USER_NAME !authenticate
Enable explicitly defined commands only for user USER_NAME
on host HOST_NAME
:
USER_NAME HOST_NAME=/usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu
%wheel
line if your user is in this group.Enable explicitly defined commands only for user USER_NAME
on host HOST_NAME
without password:
USER_NAME HOST_NAME= NOPASSWD: /usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu
A detailed sudoers
example is available at /usr/share/doc/sudo/examples/sudoers
. Otherwise, see the sudoers(5) for detailed information.
Sudoers default file permissions
The owner and group for the sudoers
file must both be 0. The file permissions must be set to 0440. These permissions are set by default, but if you accidentally change them, they should be changed back immediately or sudo will fail.
# chown -c root:root /etc/sudoers # chmod -c 0440 /etc/sudoers
Tips and tricks
Disable password prompt timeout
A common annoyance is a long-running process that runs on a background terminal somewhere that runs with normal permissions and elevates only when needed. This leads to a sudo password prompt which goes unnoticed and times out, at which point the process dies and the work done is lost or, at best, cached. Common advice is to enable passwordless sudo, or extend the timeout of sudo remembering a password. Both of these have negative security implications. The prompt timeout can also be disabled and since that does not serve any reasonable security purpose it should be the solution here:
Defaults passwd_timeout=0
Add terminal bell to the password prompt
To draw attention to a sudo prompt in a background terminal, users can simply make it echo a bell character:
Defaults passprompt="^G[sudo] password for %p: "
Note the ^G
is a literal bell character. E.g. in vim, insert using the sequence Ctrl+v
Ctrl+g
. If Ctrl+v
is mapped, e.g. for pasting, one can usually use Ctrl+q
instead. In nano, Alt+v
Ctrl+g
.
Another option is to set the SUDO_PROMPT
environment variable. For example, add the following to your shell configuration file:
export SUDO_PROMPT=$'\a[sudo] please enter a password: '
Passing aliases
Aliases in Zsh and Bash are normally only expanded for the first word in a command. This means that your aliases will not normally get expanded when running the sudo
command. One way to make the next word expand is to make an alias for sudo ending with a space. Add the following to your shell's configuration file:
alias sudo='sudo '
zshmisc(1) § ALIASING describes how this works:
- If the replacement text ends with a space, the next word in the shell input is always eligible for purposes of alias expansions.
As well as bash(1) § ALIASES:
- If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.
Disable per-terminal sudo
If you are annoyed by sudo's defaults that require you to enter your password every time you open a new terminal, set timestamp_type
to global
:
Defaults timestamp_type=global
Reduce the number of times you have to type a password
If you are annoyed that you have to re-enter your password every 5 minutes (default), you can change this by setting a longer value for timestamp_timeout
(in minutes):
Defaults timestamp_timeout=10
If you are using a lot of sudo commands on a row, it is more logical to refresh the timeout every time you use sudo than
to increase timestamp_timeout
. Refreshing the timeout can be done with sudo -v
(whereas sudo -K
revokes immediately).
You might want to automate this by adding the following to your shell initialization files:
alias sudo='sudo -v; sudo '
It is also possible to use a bash function; for more details see stackexchange.
Environment variables
If you have a lot of environment variables, or you export your proxy settings via export http_proxy="..."
, when using sudo these variables do not get passed to the root account unless you run sudo with the -E
/--preserve-env
option.
$ sudo -E pacman -Syu
The recommended way of preserving environment variables is to append them to env_keep
:
/etc/sudoers
Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"
Root password
Users can configure sudo to ask for the root password instead of the user password by adding targetpw
(target user, defaults to root) or rootpw
to the Defaults line in /etc/sudoers
:
Defaults targetpw
To prevent exposing your root password to users, you can restrict this to a specific group:
Defaults:%wheel targetpw %wheel ALL=(ALL) ALL
Disable root login
Users may wish to disable the root login. Without root, attackers must first guess a user name configured as a sudoer as well as the user password. See for example OpenSSH#Deny.
- Be careful, you may lock yourself out by disabling root login. Sudo is not automatically installed and its default configuration allows neither passwordless root access nor root access with your own password. Ensure a user is properly configured as a sudoer before disabling the root account!
- If you have changed your sudoers file to use rootpw as default, then do not disable root login with any of the following commands!
- If you are already locked out, see Password recovery for help.
The account can be locked via passwd
:
# passwd -l root
A similar command unlocks root.
$ sudo passwd -u root
Alternatively, edit /etc/shadow
and replace the root's encrypted password with !*
:
root:!*:12345::::::
To enable root login again:
$ sudo passwd root
sudo -i
.kdesu
kdesu may be used under KDE to launch GUI applications with root privileges. It is possible that by default kdesu will try to use su even if the root account is disabled. Fortunately one can tell kdesu to use sudo instead of su. Create/edit the file ~/.config/kdesurc
:
[super-user-command] super-user-command=sudo
or use the following command:
$ kwriteconfig5 --file kdesurc --group super-user-command --key super-user-command sudo
Harden with sudo example
Let us say you create 3 users: admin, devel, and archie. The user "admin" is used for journalctl, systemctl, mount, kill, and iptables; "devel" is used for installing packages, and editing configuration files; and "archie" is the user you log in with. To let "archie" reboot, shutdown, and use netctl we would do the following:
Edit /etc/pam.d/su
and /etc/pam.d/su-l
. Require user be in the wheel group, but do not put anyone in it.
#%PAM-1.0 auth sufficient pam_rootok.so # Uncomment the following line to implicitly trust users in the "wheel" group. #auth sufficient pam_wheel.so trust use_uid # Uncomment the following line to require a user to be in the "wheel" group. auth required pam_wheel.so use_uid auth required pam_unix.so account required pam_unix.so session required pam_unix.so
Limit SSH login to the 'ssh' group. Only "archie" will be part of this group.
# groupadd -r ssh # gpasswd -a archie ssh # echo 'AllowGroups ssh' >> /etc/ssh/sshd_config
Restart sshd.service
.
Add users to other groups.
# for g in power network ;do ;gpasswd -a archie $g ;done # for g in network power storage ;do ;gpasswd -a admin $g ;done
Set permissions on configs so devel can edit them.
# chown -R devel:root /etc/{http,openvpn,cups,zsh,vim,screenrc}
Cmnd_Alias POWER = /usr/bin/shutdown -h now, /usr/bin/halt, /usr/bin/poweroff, /usr/bin/reboot Cmnd_Alias STORAGE = /usr/bin/mount -o nosuid\,nodev\,noexec, /usr/bin/umount Cmnd_Alias SYSTEMD = /usr/bin/journalctl, /usr/bin/systemctl Cmnd_Alias KILL = /usr/bin/kill, /usr/bin/killall Cmnd_Alias PKGMAN = /usr/bin/pacman Cmnd_Alias NETWORK = /usr/bin/netctl Cmnd_Alias FIREWALL = /usr/bin/iptables, /usr/bin/ip6tables Cmnd_Alias SHELL = /usr/bin/zsh, /usr/bin/bash %power ALL = (root) NOPASSWD: POWER %network ALL = (root) NETWORK %storage ALL = (root) STORAGE root ALL = (ALL) ALL admin ALL = (root) SYSTEMD, KILL, FIREWALL devel ALL = (root) PKGMAN archie ALL = (devel) SHELL, (admin) SHELL
With this setup, you will almost never need to login as the root user.
"archie" can connect to their home WiFi.
$ sudo netctl start home $ sudo poweroff
"archie" can not use netctl as any other user.
$ sudo -u admin -- netctl start home
When "archie" needs to use journalctl or kill run away process they can switch to that user.
$ sudo -i -u devel $ sudo -i -u admin
But "archie" cannot switch to the root user.
$ sudo -i -u root
If "archie" want to start a gnu-screen session as admin they can do it like this:
$ sudo -i -u admin [admin]$ chown admin:tty `echo $TTY` [admin]$ screen
Configure sudo using drop-in files in /etc/sudoers.d
sudo parses files contained in the directory /etc/sudoers.d/
. This means that instead of editing /etc/sudoers
, you can change settings in standalone files and drop them in that directory. This has two advantages:
- There is no need to edit a
sudoers.pacnew
file; - If there is a problem with a new entry, you can remove the offending file instead of editing
/etc/sudoers
(but see the warning below).
The format for entries in these drop-in files is the same as for /etc/sudoers
itself. To edit them directly, use visudo -f /etc/sudoers.d/somefile
. See sudoers(5) § Including other files from within sudoers for details.
The files in /etc/sudoers.d/
directory are parsed in lexicographical order, file names containing .
or ~
are skipped. To avoid sorting problems, the file names should begin with two digits, e.g. 01_foo
.
/etc/sudoers.d/
are just as fragile as /etc/sudoers
itself: any improperly formatted file will prevent sudo
from working. Hence, for the same reason it is strongly advised to use visudo
Editing files
sudo
provides the sudoedit
command (equivalent to sudo -e
). This is useful for editing files which can be edited by root only while still running the editor as a normal user, and using that user’s configuration.
To edit a file, set SUDO_EDITOR
to the name of the editor and pass the file name to sudoedit
. For example:
$ SUDO_EDITOR=vim sudoedit /etc/file
See #Using visudo and sudo(8) § e for ways to set the editor, but beware of possible security issues.
If multiple names are passed to sudo
, all files are opened in the editor in a single invocation. A feature useful for merging files:
$ SUDO_EDITOR=vimdiff sudoedit /etc/file /etc/file.pacnew
Enable insults
Users can enable the insults easter egg in sudo by adding the following line in the sudoers
file with visudo
.
/etc/sudoers
Defaults insults
Upon entering an incorrect password this will replace Sorry, try again.
message with humorous insults.
Enable password input feedback
By default, there is no visual feedback when you input a password. That is done on purpose for extra security. However, if you wish to have visual input, you can enable it by adding this line:
/etc/sudoers
Defaults pwfeedback
Colored password prompt
To customize the password prompt with colors and/or bold fonts, set the SUDO_PROMPT
environment variable in your shell initialization file and use tput(1).
For example, to set the password prompt to display Password:
in bold red, use this:
export SUDO_PROMPT="$(tput setaf 1 bold)Password:$(tput sgr0) "
Or use different colors with the default message like so:
export SUDO_PROMPT="$(tput setab 1 setaf 7 bold)[sudo]$(tput sgr0) $(tput setaf 6)password for$(tput sgr0) $(tput setaf 5)%p$(tput sgr0): "
|
|
Using U2F
U2F is great to use with sudo, as it can effectively eliminate the risk of shoulder surfing in public areas while still giving you conscious control to approve the prompt with a simple physical touch.
See Universal 2nd Factor#Passwordless sudo.
Troubleshooting
SSH problem without TTY
SSH does not allocate a tty by default when running a remote command. Without an allocated tty, sudo cannot prevent the password from being displayed. You can use ssh's -t
option to force it to allocate a tty.
The Defaults
option requiretty
only allows the user to run sudo if they have a tty.
# Disable "ssh hostname sudo <cmd>", because it will show the password in clear text. You have to run "ssh -t hostname sudo <cmd>". # #Defaults requiretty
Permissive umask
Sudo will union the user's umask value with its own umask (which defaults to 0022). This prevents sudo from creating files with more open permissions than the user's umask allows. While this is a sane default if no custom umask is in use, this can lead to situations where a utility run by sudo may create files with different permissions than if run by root directly. If errors arise from this, sudo provides a means to fix the umask, even if the desired umask is more permissive than the umask that the user has specified. Adding this (using visudo
) will override sudo's default behavior:
Defaults umask = 0022 Defaults umask_override
This sets sudo's umask to root's default umask (0022) and overrides the default behavior, always using the indicated umask regardless of what umask the user as set.