- How to add user to sudoers with best practices & examples
- Overview on sudoers privilege
- Recommended guidelines to edit sudoers file
- Syntax of sudoers file
- First column
- Second Column
- Third Column
- Fourth Column
- How to add user to sudoers
- Example to understand first field of sudoers file
- Example to understand second field of sudoers file
- Example to understand third field of sudoers file
- How to use alias in sudoers
- Disallow a set of commands in sudoers
- Remove password prompt for sudo user
- Conclusion
- Related Posts
- Как добавить пользователя в Sudoers в Ubuntu
- Добавление пользователя в группу sudo
- Добавление пользователя в файл sudoers
- Выводы
How to add user to sudoers with best practices & examples
Table of Contents
How do we add user to sudoers file? How to give user sudo access? How to give root privileges to a user in linux? how to give superuser permission in linux? What are sudo alias? What is the syntax used by sudoers file?
These are some of the common questions user have when they start working with sudoers file. In this tutorial I will give you a detailed overview on sudo privileges and share the proper way to add user to sudoers file.
Overview on sudoers privilege
- Normal users operate in limited privilege sessions to limit the scope of their influence on the entire system.
- One special user exists on Linux that we know already is root, which has super-user privileges.
- This account doesn’t have any restrictions that are present to normal users.
- Sudoer is the functionality of the Linux system that can be used by an administrator to provide administrative access to a trusted regular user, without actually sharing the root user’s password.
- The administrator simply needs to add the regular user in the sudoers list.
- Once a user has been added to the sudoers list, they can execute any administrative command by preceding it with sudo.
- Then the user would be asked to enter their own password depending upon the configuration.
- After this, the administrative command would be executed the same way as by the root user.
It is very important to update sudoers correctly or else you may break the complete sudoers functionality. There is a particular syntax which must be followed while adding a user or new entry to the sudoers file.
We will discuss about those syntax later in this article. But first let me highlight you the dos and dont’s which you must follow when working with sudoers file.
Recommended guidelines to edit sudoers file
- You should avoid using echo » » >> /etc/sudoers method to add any user content to main sudoers file. The reason being, if you follow incorrect syntax then you can break the entire sudoers functionality
- Always use » visudo » to edit the /etc/sudoers file. It is again not recommended to use any editor such as vim or nano etc to directly edit the /etc/sudoers file. This is because visudo editor is part of sudo rpm and it will perform a syntax check before we save and exit the sudoers file. Assuming you have provided an incorrect syntax in the sudoers file and try to save and exit the sudoers file, you will get this error prompt:
- So visudo will warn you for any incorrect syntax, but if you edit /etc/sudoers using any normal editor then there will no syntax check performed and you may end up with incorrect sudoers entry
- Another advantage with visudo is that it will protect you from race condition when multiple user try to modify sudoers file at the same time. If visudo is used in parallel when there is already a visudo session then you will get » visudo: /etc/sudoers busy, try again later «
- It is always a good practice to leave the default sudoers file untouched, you should add any custom content inside /etc/sudoers.d as which this the chances of corrupting the original sudoers content will be minimal.
- By default /etc/sudoers contain below entry
- So you can create multiple files based on your teams or groups under /etc/sudoers.d/ and add respective sudo permissions for users or groups in your organization. This will make sure other sudo users are not impacted by any syntax error
I hope we are clear on the dos and dont’s before you work on sudoers file. Let us now understand the basic syntax of sudoers file.
Syntax of sudoers file
The syntax usage of sudoers can be little tricky and complicated for complex use cases. To fully explain the syntax of /etc/sudoers , we will use a sample rule and break down each column:
First column
- The first column defines what user or group this sudo rule applies to.
- In this case, it is the user deepak .
- If the word in this column is preceded by a % symbol, it designates this value as a group instead of a user, since a system can have users and groups with the same name.
Second Column
- The second value (ALL) defines what hosts this sudo rule applies to.
- This column is most useful when you deploy a sudo environment across multiple systems.
- For a desktop Ubuntu system, or a system where you don’t plan on deploying the sudo roles to multiple systems, you can feel free to leave this value set to ALL , which is a wildcard that matches all hosts.
- For single server deployment this section does not has much usage and can be left to default ALL or provide localhost’s hostname
Third Column
- The third value is set in parentheses and defines what user or users the user in the first column can execute a command as.
- This value is set to root , which means that deepak will be allowed to execute the commands specified in the last column as the root user.
- This value can also be set to the ALL wildcard, which would allow deepak to run the commands as any user on the system.
Fourth Column
- The last value ( /usr/bin/find , /bin/rm ) is a comma-separated list of commands the user in the first column can run as the user(s) in the third column.
- In this case, we’re allowing deepak to run find and rm as root with sudo privileges.
- This value can also be set to the ALL wildcard, which would allow deepak to run all commands on the system as root.
So now that we know about the basic syntax of sudoers file, let us go ahead and add some users to sudoers file with privilege to execute few commands as root user
How to add user to sudoers
In this example we want to provide sudo privilege to user » deepak » from my Linux server to be able to execute chown and chmod as root user
Example to understand first field of sudoers file
I will create a new file under /etc/sudoers.d/ by the name » custom «, you can use any name as per your requirement
Add the below content in this file using visudo
Save and exit the file.
Add user to sudoers
Next try to login as deepak user and execute chown as sudo
So the command prompts for password and the execution is successful. You can ignore the » missing operand » error, since I have not used proper command syntax, the command is throwing error. But we know the command was executed successfully with sudo privilege
Now this would explain the first column
Example to understand second field of sudoers file
Let’s understand the usage of second column.
Now we have 100 servers and using some remote tool we are deploying sudoers list to all these 100 servers. Now our of these 100 servers we want user deepak to be allowed to use chown only on the host with hostname » server » so we will use
Now the same sudoers script will be deployed to 100 servers but user deepak will be allowed use chown with sudo only on server. If he tries to use chown on other servers, he will get
While the same would work on » server » host
But again this is of not too much use when you are working on single server deployment. You can choose to use wildcard ALL or provide the hostname of your host, either should be fine.
So this explains the second column.
Example to understand third field of sudoers file
Let us understand how third column is used in sudoers file.
We have a script which should only be used by user » amit » but due to some requirement we also want user » deepak » to be able to execute this script.
Sample script to verify sudo permission
sudo to the rescue
We will add below content to our /etc/sudoers.d/custom
If deepak tries to call amit_script.sh , he is asked to » Get Lost «
Then he tries to run the same script as sudo user, but sadly the output says he is not allowed to execute /tmp/amit_script.sh when he knows he was given privilege for this.
The problem is, deepak is trying to run amit’s script so he must use » sudo -u amit » to be able to execute amit’s script as amit user. So let’s give one more try:
Bingo, it worked.
So I hope the third column usage was clear.
The fourth column should be easy to understand. You must provide the list of commands, or scripts with full path separated by a command and whitespace character.
How to use alias in sudoers
There is a concept of alias in sudoers which can keep your sudoers file organized and clean. It is similar to a variable which we use in scripts and codes. Here in the below syntax, all the ALIAS_NAME must be provided in UPPERCASE letters or you will get syntax error.
You can create a user alias using
To create a command alias
To create host alias
For example, I have a scenario where I want to assign permission to execute same set of commands to a bunch of users. Now these users are from different system groups. So in such case I have below possible options
- Create a new system group and assign these users to that system group so I can assign all permissions to single system group
- I create separate entries for all these users and then assign permission (very lengthy task)
- Create a User Alias inside sudoers file and then assign permission in single line
So the third option sounds easy and neat. Hence I will create a new User_Alias and add the usernames to this alias
Next assign the permission of commands to this alias
So now all the users part of MYADMINS alias group will have sudo privilege to execute chown as root user.
Disallow a set of commands in sudoers
We can also prevent users from executing a certain set of commands, scripts inside sudoers . For example, I want user deepak to be able to execute all commands inside /usr/bin except chown command.
So open the sudoers file
So here we have allowed all the commands under /usr/bin/* but have added a NOT ( ! ) operator for /usr/bin/chown . You can add multiple commands in the similar format to block the sudo access for these provided commands for respective user or group
Let us verify this permission:
As expected, user deepak is allowed to use chmod
But execution of chown is denied as defined in our configuration
Remove password prompt for sudo user
By default you may have observed that, every time user tries to execute a command with sudo privilege, they are prompted for user password. This is the default behaviour of sudoers . To overwrite this you must use NOPASSWD in the sudoers file while adding the user permission in the below format (from our last example)
So now user deepak can execute all the commands with sudo privilege without the need to enter password every time
These can be used with scripting solutions to automate the command execution.
Conclusion
In this tutorial I gave you a complete overview on best practices to use and modify sudoers file. The steps to add user to sudoers with proper syntax and different practical examples, about different alias, and executing sudo commands without password prompt. In production environment, sudoers file are handled very cautiously. The default sudoers file contain a lot of default entries and it may break if you do not modify the this file properly.
Lastly I hope the steps from the article to learn all about sudo privilege and sudoers file on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
You can read more about sudo privilege:
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник
Как добавить пользователя в Sudoers в Ubuntu
sudo — это программа командной строки, которая позволяет доверенным пользователям выполнять команды от имени пользователя root или другого пользователя.
В этой статье мы покажем вам два способа предоставить пользователю права sudo. Первый — добавить пользователя в файл sudoers . Этот файл содержит информацию, которая контролирует, каким пользователям и группам предоставлены привилегии sudo, а также уровень этих привилегий.
Второй вариант — добавить пользователя в группу sudo, указанную в файле sudoers . По умолчанию в дистрибутивах на основе Debian, таких как Ubuntu и Linux Mint, членам группы «sudo» предоставляется доступ sudo.
Добавление пользователя в группу sudo
В Ubuntu самый простой способ предоставить пользователю права sudo — это добавить пользователя в группу «sudo». Члены этой группы могут выполнять любую команду как root через sudo и sudo запрос на аутентификацию с помощью своего пароля при использовании sudo .
Мы предполагаем, что пользователь уже существует. Если вы хотите создать нового пользователя, ознакомьтесь с этим руководством.
Чтобы добавить пользователя в группу, выполните команду ниже от имени пользователя root или другого пользователя sudo. Убедитесь, что вы заменили «username» на имя пользователя, которому вы хотите предоставить разрешения.
Предоставления доступа sudo с помощью этого метода достаточно для большинства случаев использования.
Чтобы убедиться, что у пользователя есть привилегии sudo, выполните команду whoami :
Вам будет предложено ввести пароль. Если у пользователя есть доступ к sudo, команда выведет «root»:
Если вы получаете сообщение об ошибке «пользователя нет в файле sudoers», это означает, что у пользователя нет прав sudo.
Добавление пользователя в файл sudoers
/etc/sudoers доступа sudo пользователей и групп определены в /etc/sudoers . Добавление пользователя в этот файл позволяет вам предоставить индивидуальный доступ к командам и настроить собственные политики безопасности.
Вы можете настроить доступ пользователя sudo, изменив файл sudoers или создав новый файл конфигурации в каталоге /etc/sudoers.d . Файлы внутри этого каталога включены в файл sudoers.
Всегда используйте visudo для редактирования файла /etc/sudoers . Эта команда проверяет файл на наличие синтаксических ошибок при его сохранении. Если есть ошибки, файл не сохраняется. Если вы откроете файл в текстовом редакторе, синтаксическая ошибка может привести к потере доступа sudo.
Обычно visudo использует vim для открытия /etc/sudoers . Если у вас нет опыта работы с vim и вы хотите отредактировать файл с помощью nano , измените редактор по умолчанию, запустив:
Допустим, вы хотите разрешить пользователю запускать команды sudo без запроса пароля. Для этого откройте файл /etc/sudoers :
Прокрутите вниз до конца файла и добавьте следующую строку:
Сохраните файл и выйдите из редактора . Не забудьте изменить «имя пользователя» на имя пользователя, которому вы хотите предоставить доступ.
Другой типичный пример — разрешить пользователю запускать только определенные команды через sudo . Например, чтобы разрешить только команды mkdir и rmdir , вы должны использовать:
Вместо редактирования файла sudoers вы можете сделать то же самое, создав новый файл с правилами авторизации в каталоге /etc/sudoers.d . Добавьте то же правило, что и в файл sudoers:
Такой подход делает управление привилегиями sudo более удобным в обслуживании. Имя файла не имеет значения. Обычно имя файла совпадает с именем пользователя.
Выводы
Предоставление доступа sudo пользователю в Ubuntu — простая задача; все, что вам нужно сделать, это добавить пользователя в группу «sudo».
Если у вас есть вопросы, не стесняйтесь оставлять комментарии.
Источник