- Linux debian права администратора
- Sudo не включён по умолчанию в Debian
- Почему sudo
- Обзор настроек
- Проблемы и решения
- Извините, пользователь jdoe не может выполнять .
- sudoers только для чтения
- CVE-2005-4158
- Опция PASSWD не работает
- Неправильное поведение HOME (и настроек профиля)
- См. также
- Linux debian права администратора
- Notes for new Debian users
- Why not sudo?
- Why sudo?
- Users and sudo
- Verifying sudo membership
- Add existing user from commandline
- Creating users with sudo
- Creating new user while installing OS
- Creating new user from commandline
- Configuration overview
- Problems and tips
- Sorry, user jdoe is not allowed to execute .
- The include directive
- sudoers is read-only
- Require root password
- No password prompt for sudo user
- Customize credentials cache timeout
- See also
Linux debian права администратора
Sudo — программа, дающая возможность системным администраторам позволять пользователям выполнять команды как root (или другой пользователь). Основная философия — позволить людям выполнить свою задачу, используя как можно меньше привилегий. Также sudo — эффективный способ для записи деятельности root: кто использует sudo,какую команду и когда.
Sudo не включён по умолчанию в Debian
Грубо говоря, sudo установлен и включён (если во время установки были выбраны компоненты рабочего стола). Но в Debian права не предоставляются по умолчанию (в отличие от некоторых других дистрибутивов).
- Пароль учётной записи root выбирается при установке системы.
- Gnome запрашивает пароль (для учетной записи администратора) при запуске программ, которые настраивают систему.
- Для выполнения команды от root, откройте Root Terminal (Приложения > Стандартные > Root Terminal), или запустите su в любом терминале.
(Примечание для DebianSqueeze: введён аналогичный инструмент PolicyKit, ориентированные на потребности настольных компьютеров и ноутбуков).
Почему sudo
- Нет необходимости в пароле root (sudo запрашивает пароль текущего пользователя).
- По умолчанию команды выполняются от имени обычного пользователя (не привилегированного), что позволяет избежать ошибок. От имени root выполняются только команды с префиксом sudo.
- Проверка/запись: когда выполняется sudo, записывается имя пользователя и исполняемая команда.
По этим причинам, переключение на root с помощью «sudo -i» (или sudo su) считается устаревшим, поскольку отменяет вышеперечисленные особенности.
Обзор настроек
Небольшой пример для того чтобы разрешить определённым пользователям запускать некоторые программы (для получения дополнительной информации, см. документацию).
# /etc/sudoers # # This file MUST be edited with the 'visudo' command as root. # # See the man page for details on how to write a sudoers file. # Defaults env_reset # Host alias specification User_Alias MYADMINS = jdoe # User alias specification # Cmnd alias specification Cmnd_Alias SHUTDOWN = /sbin/reboot, /sbin/poweroff Cmnd_Alias PKGMGMT = /usr/bin/dpkg, /usr/bin/apt-get, /usr/bin/aptitude # User privilege specification # Users listed above (MYADMINS) can run package managers and reboot the system. MYADMINS ALL = PKGMGMT, SHUTDOWN # Users in the group wheel can execute any command impersonating any user. #%wheel ALL= ALL #Default rule for root. root ALL=(ALL) ALL
Проблемы и решения
Извините, пользователь jdoe не может выполнять .
$sudo test We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things: #1) Respect the privacy of others. #2) Think before you type. #3) With great power comes great responsibility. [sudo] password for jdoe: Sorry, user jdoe is not allowed to execute '/usr/bin/test' as root on localhost.
Это сообщение обычно означает, что пользователю не разрешено выполнять этого действие.
sudoers только для чтения
Файл /etc/sudoers только для чтения, даже для root!
Нужно использовать команду visudo для редактирования /etc/sudoers.
CVE-2005-4158
- sudo (1.6.8p7-1.3) stable-security; urgency=high
- Non-maintainer upload by the Security Team
- Reverse the environment semantic by forcing users to maintain a whitelist [env.c, Bug 342948, CVE-2005-4158]
- E138: Can’t write viminfo file $HOME/.viminfo!
- dircolors: no SHELL environment variable, and no shell type option given
- squidview: can’t get your home directory, exiting
If you had more complex setups where you meant to pass through environment variables, your work around may be more complex or no longer possible.
Опция PASSWD не работает
sudo has a flag called exempt_group which contains a list of groups for which always NOPASSWD is true and setting PASSWD has no effect. On Debian Systems this list consists of the group sudo.
Неправильное поведение HOME (и настроек профиля)
If you are having problems when you sudo to your shell and your HOME (and profile settings) doesn’t work as expected because your new HOME is root’s homedir you must know that sudo since upstream version 1.7.4 (Debian Squeeze/Sid after Sep/2010) resets all environmental variables in it’s new default configuration, to restore the old behavior of reading the users HOME dir you may preserve the HOME environment variable by adding this to your /etc/sudoers configuration file:
Для получения дополнительной информации см. список изменений для версии 1.7.4
См. также
Linux debian права администратора
Sudo (sometimes considered as short for Super-user do) is a program designed to let system administrators allow some users to execute some commands as root (or another user). The basic philosophy is to give as few privileges as possible but still allow people to get their work done. Sudo is also an effective way to log who ran which command and when.
Notes for new Debian users
Some new Debian users, usually coming from Ubuntu, are shocked by problems like «sudo not working in Debian». However, this situation only happens if you have set a root password during your Debian installation.
If you like sudo and you want to install it (even if you skipped it during your Debian installation), you can, but in the way without sudo, so, becoming root with the su command, installing it, and adding yourself in the sudo group and doing a full logout/login.
$ su - Password: (enter here the password of the root user that you specified during your Debian installation, and press Enter) # apt install sudo # adduser jhon-smith sudo
(Obviously just replace «jhon-smith» with your personal username)
Then please do a full logout and login again.
Why not sudo?
Note that, historically, all Unix-like systems worked perfectly even before «sudo» was invented. Moreover, having a system without sudo could still give security benefits, since the sudo package could be affected by security bugs, as any additional part of the system.
Lot of Debian users do not install sudo. Instead, they open a terminal as root (for example with su - from a normal user). So you do not have to put «sudo» in front of any command.
Why sudo?
- Nobody needs to know the root password (sudo prompts for the current user’s password). Extra privileges can be granted to individual users temporarily, and then taken away without the need for a password change.
- It’s easy to run only the commands that require special privileges via sudo; the rest of the time, you work as an unprivileged user, which reduces the damage that mistakes can cause.
- Auditing/logging: when a sudo command is executed, the original username and the command are logged.
For the reasons above, switching to root using sudo -i (or sudo su) is usually deprecated because it cancels most of the above features.
Users and sudo
Debian’s default configuration allows users in the sudo group to run any command via sudo.
Verifying sudo membership
uid=1001(foo) gid=1001(foo) groups=1001(foo),27(sudo)
Add existing user from commandline
# adduser foo # adduser foo sudo
After being added to a new group the user must log out and then log back in again for the new group to take effect. Groups are only assigned to users at login time. A most common source of confusion is that people add themselves to a new group but then do not log out and back in again and then have problems because the group is not assigned; be sure to verify group membership.
Creating users with sudo
You can also create new users with sudo membership:
Creating new user while installing OS
As of DebianSqueeze, if you give root an empty password during installation, sudo will be installed and the first user will be able to use it to gain root access (currently, the user will be added to the sudo group). The system will also configure gksu and aptitude to use sudo. You should still verify group membership after logging in as the installed user.
Creating new user from commandline
(or first get root as in previous section). You should then login as the new user and verify group membership.
Configuration overview
Now, if you want to allow certain users to execute certain programs, here’s a quick example (for more information, read the fine manual), which you can put in a file in /etc/sudoers.d, probably using visudo -f /etc/sudoers.d/myfile.
User_Alias MYADMINS = jdoe Cmnd_Alias SHUTDOWN = /sbin/reboot, /sbin/poweroff Cmnd_Alias PKGMGMT = /usr/bin/dpkg, /usr/bin/apt-get, /usr/bin/aptitude # Users listed above (MYADMINS) can run package managers and reboot the system. MYADMINS ALL = PKGMGMT, SHUTDOWN
Problems and tips
Sorry, user jdoe is not allowed to execute .
$ sudo test We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things: #1) Respect the privacy of others. #2) Think before you type. #3) With great power comes great responsibility. [sudo] password for jdoe: Sorry, user jdoe is not allowed to execute '/usr/bin/test' as root on localhost.
This message means what it says: the user you’re running as isn’t allowed to execute the given command on the given machine. One confusing possible reason for this is that the administrator has just added user jdoe to a privileged group — but you’re still using the old login, which doesn’t have that new group information, and therefore has no new sudo-ing rights. People in this situation are usually advised to log out completely and back in again, though you can sometimes get away with just performing a «re-login on the spot» with su - $USER or changing group with newgrp sudo.
The include directive
This makes it possible for other packages to provide snippets in /etc/sudoers.d/ which modify the configuration of sudo. It may look as if it needs to be edited to take out the leading numbersign (a.k.a. "hash" or "pound"), but no, the '#' is part of the directive!
It is recommended that you make local changes in a snippet as well.
sudoers is read-only
Yes, the file /etc/sudoers is intentionally set read-only, even for root!
The explanation is that it was set up this way to motivate admins to only ever edit it via the command visudo, which provides additional checking before leaving the new file in place. You might think that the fix for a mangled /etc/sudoers, the fix may be as simple as su -c visudo, but sudo is often used in a place where simply su'ing to root is not possible since you simply don't know the root password.
Beware, most text editors will let you edit the file without complaining about the read-only bit, so you might not automatically get this additional protection.
Require root password
If you want to require the root password for use of sudo, rather than the user password, add the line:
No password prompt for sudo user
If you want sudo group members to execute commands without password, add the line:
Customize credentials cache timeout
As default, after asking a password, your credentials are cached by sudo and last for 15 minutes. You can change this behavior using the command visudo and customizing the timeout for a specific user:
Defaults:foobar timestamp_timeout=30
See also
- Manpages: sudoers(5), sudo(8), visudo(8), sudoedit(8), sudoreplay(8)
- Doas - A lighter and more minimalistic tool for the same purpose, with simpler configuration.