Linux debian получить права root

Linux debian получить права root

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.

Читайте также:  Icon set for linux

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!

Читайте также:  Распаковать вложенные архивы linux

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.

Источник

Права суперпользователя Debian (sudo, visudo)

В операционных системах семейства Linux реализован принцип разграничения пользовательских привилегий, то есть у разных учетных записей разный объем прав доступа к каталогам, файлам и программам. Максимальными правами наделена встроенная учетная запись root. Вновь создаваемые пользовательские аккаунты обычно существенно ограничены в доступе к системным конфигурационным файлам, управлении сервисами, установке и удалении программных пакетов. При этом работа в операционной системе под учетной записью root настоятельно не рекомендуется, прежде всего в целях безопасности. В этом случае на помощь приходит утилита командной строки sudo.

Команда sudo позволяет запускать отдельные команды с повышением привилегий (по умолчанию с правами root) пользуясь непривилегированной учетной записью. Давайте разберемся, что же требуется для работы этой утилиты.

Установка и настройка

В ОС Ubuntu sudo включена по умолчанию, а в Debian, если в процессе установки не был выбран соответствующий пакет, скорее всего будет следующая картина:

root@debian10:~# sudo
-bash: sudo: command not found

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

apt-get update
apt-get install sudo

Дожидаемся окончания процесса:

После успешной установки потребуется сконфигурировать sudo, определив, какие пользователи или группы смогут использовать повышение привилегий и в каком объеме. Все эти настройки хранятся в конфигурационном файле /etc/sudoers, однако вносить в него изменения напрямую настоятельно не рекомендуется. Для этих целей используется специальная команда:

которая запускает текстовый редактор с конфигурационным файлом:

За предоставление прав здесь отвечают две строки:

root ALL=(ALL:ALL) ALL
%sudo ALL=(ALL:ALL) ALL

Первая строка назначает права для учетной записи root, вторая устанавливает права для членов группы sudo, которая была создана при установке пакета (знак % перед названием означает, что имя относится к группе пользователей). Соответственно, у нас есть два основных способа предоставить пользовательской учетной записи право использовать sudo:

Читайте также:  Посмотреть версию видеокарты linux

1. Добавить учетную запись пользователя (например, user) в группу sudo на сервере:

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

2. Создать в файле новую запись, например, для учетной записи user. Мы добавляем строку по аналогии с root:

Добавлять новую запись рекомендуется в тех случаях, когда список привилегий будет корректироваться (об этом чуть позднее). Если мы внесли изменения в файл, нужно их сохранить нажатием сочетания клавиш Ctrl-O и выйти из редактора — Ctrl-X.

Теперь можно проверить корректность работы:

user@debian10:~$ sudo cat /etc/sudoers
[sudo] password for user:

Команда sudo запрашивает пароль текущего пользователя (в данном случае это user) — вводим его, и, если все сделано правильно, мы увидим содержание системного конфигурационного файла.

Тонкая настройка

Таким образом, обычный пользователь может запускать команды с правами учетной записи root не зная ее пароль. Это очень удобно, но может быть небезопасно — есть ли возможность ограничить круг команд, которые можно исполнять посредством sudo? Да, и поможет нам в этом тот же самый конфигурационный файл. Снова запускаем visudo и разбираемся дальше. Нас интересуют параметры, указанные после имени пользователя:

  • ALL=(ALL:ALL) ALL — первый параметр определяет к какому хосту применяется конфигурация. При использовании выделенного сервера параметр можно оставить без изменений;
  • ALL=(ALL:ALL) ALL — параметры в скобках определяют с полномочиями какого пользователя (первый параметр) и/или группы (второй параметр) будет выполняться команда. По умолчанию sudo выполняет команду от имени root, однако при запуске с ключом –u можно указать другую учетную запись, а с ключом –g другую группу, чьи полномочия будут использованы при запуске;
  • ALL=(ALL:ALL) ALL — третий параметр определяет к каким файлам и командам относятся данные настройки.

Исходя из вышесказанного, при необходимости определить перечень разрешенных команд заменяем последний параметр ALL тем, что нам требуется, перечисляя команды через запятую. Например, строка:

user ALL=(ALL:ALL) /sbin/shutdown –r, /bin/cat

дает право пользователю user с помощью sudo осуществлять перезагрузку сервера командой sudo /sbin/shutdown –r и просматривать файлы с помощью sudo /bin/cat. Другие команды через sudo выполняться не будут. Например, при попытке выключить сервер командой sudo /sbin/shutdown –h, получим ответ:

Sorry, user user is not allowed to execute '/sbin/shutdown -h' as root on debian10.

Полезное

Увидеть список привилегий можно, запустив sudo –l (будет отображен список для текущего пользователя), либо sudo –l –U user (будет отображен список привилегий пользователя user):

В состав sudo входит команда sudoedit, которая запускает текстовый редактор с указанным файлом сразу с повышенными привилегиями, то есть вместо команды:

sudo nano /etc/network/interfaces

Если требуется длительная работа в режиме повышенных привилегий и вводить sudo для каждой команды неудобно, можно запустить через sudo экземпляр командного интерпретатора:

и продолжить работу в нем — все команды будут запускаться с повышенными правами. По завершении работы выходим из интерпретатора командой exit.

Источник

Оцените статью
Adblock
detector