Sudo linux command line

Linux sudo command

On Unix-like operating systems, the sudo command («switch user, do») allows a user with proper permissions to execute a command as another user. By default, sudo executes commands as root.

This page describes the Linux version of sudo.

Description

sudo allows a permitted user to execute a command as another user, according to specifications in the /etc/sudoers file. The real and effective uid and gid of the issuing user are then set to match those of the target user account as specified in the passwd file.

By default, sudo requires that users authenticate themselves with a password. By default, this is the user’s password, not the root password itself.

Once a user is authenticated, a timestamp is recorded and the user may use sudo without a password for a short time (5 minutes, unless configured differently in sudoers). This timestamp can be renewed if the user issues sudo with the -v flag.

If a user not listed in sudoers tries to run a command using sudo, it is considered an unsuccessful attempt to breach system security and mail is sent to the proper authorities, as defined at configure time or in the sudoers file. The default authority to be notified of unsuccessful sudo attempts is root. Note that the mail isn’t sent if an unauthorized user tries to run sudo with the -l or -v flags; this allows users to determine for themselves whether or not they are allowed to use sudo.

sudo can log both successful and unsuccessful attempts (and errors) to syslog, a unique log file, or both. By default, sudo will log to syslog but this can be changed at configure time or in the sudoers file.

To edit the sudoers file, use the visudo command.

Syntax

Options

-V The -V (version) option causes sudo to print the version number and exit. If the invoking user is already root, the -V option prints out a list of the defaults sudo was compiled with and the machine’s local network addresses.
-l The -l (list) option prints out the commands allowed (and forbidden) the user on the current host.
-L The -L (list defaults) option lists out the parameters set in a Defaults line with a short description for each. This option is useful in conjunction with grep.
-h The -h (help) option causes sudo to print a usage message and exit.
-v If given the -v (validate) option, sudo updates the user’s timestamp, prompting for the user’s password if necessary. This extends the sudo timeout for another 5 minutes (or whatever the timeout is set to in sudoers) but does not run a command.
-k The -k (kill) option to sudo invalidates the user’s timestamp by setting the time on it to the epoch. The next time sudo is run a password will be required. This option does not require a password and was added to allow a user to revoke sudo permissions from a .logout file.
-K The -K (sure kill) option to sudo removes the user’s timestamp entirely. Likewise, this option does not require a password.
-b The -b (background) option tells sudo to run the given command in the background. Note that if you use the -b option you cannot use shell job control to manipulate the process.
-p The -p (prompt) option allows you to override the default password prompt and use a custom one. The following percent (‘%‘) escapes are supported:

%u is expanded to the invoking user’s login name;

%U is expanded to the login name of the user the command will run as (which defaults to root);

%h is expanded to the local hostname without the domain name;

%H is expanded to the local hostname including the domain name (only if the machine’s hostname is fully qualified or the «fqdn» sudoers option is set);

%% (two consecutive % characters) are collapsed into a single % character. -c The -c (class) option causes sudo to run the specified command with resources limited by the specified login class. The class argument can be either a class name as defined in /etc/login.conf, or a single ‘‘ character. Specifying a class of indicates that the command should run restricted by the default login capabilities for the user running the command. If the class argument specifies an existing user class, the command must run as root, or the sudo command must run from a shell that is already root. This option is only available on systems with BSD login classes where sudo is configured with the —with-logincap option. -a The -a (authentication type) option causes sudo to use the specified authentication type when validating the user, as allowed by /etc/login.conf. The system administrator may specify a list of sudo-specific authentication methods by adding an «auth-sudo» entry in /etc/login.conf. This option is only available on systems that support BSD authentication where sudo is configured with the —with-bsdauth option. -u The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a username, use #uid. -s The -s (shell) option runs the shell specified by the SHELL environment variable if it’s set or the shell as specified in the file passwd. -H The -H (HOME) option sets the HOME environment variable to the home directory of the target user (root by default) as specified in passwd. By default, sudo does not modify HOME. -P The -P (preserve group vector) option causes sudo to preserve the user’s group vector unaltered. By default, sudo will initialize the group vector to the list of groups of the target user. The real and effective group IDs, however, are still set to match the target user. -r The -r (role) option causes the new (SELinux) security context to have the role specified by ROLE. -t The -t (type) option causes the new (SELinux) security context to have the type (domain) specified by TYPE. If no type is specified, the default type is derived from the specified role. -S The -S (stdin) option causes sudo to read the password from standard input instead of the terminal device. The flag indicates that sudo should stop processing command line arguments. It is most useful in conjunction with the -s flag.

Return values

Upon successful execution of a program, the return value from sudo will be the return value of the program that was executed.

Otherwise, sudo quits with an exit value of 1 if there is a configuration/permission problem or if sudo cannot execute the given command. In the latter case the error string is printed to stderr. If sudo cannot stat one or more entries in the user’s PATH an error is printed on stderr. (If the directory does not exist or if it’s not a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat to return «permission denied» is if you are running an auto-mounter and one of the directories in your PATH is on a machine that is currently unreachable.

Security notes

sudo tries to be safe when executing commands. Variables that control how dynamic loading and binding is done can subvert the program that sudo runs. To combat this, some system-specific environment variables are removed from the environment that is passed on to the commands that are executed. Other variables that sudo removes from the environment include:

  • IFS
  • ENV
  • BASH_ENV
  • KRB_CONF
  • KRBCONFDIR
  • KRBTKFILE
  • KRB5_CONFIG
  • LOCALDOMAIN
  • RES_OPTIONS
  • HOSTALIASES
  • NLSPATH
  • PATH_LOCALE
  • TERMINFO
  • TERMINFO_DIRS
  • TERMPATH

as they too can pose a threat. If the TERMCAP variable is set and is a pathname, it too is ignored. Additionally, if certain variables contain the / or % characters, they are ignored.

If sudo was compiled with SecurID support, the VAR_ACE, USR_ACE and DLC_ACE variables are cleared as well. The list of environment variables that sudo clears is contained in the output of sudo -V when run as root.

To prevent command spoofing, sudo checks «.» and «» (both denoting current directory) last when searching for a command in the user’s PATH (if one or both are in the PATH). Note, however, that the actual PATH environment variable is not modified and is passed unchanged to the program that sudo executes.

For security reasons, if your OS supports shared libraries and does not disable user-defined library search paths for setuid programs (most do), either use a linker option that disables this behavior or link sudo statically.

sudo checks the ownership of its timestamp directory (/var/run/sudo by default) and ignore the directory’s contents if it’s not owned by root and only writable by root. On systems that allow non-root users to give away files via chown, if the timestamp directory is located in a directory writable by anyone (e.g.: /tmp), it is possible for a user to create the timestamp directory before sudo is run. However, because sudo checks the ownership and mode of the directory and its contents, the only damage that can be done is to «hide» files by putting them in the timestamp dir. This is unlikely to happen since once the timestamp dir is owned by root and inaccessible by any other user the user placing files there would be unable to get them back out. To get around this issue, you can use a directory that is not world-writable for the timestamps (/var/adm/sudo for instance) or create /var/run/sudo with the appropriate owner (root) and permissions (0700) in the system startup files.

sudo will not honor timestamps set far in the future. Timestamps with a date greater than current_time + 2 * TIMEOUT is ignored and sudo will log and complain. This is done to keep a user from creating his/her own timestamp with a bogus date on systems that allow users to give away files.

Please note that sudo only logs the command it explicitly runs. If a user runs a command such as «sudo su» or «sudo sh«, subsequent commands run from that shell are not logged, nor will sudo‘s access control affect them. The same is true for commands that offer shell escapes (including most editors). Because of this, care must be taken when giving users access to commands via sudo to verify that the command does not inadvertently give the user an effective root shell.

Environment variables

PATH Set to a sane value if SECURE_PATH is set
SHELL Used to determine shell to run with -s option
USER Set to the target user (root unless the -u option is specified)
HOME In -s or -H mode (or if sudo was configured with the —enable-shell-sets-home option), set to home directory of the target user.
SUDO_PROMPT Used as the default password prompt
SUDO_COMMAND Set to the command run by sudo
SUDO_USER Set to the login of the user who invoked sudo
SUDO_UID Set to the uid of the user who invoked sudo
SUDO_GID Set to the gid of the user who invoked sudo
SUDO_PS1 If set, PS1 will be set to its value

Examples

Restart the system; run the shutdown command as root.

List the contents of the /home/otheruser/Documents directory as the user hope.

Create a new directory with the mkdir command, as the user hope, with hope’s current group set to otherusers. hope must be a member of the otherusers group.

Extend/reset sudo‘s automatic authentication timeout, allowing you to continue issuing sudo commands without entering a password.

«Kill» sudo authentication for the current user. The next sudo command requires a password.

su — Become the superuser or another user.
visudo — Edit the sudoers file, which defines who can run sudo.

Источник

Администратор в Ubuntu, или Что такое sudo

Содержание

В любой Linux-системе обязательно есть один привилегированный пользователь — root. Этот пользователь имеет права на выполнение любых действий, удаление любых файлов и изменение любых параметров. Как-то ограничить свободу действий root практически невозможно. С другой стороны, все остальные пользователи системы обычно не имеют большинства необходимых прав, например, прав на установку программ, поскольку это является административной операцией, права на которую есть только у root. Ещё одной распространённой операцией, доступной только суперпользователю, является копирование и изменение файлов в системных папках, куда обычный пользователь доступа не имеет.

Раньше данная проблема решалась достаточно просто: при обладании паролем root можно было зайти в систему под его аккаунтом либо временно получить его права, используя команду su . Потом выполнить все необходимые операции и вернуться обратно под обычного пользователя. В принципе, такая схема работает неплохо, однако у неё есть много существенных недостатков, в частности, невозможно никак (точнее, очень сложно) ограничивать административные привилегии только определённым кругом задач.

Поэтому в современных дистрибутивах Linux вместо root аккаунта для администрирования используется утилита sudo .

В Ubuntu по умолчанию root аккаунт вообще отключён, т.е. вы никаким способом не сможете попасть под root, не включив его. root именно что отключён, т.е. он присутствует в системе, под него всего лишь нельзя зайти. Если вы хотите вернуть возможность использовать root, смотрите ниже пункт о включении root аккаунта.

Что такое sudo

sudo — это утилита, предоставляющая привилегии root для выполнения административных операций в соответствии со своими настройками. Она позволяет легко контролировать доступ к важным приложениям в системе. По умолчанию, при установке Ubuntu первому пользователю (тому, который создаётся во время установки) предоставляются полные права на использование sudo. Т.е. фактически первый пользователь обладает той же свободой действий, что и root. Однако такое поведение sudo легко изменить, об этом см. ниже в пункте про настройку sudo.

Где используется sudo

sudo используется всегда, когда вы запускаете что-то из меню Администрирования системы. Например, при запуске Synaptic вас попросят ввести свой пароль. Synaptic — это программа управления установленным ПО, поэтому для её запуска нужны права администратора, которые вы и получаете через sudo вводя свой пароль.

Однако не все программы, требующие административных привилегий, автоматически запускаются через sudo. Обычно запускать программы с правами администратора приходится вручную.

Запуск графических программ с правами администратора

Для запуска графических программ с правами администратора можно воспользоваться диалогом запуска программ, вызываемым по умолчанию сочетанием клавиш Alt + F2 .

Допустим, нам необходимо запустить файловый менеджер Nautilus с правами администратора, чтобы через графический интерфейс как-то изменить содержимое системных папок. Для этого необходимо ввести в диалог запуска приложений команду

Вместо gksudo можно подставить gksu , кроме того, пользователи KDE должны вместо gksudo писать kdesu . У вас попросят ввести свой пароль, и, если вы обладаете нужными правами, Nautilus запуститься от имени администратора. Запуск любого графического ПО можно производить с правами администратора, просто написав в диалоге запуска

Запуск программ с правами администратора в терминале

Для запуска в терминале команды с правами администратора просто наберите перед ней sudo :

У вас попросят ввести ваш пароль. Будьте внимательны, пароль при вводе никак не отображается, это нормально и сделано в целях безопасности, просто вводите до конца и нажимайте Enter . После ввода пароля указанная команда исполнится от имени root.

Система какое-то время помнит введённый пароль (сохраняет открытой sudo-сессию). Поэтому при последующих выполнениях sudo ввод пароля может не потребоваться. Для гарантированного прекращения сессии sudo наберите в терминале

Кроме того, часто встречаются ошибки, связанные с каналами в Linux. При исполнении команды

с правами root исполнится только cat , поэтому файл result.txt может не записаться. Нужно либо писать sudo перед каждой командой, либо временно переходить под суперпользователя.

Получение прав суперпользователя для выполнения нескольких команд

Иногда возникает необходимость выполнить подряд несколько команд с правами администратора. В этом случае можно временно стать суперпользователем одной из следующих команд:

После этого вы перейдёте в режим суперпользователя (с ограничениями, наложенными через настройки sudo), о чём говорит символ # в конце приглашения командной строки. Данные команды по действию похожа на su , однако: — sudo -s — не меняет домашний каталог на /root, домашним остается домашний каталог пользователя вызвавшего sudo -s, что обычно очень удобно. — sudo -i — сменит так же и домашний каталог на /root.

Для выхода обратно в режим обычного пользователя наберите exit или просто нажмите Ctrl + D .

Использование традиционного root аккаунта и команды su

Ubuntu 11.04 и младше

Для входа под root достаточно задать ему пароль:

Потом на экране входа нажмите Другой… и введите логин (root) и пароль, который вы задали.

Ubuntu 11.10 и старше

Начиная с версии 11.10 был установлен менеджер входа lightdm, и дело со входом под root обстоит немного сложнее.

1. Устанавливаем root пароль. Введите в терминал:

2. Включаем пункт «Введите логин». Введите в терминал:

В конце файла допишите:

3. Перезагружаем lightdm. Введите в терминал:

Все, на экране входа появится пункт «Логин». В поле логин вводим «root», в поле пароль — пароль, который мы задали на первом этапе.

Для обратной блокировки учетной записи root вам потребуется откатить изменения в настройках lightdm, а также заблокировать учетную запись root командой в терминале:

Настройка sudo и прав доступа на выполнение различных команд

sudo позволяет разрешать или запрещать пользователям выполнение конкретного набора программ. Все настройки, связанные с правами доступа, хранятся в файле /etc/sudoers . Это не совсем обычный файл. Для его редактирования необходимо (в целях безопасности) использовать команду

По умолчанию, в нём написано, что все члены группы admin имеют полный доступ к sudo , о чём говорит строчка

Подробнее о синтаксисе и возможностях настройки этого файла можно почитать выполнив

Разрешение пользователю выполнять команду без ввода пароля

Для того, что бы система не запрашивала пароль при определенных командах необходимо в sudoers после строки # Cmnd alias specification добавить строку, где через запятую перечислить желаемые команды с полным путём(путь команды можно узнать, выполнив which имя_команды:

И в конец файла дописать строку

Создание синонимов (alias`ов)

Для того, чтобы не только не вводить пароль для sudo, но и вообще не вводить sudo, сделайте следующее: откройте файл .bashrc, находящейся в вашем домашнем каталоге

и добавьте в конец файла строки

Время действия введённого пароля

Возможно, вы хотите изменить промежуток времени, в течение которого sudo действует без ввода пароля. Этого легко добиться добавив в /etc/sudoers (visudo) примерно следующее:

Здесь sudo для пользователя foo действует без необходимости ввода пароля в течение 20 минут. Если вы хотите, чтобы sudo всегда требовал ввода пароля, сделайте timestamp_timeout равным 0.

sudo не спрашивает пароль

sudo без пароля — чудовищная дыра в безопасности, кому попало разрешено делать что угодно. Если вы разрешили это намеренно — срочно верните обратно как было.

Однако, в некоторых случаях sudo внезапно перестаёт требовать пароль само по себе. Если сделать visudo , то можно увидеть примерно такую строку, которую пользователь вроде бы не добавлял:

Скорее всего, эта катастрофичная строка была добавлена при установке программы типа Connect Manager от МТС или Мегафона. В таком случае, её нужно поменять на строку, разрешающую с правами root запускать только этот Connect Manager, примерно так:

Есть и другие варианты решения проблемы, небольшое обсуждение здесь.

Источник

Читайте также:  Hp compaq dc7700 драйвера windows
Оцените статью