Install the package.
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
- Интерактивная система просмотра системных руководств (man-ов)
- INTRODUCTION
- SSH problem without TTY
- View current settings
- Sudoers default file permissions
- Index
- NAME
- Giving yourself root rights
- Просмотр текущих настроек
- Права доступа к файлам sudoers по умолчанию
- Tips and tricks
- Disable password prompt timeout
- Add terminal bell to the password prompt
- Disable per-terminal sudo
- Reduce the number of times you have to type a password
- Disable root login
- Harden with sudo example
- Configure sudo using drop-in files in /etc/sudoers.d
- Enable password input feedback
- Colored password prompt
- Проблемы с TTY через SSH
- SEE ALSO
- Using Sudo
- ALLOWING OTHER USERS TO RUN SUDO
- GOING BACK TO A TRADITIONAL ROOT ACCOUNT
- Additional steps with Debian
- BENEFITS OF USING SUDO
- What is sudo / root?
- Switching to the root user
- DOWNSIDES OF USING SUDO
- Советы и рекомендации
- Отключение таймаута запроса пароля
- Сигнал при запросе пароля
- Один тайм-аут на все сеансы терминала
- Время действия введённого пароля
- Отключение учетной записи root
- Еще один пример настройки
- Настройка sudo с помощью вкладываемых в /etc/sudoers.d файлов
Интерактивная система просмотра системных руководств (man-ов)
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.
INTRODUCTION
This means that in the terminal you can use sudo for commands that
require root privileges. All programs in the menu will use a graphical
sudo to prompt for a password. When sudo asks for a password, it needs
your password,
this means that a root password is not needed.
To run a command which requires root privileges in a terminal, simply
prepend
sudo
in front of it. To get an interactive root shell, use
sudo -i.
Like title says, is there a difference between these two commands :
sudo su - root
sudo -u root -H /bin/bash
I’m using GNU/Linux, if that makes a difference.
asked Mar 21, 2012 at 15:30
answered Mar 21, 2012 at 15:41
su - # causes the user to run a login shell aka bash --login # the same as if the user had logged in as the root from the login prompt
and sudo su -
is the same as sudo su - root
specifying root is redundant.
But in this case, bash is not run as a login shell.
answered Mar 21, 2012 at 22:20
4 gold badges30 silver badges38 bronze badges
answered Mar 21, 2012 at 20:40
17 silver badges11 bronze badges
answered Mar 22, 2012 at 0:20
5 gold badges56 silver badges58 bronze badges
SSH problem without TTY
This article or section is a candidate for merging with #Configuration.
Notes: please use the second argument of the template to provide more detailed indications. (Discuss in Talk:Sudo)
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.
# 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
This article or section is a candidate for merging with #Configuration.
Notes: please use the second argument of the template to provide more detailed indications. (Discuss in Talk:Sudo)
Defaults umask = 0022 Defaults umask_override
Состояние перевода: На этой странице представлен перевод статьи Sudo. Дата последней синхронизации: 26 июня 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.
Sudo — это альтернатива su для выполнения команд с правами суперпользователя (root). В отличие от su, который запускает оболочку с правами root и даёт всем дальнейшим командам root-права, sudo предоставляет временное повышение привилегий для одной команды. Предоставляя привилегии root только при необходимости, sudo снижает вероятность того, что опечатка или ошибка в выполняемой команде произведут в системе разрушительные действия.
Sudo может также использоваться для выполнения команд от имени других пользователей; кроме того, sudo логирует все команды и неудачные попытки доступа для аудита безопасности.
So, e.g. sudo vi /etc/hosts
would allow you to edit the hosts file as if you were running as root. You don’t even need the root password, just your own login password.
And of course, sudo su
would allow you to simply become root. The result is the same as if you had logged in as root or executed the su
command, except that you don’t need to know the root password but you do need to be in the sudoers file.
The sudoers file determines who can use the sudo command and what they can do with it.
At one company I worked for, with a ginormous server farm, only a very, very small number of people knew the root passwords. Instead, there was a database of who was allowed to work on which servers. An automated process would add you to the sudoers files of those servers you were authorized to access, and remove you when your authorization expired.
Under SELinux (Security Enhanced Linux), there’s effectively an access control list that determines which program can do what, and even root can’t get past those restrictions.
Under Apple’s System Integrity Protection (SIP) (aka «rootless») system, certain files and directories are locked down so that only applications on the appropriate whitelist can access them.
This article or section needs expansion.
Reason: Create an intro discussing Defaults
, perhaps with a table that lists common settings (Discuss in Talk:Sudo)
sudoers(5) § SUDOERS OPTIONS lists all the options that can be used with the Defaults
command in the /etc/sudoers
file.
View current settings
The configuration file for sudo is /etc/sudoers
. It should always be edited with the 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. - 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 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.
# Set default EDITOR to restricted version of nano, and do not allow visudo to use EDITOR/VISUAL. Defaults editor=/usr/bin/rnano, !env_editor
USER_NAME ALL=(ALL:ALL) ALL
USER_NAME HOST_NAME=(ALL:ALL) ALL
To allow members of group wheel sudo access:
%wheel ALL=(ALL:ALL) ALL
Defaults:USER_NAME !authenticate
USER_NAME HOST_NAME=/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
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
Index
- NAME
- SYNOPSIS
- INTRODUCTION
- ALLOWING OTHER USERS TO RUN SUDO
- BENEFITS OF USING SUDO
- DOWNSIDES OF USING SUDO
- GOING BACK TO A TRADITIONAL ROOT ACCOUNT
- SEE ALSO
NAME
sudo_root - How to run administrative commands
Giving yourself root rights
If you get a message that the sudo group does not exist, add the sudo group (if necessary). To do so, first open visudo:
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
sudoers(5) § SUDOERS OPTIONS содержит список опций, которые можно использовать с командой Defaults
в файле /etc/sudoers
.
Здесь доступен список опций (извлечён из исходного кода версии 1.8.7) в формате, удобном для копирования и вставки в файл sudoers
.
Смотрите для более подробной информации, например о настройке таймаутов.
Просмотр текущих настроек
Выполните sudo -ll
для вывода текущей конфигурации sudo.
Чтобы посмотреть настройки, действующие для конкретного пользователя, выполните sudo -lU пользователь
.
Файл настроек /etc/sudoers
всегда следует редактировать с помощью команды . visudo блокирует файл sudoers
, сохраняет изменения во временный файл и проверяет, что файл синтаксически корректен, перед тем как скопировать его в /etc/sudoers
.
- Крайне важно, чтобы файл
sudoers
был без синтаксических ошибок! Любая ошибка делает sudo неработоспособным. Всегда редактируйте его только с помощью visudo для предотвращения ошибок. - Из : Обратите внимание, что это дыра в безопасности, поскольку позволяет пользователю запускать любую программу, какую он захочет, просто прописав её в VISUAL или EDITOR.
visudo использует vi в качестве текстового редактора по умолчанию. Пакет скомпилирован с опцией --with-env-editor
по умолчанию и использует переменные VISUAL
и EDITOR
. EDITOR
не используется, если задана переменная VISUAL
.
Чтобы выбрать nano в качестве редактора для visudo в текущем сеансе, задайте и экспортируйте переменную EDITOR
перед запуском visudo. Чтобы выбрать другой редактор однократно, можно просто прописать эту переменную перед командой visudo:
# EDITOR=nano visudo
В качестве альтернативы можно отредактировать копию файла /etc/sudoers
и вручную запустить проверку синтаксиса с помощью команды visudo -c /копия/файла/sudoers
. Это может пригодиться, если вас не устраивает, что visudo блокирует файл.
Для изменения редактора на постоянной основе для текущего пользователя, смотрите раздел Переменные окружения#На уровне пользователя. Для того, чтобы установить выбранный редактор на постоянной основе для всей системы, но только для visudo, добавьте следующее в /etc/sudoers
(предположим, что вы предпочитаете nano в качестве редактора):
# Сброс окружения Defaults env_reset # Установка ограниченного варианта nano в качестве редактора по умолчанию и запрет visudo использовать EDITOR/VISUAL. Defaults editor=/usr/bin/rnano, !env_editor
Настройка sudo осуществляется добавлением записей в файл /etc/sudoers
. Чтобы дать пользователю привилегии суперпользователя, когда он вводит sudo
перед командой, добавьте следующую строку:
имя_пользователя ALL=(ALL:ALL) ALL
Разрешить пользователю выполнять все команды от любого пользователя, но только на машине с определенным названием хоста:
имя_пользователя название_хоста=(ALL:ALL) ALL
Предоставить членам группы wheel доступ к sudo:
%wheel ALL=(ALL:ALL) ALL
Совет: Для добавления новых администраторов рекомендуется включить доступ к sudo для группы wheel
и добавлять новых пользователей в неё, поскольку по умолчанию Polkit рассматривает членов группы wheel
как администраторов. Если пользователь не является членом группы wheel
, программы, использующие Polkit, могут запросить аутентификацию с использованием пароля root вместо пароля пользователя.
Чтобы не спрашивать пароль у пользователя:
Важно: Это позволит любому процессу, запущенному под вашим именем пользователя, использовать sudo, не спрашивая разрешения.
Defaults:имя_пользователя !authenticate
Разрешить выполнять только конкретные команды и только пользователю на определенном хосте:
имя_пользователя название_хоста=/usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu
Примечание: Наиболее общие опции должны идти в начале файла, а наиболее частные — наоборот, в конце файла, так как более нижние строки переопределяют более верхние. В частности, добавляемая строка должна быть после строки %wheel
, если ваш пользователь находится в этой группе.
Разрешить выполнять конкретно определённые команды только для пользователя на определенном хосте и без пароля:
имя_пользователя название_хоста= NOPASSWD: /usr/bin/halt,/usr/bin/poweroff,/usr/bin/reboot,/usr/bin/pacman -Syu
Права доступа к файлам sudoers по умолчанию
Файл sudoers
должен иметь владельца root и группу root (0). Права доступа всегда должны быть установлены как r--r-----
(0440). Эти права установлены по умолчанию, однако если вы случайно измените их, они должны быть немедленно изменены обратно, иначе sudo не будет работать.
# 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
Defaults passprompt="[sudo] password for %p: "
Note the 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
.
This article or section needs expansion.
Reason: 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? (Discuss in Talk:Sudo)
export SUDO_PROMPT=$'\a[sudo] please enter a password: '
alias sudo='sudo '
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 :
- 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
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, 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).
alias sudo='sudo -v; sudo '
$ 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"
Defaults targetpw
Defaults:%wheel targetpw %wheel ALL=(ALL) ALL
Disable root login
- 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
Tip: To get to an interactive root prompt, even after disabling the root account, use sudo -i
.
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
$ kwriteconfig5 --file kdesurc --group super-user-command --key super-user-command sudo
Harden with sudo example
#%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
# 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
«archie» can connect to their home WiFi.
$ sudo netctl start home $ sudo poweroff
$ sudo -u admin -- netctl start home
$ sudo -i -u devel $ sudo -i -u admin
$ sudo -i -u root
$ 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
.
Note: The order of entries in the drop-in files is important: make sure that the statements do not override themselves.
Warning: The files in /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
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 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
/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 .
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): "
Проблемы с TTY через SSH
По умолчанию SSH не выделяет tty при выполнении удалённой команды. Без tty sudo не может отключить отображение пароля при его вводе. Вы можете воспользоваться ssh опцией -t
, чтобы заставить его выделять tty.
Defaults
опция requiretty
всего лишь позволяет запускать sudo пользователям, если они имеют 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
Sudo накладывает на значение umask пользователя свою собственную (которая по умолчанию установлена в 0022). Это предотвращает sudo от создания файлов с более либеральными правами доступа, чем это позволяет umask пользователя. Несмотря на то, что это разумное значение по умолчанию, если не используется измененная umask, это может привести к ситуации, когда программа, запущенная через sudo может создавать файлы с правами доступа отличными от тех, которые создаются при запуске программы непосредственно суперпользователем. Для исправления таких ошибок sudo предоставляет возможность исправить umask, даже если желаемая umask более либеральна, чем установлено в umask пользователя. Добавив такие строки (используйте visudo
) вы измените поведение sudo по умолчанию:
Defaults umask = 0022 Defaults umask_override
Это установит sudo umask в umask суперпользователя по умолчанию (0022) и переопределит поведение по умолчанию, всегда используя указанную umask и независимо от umask пользователя.
SEE ALSO
sudo
https://wiki.ubuntu.com/RootSudo
Using Sudo
You use ‘sudo’ by placing it in front of the command you want to execute, for example:
sudo nano /var/log/example
Чтобы начать использовать sudo
как непривилегированный пользователь, его нужно настроить должным образом. Для этого прочтите раздел о настройке.
Для использования sudo просто добавьте sudo
и пробел перед нужной командой:
$ sudo команда
Например, для использования pacman:
$ sudo pacman -Syu
Смотрите для более подробной информации.
ALLOWING OTHER USERS TO RUN SUDO
- *
- In a shell, do
- sudo adduser
username
admin
- sudo adduser
- *
- Use the graphical «Users & Groups» program in the «System settings»
menu to add the new user to the
admingroup.
GOING BACK TO A TRADITIONAL ROOT ACCOUNT
This is not recommended!
To enable the root account (i.e. set a password) use:
- sudo passwd root
Afterwards, edit the sudo configuration with
sudo visudo
and comment out the line
- %admin ALL=(ALL) ALL
Additional steps with Debian
Next, you give yourself root rights before you are actually able to use the sudo command, see the steps above.
Should you have any questions left regarding this article, do not hesitate to contact our support department. You can reach them via the ‘ContactUs’ button at the bottom of this page.
BENEFITS OF USING SUDO
- *
- Users do not have to remember an extra password, which they are likely to forget.
- *
- The installer is able to ask fewer questions.
- *
- It avoids the «I can do anything» interactive login by default — you
will be prompted for a password before major changes can happen, which
should make you think about the consequences of what you are doing. - *
- Sudo adds a log entry of the command(s) run (in /var/log/auth.log).
- *
- Every attacker trying to brute-force their way into your box will
know it has an account named root and will try that first. What they
do not know is what the usernames of your other users are. - *
- Allows easy transfer for admin rights, in a short term or long term
period, by adding and removing users from the admin group, while not
compromising the root account. - *
- sudo can be set up with a much more fine-grained security policy.
- *
- On systems with more than one administrator using sudo avoids sharing
a password amongst them.
What is sudo / root?
Switching to the root user
- Switching to the root user and (automatically) invoking a new login shell. This resets most environment variables and is the cleanest and most secure method for switching to the root user. It is done using the command:
- Switching to the root user without invoking a new login shell. You could say that using this method, you’re faking being a root user.
CentOS 7 (or earlier) / Debian 9 (or earlier):
With Ubuntu, your account has root privileges by default and you use the command:
DOWNSIDES OF USING SUDO
Although for desktops the benefits of using sudo are great, there are
possible issues which need to be noted:
- *
- Redirecting the output of commands run with sudo can be confusing at
first. For instance consider- sudo ls > /root/somefile
- will not work since it is the shell that tries to write to that file. You can use
- ls | sudo tee /root/somefile
- to get the behaviour you want.
- *
- In a lot of office environments the ONLY local user on a system is
root. All other users are imported using NSS techniques such as
nss-ldap. To setup a workstation, or fix it, in the case of a network
failure where nss-ldap is broken, root is required. This tends to
leave the system unusable. An extra local user, or an enabled root
password is needed here.
Советы и рекомендации
Отключение таймаута запроса пароля
Часто раздражает такая вещь: вы запускаете какой-то долгий процесс, который работает с обычными правами и повышает их только при необходимости, и когда sudo запросит пароль, вы можете случайно не заметить это и не ввести его вовремя, из-за чего случается таймаут, процесс умирает и проделанная работа теряется или, если повезёт, кэшируется. Обычно советуют отключить запрос пароля для sudo или увеличить время действия ранее введённого пароля, однако оба этих способа имеют негативные последствия для безопасности. Таймаут запроса пароля тоже можно отключить, и поскольку это никак не влияет на безопасность, это и должно быть предпочтительным решением:
Defaults passwd_timeout=0
Сигнал при запросе пароля
Чтобы работающий в фоне терминал привлёк ваше внимание в момент запроса пароля, можно добавить символ BELL в строку запроса пароля:
Defaults passprompt="^G[sudo] password for %p: "
Вместо ^G
должен быть вписан настоящий символ BELL. Например, чтобы ввести его в vim, используйте сочетание Ctrl+v
Ctrl+g
, а в nano используйте Alt+v
Ctrl+g
.
Если у вас установлено много псевдонимов, вы могли заметить, что они не переносятся в сеанс sudo. Однако, это легко исправить. Просто добавьте в ваш ~/.bashrc
или /etc/bash.bashrc
строку:
alias sudo='sudo '
Один тайм-аут на все сеансы терминала
Важно: Это позволит любому процессу воспользоваться вашим открытым сеансом sudo.
По умолчанию сеанс sudo действует только в пределах текущего терминала; при запуске sudo в новом терминале он запросит пароль заново. Если вас это раздражает, укажите для опции timestamp_type
значение global
:
Defaults timestamp_type=global
Время действия введённого пароля
Возможно, вы захотите изменить промежуток времени, в течение которого sudo действует без ввода пароля. Этого легко добиться добавив опцию timestamp_timeout
в /etc/sudoers
(по умолчанию 5 минут):
Defaults timestamp_timeout=10
Если вы запускаете много sudo-команд подряд, возможно, вместо увеличения timestamp_timeout
лучше просто периодически обновлять временную метку. Команда sudo -v
запустит отсчёт таймаута заново. С помощью команды sudo -K
можно удалить временную метку, что приведёт к запросу пароля при следующем запуске sudo.
Обновление временной метки можно автоматизировать с помощью такого псевдонима (добавьте его в .bashrc
):
alias sudo='sudo -v; sudo '
Также можно сделать bash-функцию: подробнее на stackexchange.
$ sudo -E pacman -Syu
Рекомендованный способ сохранения переменных окружения — это прописать их в env_keep
:
/etc/sudoers
Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"
Вы можете сконфигурировать sudo так, чтобы он спрашивал пароль суперпользователя вместо пароля текущего пользователя, добавив targetpw
(целевой пользователь, по умолчанию root) или rootpw
в список опций Defaults в /etc/sudoers
:
Defaults targetpw
Чтобы не понадобилось разглашать пароль root обычным пользователям, можно указать эту опцию только для определённой группы:
Defaults:%wheel targetpw %wheel ALL=(ALL) ALL
Отключение учетной записи root
Вы можете захотеть отключить возможность входа систему пользователя root. Без этого атакующие сначала должны будут угадать имя пользователя, сконфигурированного как sudoer, а также пароль этого пользователя. Смотрите для примера Secure Shell (Русский)#Отключение.
- Будьте осторожны. Вы можете попасть в свою ловушку, если отключите вход систему пользователя root. Sudo по умолчанию не установлен, и его стандартная конфигурация не позволяет ни получить доступ к правам root без пароля, ни дать такой доступ вам по вашему собственному паролю. Убедитесь, что пользователь правильно сконфигурирован как sudoer перед отключением аккаунта суперпользователя!
- Если файл sudoers настроен на использование rootpw по умолчанию, то не отключайте root-вход ни одной из следующих команд!
- Если вы уже попали в ловушку, смотрите статью Сброс пароля root для получения помощи.
Можно заблокировать аккаунт с помощью passwd
:
# passwd -l root
Похожая команда снимает блокировку:
$ sudo passwd -u root
Также вы можете отредактировать /etc/shadow
и заменить зашифрованный пароль root на «!»:
root:!:12345::::::
Тогда, чтобы задать новый пароль и тем самым разблокировать пользователя root:
$ sudo passwd root
Совет: Чтобы попасть в командную оболочку root даже после отключения аккаунта, используйте команду sudo -i
.
kdesu можно использовать в KDE для запуска графических программ с привилегиями суперпользователя. Вероятно, что kdesu по умолчанию будет пытаться использовать su, даже если аккаунт root отключен. К счастью, можно сказать kdesu использовать sudo вместо su. Создайте/отредактируйте файл ~/.config/kdesurc
:
[super-user-command] super-user-command=sudo
или используйте следующую команду:
$ kwriteconfig5 --file kdesurc --group super-user-command --key super-user-command sudo
Еще один пример настройки
Отредактировать /etc/pam.d/su
и /etc/pam.d/su-1
.
Потребовать, чтобы пользователь был в группе wheel, но никого в неё не добавлять.
#%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
Разрешить вход по SSH только для группы ‘ssh’. В эту группу будет входить только «joe».
# groupadd -r ssh # gpasswd -a joe ssh # echo 'AllowGroups ssh' >> /etc/ssh/sshd_config
Перезапустите службу sshd.service
.
Добавить пользователей в другие группы.
# for g in power network ;do ;gpasswd -a joe $g ;done # for g in network power storage ;do ;gpasswd -a admin $g ;done
Установить права на настройки так, чтобы devel мог редактировать их.
# 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 joe ALL = (devel) SHELL, (admin) SHELL
С такими настройками вам практически никогда не понадобится входить как суперпользователь.
«joe» может подсоединиться к своему домашнему WiFi.
$ sudo netctl start home $ sudo poweroff
«joe» не может использовать netctl от имени другого пользователя.
$ sudo -u admin -- netctl start home
Когда «joe» хочет воспользоваться journalctl или убить зависший процесс, он может переключиться на нужного пользователя:
$ sudo -i -u devel $ sudo -i -u admin
Но «joe» не может переключиться на суперпользователя.
$ sudo -i -u root
$ sudo -i -u admin [admin]$ chown admin:tty `echo $TTY` [admin]$ screen
Настройка sudo с помощью вкладываемых в /etc/sudoers.d файлов
sudo обрабатывает файлы, содержащиеся в директории /etc/sudoers.d/
. Это означает, что вместо того, чтобы редактировать /etc/sudoers
, вы можете менять настройки в отдельных файлах и перемещать их в эту директорию. Это даёт два преимущества:
- Вам не понадобится редактировать файл
sudoers.pacnew
; - Если с новой записью будет проблема, вы можете просто удалить соответствующий файл вместо необходимости редактировать
/etc/sudoers
(но смотрите предупреждение ниже).
Формат записей в этих вкладываемых файлах такой же, как и в самом файле /etc/sudoers
. Чтобы редактировать их напрямую, используйте visudo -f /etc/sudoers.d/файл
. Смотрите sudoers(5) § Including other files from within sudoers для дополнительной информации.
Файлы из каталога /etc/sudoers.d/
обрабатываются в лексикографическом порядке; файлы, содержащие .
или ~
в имени, пропускаются. Чтобы избежать путаницы с сортировкой, рекомендуется начинать имена файлов с двух цифр, например 01_foo
.
Примечание: Порядок настроек в файлах имеет значение: убедитесь, что правила не переопределяют сами себя.
Важно: Файлы в /etc/sudoers.d/
так же хрупки, как и сам /etc/sudoers
: любой некорректный файл сделает sudo
неработоспособным. Поэтому по той же причине настоятельно рекомендуется использовать visudo
sudo -e
или sudoedit
позволяет редактировать файл от имени другого пользователя, но при этом запускать текстовый редактор от имени вашего пользователя.
Это полезно для редактирования файлов от имени root без предоставления повышенных привилегий вашему текстовому редактору. Подробнее об этом читайте в .
В качестве редактора можно использовать любую программу, поэтому, например, можно использовать для управления файлами pacnew:
$ SUDO_EDITOR=meld sudo -e /etc/файл{,.pacnew}
Вы можете сконфигурировать sudo так, чтобы при вводе неверного пароля он выводил шутливые оскорбления вместо стандартного сообщения «Sorry, try again». Найдите строку Defaults
в /etc/sudoers
и добавьте insults
в список опции, разделяя их запятыми. Конечный результат может выглядеть так:
/etc/sudoers
Defaults insults
Для проверки, введите sudo -K
, чтобы завершить текущий сеанс и позволить sudo заново запросить пароль.