How To Edit the Sudoers File

Introduction

Before we start talking about how to edit the sudoers file, let's briefly understand-What is Sudoers File ?

The sudoers file in Linux controls user access to administrative tasks through the sudo command. By editing the sudoers file, you can grant or restrict specific users or groups from running commands with administrative privileges.

One of the key security models used on Linux and other Unix-like operating systems is privilege separation. Regular users have restricted access to the operating system in order to confine their effect to their immediate surroundings.

This tutorial goes into great detail about sudoers and privilege escalation. Check out our How To Create a New Sudo-enabled User quick start instructions for Ubuntu and CentOS if you simply want to provide a user sudo privileges.

How To Obtain Root Privileges

There are three fundamental ways to gain root privileges, ranging in complexity.

Logging In As Root

Directly logging into your server as the root user is the simplest and fastest way to obtain root access.

If you are connecting into a local system (or using a virtual server's out-of-band console feature), use root as your username and the root password when prompted:

When entering SSH, enter the root user before the IP address or domain name in your SSH connection string:

ssh root@server_domain_or_ip

Enter the root password when prompted if the root user's SSH keys have not been setup.

Using su to Become Root

Direct root logins are generally not suggested because it is simple to start using the system for purposes other than administration, which can be hazardous.

You can assume the role of the root user whenever you need to by using the following procedure.

The "substitute user" command, su, can be used to accomplish this. To obtain root privileges, enter:

su

Following a request for the root user's password, a root shell session will be launched for you.

After completing the actions that call for root privileges, type the following to return to your normal shell:

exit

Using sudo to Execute Commands as Root

The sudo command is the last method of gaining root privileges that we'll cover.

Without having to make a new shell, you can execute one-off commands as root with the sudo command. It is carried out as follows:

sudo command_to_execute

The sudo command, unlike su, will ask for the current user's password rather than the root password.

sudo access is not given to users by default and needs to be set up before it works properly because of the security considerations. To understand how to set up a sudo-enabled user, visit our quick start tutorials for Ubuntu and CentOS on How To Create a New Sudo-enabled User.

We will go into more depth about changing the sudo configuration in the section that follows.

What is Visudo?

The /etc/sudoers file is used to configure the sudo command.

⚠️
Warning: Never use a standard text editor to modify this file! Use the visudo command instead at all times!

It is vital to use the visudo command when modifying the /etc/sudoers file, since erroneous syntax can result in a damaged system that prevents you from gaining elevated privileges.

The visudo command launches a text editor as usual, but before saving, it verifies the file's syntax. This keeps sudo operations from being terminated by configuration issues, which might be the only way for you to gain root privileges.

Traditionally, visudo uses the vi text editor to open the /etc/sudoers file. However, Ubuntu has set up visudo to utilize the nano text editor in its place.

Using the command line, you can return it to vi by typing:

sudo update-alternatives --config editor
Output
There are 4 choices for the alternative editor (providing /usr/bin/editor).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /bin/nano            40        auto mode
  1            /bin/ed             -100       manual mode
  2            /bin/nano            40        manual mode
  3            /usr/bin/vim.basic   30        manual mode
  4            /usr/bin/vim.tiny    10        manual mode

Press <enter> to keep the current choice[*], or type selection number:

Choose the number that is corresponding to the decision you want to make.

You can alter this value on CentOS by including the subsequent line in your ~/.bashrc:

export EDITOR=`which name_of_editor`

To make the modifications, source the following file:

. ~/.bashrc

Run the following command to view the /etc/sudoers file after configuring visudo:

sudo visudo

How To Modify the Sudoers File

The /etc/sudoers file will appear in the text editor you've decided.

I have removed the remarks and copied and pasted the file from Ubuntu 20.04. There are many more lines in the CentOS /etc/sudoers file, some of which we won't cover in this article.

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

root    ALL=(ALL:ALL) ALL

%admin ALL=(ALL) ALL
%sudo   ALL=(ALL:ALL) ALL

#includedir /etc/sudoers.d

Let's see what these lines accomplish.

Default Lines

The first line, Defaults env_reset, clears all user variables from the terminal environment. Clearing the sudo session of possibly dangerous ambient factors is done as a safety step.

The system is instructed to mail alerts of failed sudo password attempts to the specified mailto user by the second line, Defaults mail_badpass. This is the root account by default.

The PATH (the locations in the filesystem the operating system will seek for applications) that will be used for sudo actions is specified in the third line, which starts with Defaults secure_path=... This stops potentially hazardous user paths from being used.

User Privilege Lines

The sudo privileges for the root user are specified on the fourth line, which is distinct from the lines before it. Let's examine what the various fields mean:

  • root ALL=(ALL:ALL) ALL The username (root) to which the rule will apply is indicated in the first field.
  • root ALL=(ALL:ALL) ALL The first "ALL" denotes that all hosts are subject to this regulation.
  • root ALL=(ALL:ALL) ALL This "ALL" denotes the root user's ability to execute instructions for all users.
  • root ALL=(ALL:ALL) ALL This "ALL" denotes the root user's ability to execute commands on behalf of all groups.
  • root ALL=(ALL:ALL) ALLThe final "ALL" denotes that all commands must abide by these guidelines.

This means that as long as the root user enters their password, they can execute any command using sudo.

Group Privilege Lines

Similar to the lines describing user privileges, the following two lines outline sudo rules for groups.

Names that start with a % are group names.

We can see that the admin group can run any command as any user on any host in this instance. In a similar vein, the sudo group the same privileges, but can execute as any group as well.

Included /etc/sudoers.d Line

The last line appears to be a comment at first:

. . .

#includedir /etc/sudoers.d

Yes, it starts with a #, which typically denotes a comment. This line, however, actually says that files from the /etc/sudoers.d directory will also be sourced and used.

That directory's files adhere to the same guidelines as the /etc/sudoers file itself. The sudo configuration will be read from and added to any file that does not end in ~ and does not contain a ..

The major purpose of this is to allow apps to change the sudo privileges after installation. The /etc/sudoers.d directory can make it simple to determine what privileges are assigned to which accounts and to reverse credentials without having to try by putting all the related rules in a single file.

You should always use visudo to edit files in the /etc/sudoers.d directory, just like you should with the /etc/sudoers file itself. The syntax to edit these files is as follows:

sudo visudo -f /etc/sudoers.d/file_to_edit

How To Give a User Sudo Privileges

Giving a new user general sudo access is the most frequent task users attempt when handling sudo access. If you wish to grant a user account full administrative access to the system, this is helpful.

On a system configured with a general purpose administration group, like the Ubuntu system in this guide, adding the user in question to that group is actually the simplest way to accomplish this.

For instance, the sudo group has full admin privileges on Ubuntu 20.04. By including a user in the group, we may provide them the same privileges, just like this:

sudo usermod -aG sudo username

You can use the gpasswd command to:

sudo gpasswd -a username sudo

Both of these will achieve the same objective.

Instead of the sudo group, the wheel group is typically used on CentOS:

sudo usermod -aG wheel username

Or, via gpasswd:

sudo gpasswd -a username wheel

CentOS, you might need to update the /etc/sudoers file to uncomment the group name if adding the user to the group does not take effect right away:

sudo visudo
. . .
%wheel ALL=(ALL) ALL
. . .

How To Set Up Custom Rules

Let's create some new rules now that we are familiar with the file's general syntax.

How To Create Aliases

Grouping items with multiple "aliases" will make organizing the sudoers file easier.

For instance, we can develop three distinct user groups that share members:

. . .
User_Alias		GROUPONE = abby, brent, carl
User_Alias		GROUPTWO = brent, doris, eric,
User_Alias		GROUPTHREE = doris, felicia, grant
. . .

Names of groups must begin with a capital letter. Then, by establishing a rule like this, we may permit GROUPTWO members to change the apt database.

. . .
GROUPTWO	ALL = /usr/bin/apt-get update
. . .

Without a user or group specified, sudo runs as the root user by default.

By generating a "command alias" and utilizing it in a GROUPTHREE rule, we may permit members of GROUPTHREE to shut down and restart the computer:

. . .
Cmnd_Alias		POWER = /sbin/shutdown, /sbin/halt, /sbin/reboot, /sbin/restart
GROUPTHREE	ALL = POWER
. . .

We establish the command alias POWER, which comprises commands for rebooting and turning off the computer. We then give the GROUPTHREE members the authority to carry out these directives.

Additionally, "Run as" aliases can be made, which can take the place of the rule's clause designating the user as which the command should be executed:

. . .
Runas_Alias		WEB = www-data, apache
GROUPONE	ALL = (WEB) ALL
. . .

The www-data user or the apache user can now be used to execute commands by any member of GROUPONE.

Just keep in mind that the later rule will take precedence if there is a conflict between two regulations.

How To Lock Down Rules

You may exert additional control over how sudo responds to a call in a number of ways.

On a single-user system, the updatedb command that comes with the mlocate package is comparatively safe. If we want people to be able to run it as root without having to enter a password, we can implement the following rule:

. . .
GROUPONE	ALL = NOPASSWD: /usr/bin/updatedb
. . .

No password will be requested, as indicated by the "tag" NOPASSWD. There is a companion command named PASSWD that is used by default. Unless overruled by its "twin" tag later on, a tag is relevant for the remainder of the rule.

In this case, we can have a line like this:

. . .
GROUPTWO	ALL = NOPASSWD: /usr/bin/updatedb, PASSWD: /bin/kill
. . .

NOEXEC is a useful tag that can be used to stop some hazardous behaviours in some programs.

For instance, certain programmes, like less, allow you to launch additional commands by entering the following from their user interface:

!command_to_run

This essentially executes any command the user offers while operating under the same permissions as less, which might be quite risky.

We could use a line like this to restrict this:

. . .
username	ALL = NOEXEC: /usr/bin/less
. . .

Miscellaneous Information

There are a few more details that could be helpful while working with sudo.

By using the -u and -g flags, you can run commands as the users or groups you designated in the configuration file to "run as":

sudo -u run_as_user command
sudo -g run_as_group command

By default, sudo will save your authentication information on one terminal for a predetermined amount of time for your convenience. This indicates that you won't need to enter your password again until the timer expires.

If you want to stop the timer for security reasons after executing administrative commands, type the following command:

sudo -k

However, you can always type: to "prime" the sudo command so that you won't be prompted again, or to renew your sudo lease:

sudo -v

Your password will be requested and stored for future sudo uses until the sudo time limit expires.

You can type the following if you're just curious about the privileges that are associated with your login:

sudo -l

This will provide a list of each rule that your user is bound by in the /etc/sudoers file. This offers you a clear picture of what you may and cannot do when using sudo as any user.

There are numerous occasions when you will run a command without using sudo, causing it to fail. You can use a bash feature called "repeat last command" to avoid having to type the command again:

sudo !!

The previous instruction will be repeated if you use two exclamation points. To fast change the unprivileged command to a privileged command, we used sudo to come before it.

You can use visudo to add the following line to your /etc/sudoers file for some fun:

sudo visudo
. . .
Defaults	insults
. . .

When a user fills in the wrong password for sudo, this will result in sudo returning a ludicrous insult. To test it out, we may run sudo -k to clear the previous sudo cached password:

sudo -k
sudo ls
Output
[sudo] password for demo:    # enter an incorrect password here to see the results
Your mind just hasn't been the same since the electro-shock, has it?
[sudo] password for demo:
My mind is going. I can feel it.

FAQs to Edit Sudoers File

What precautions should I take before editing the sudoers file? 

It is crucial to use caution when editing the sudoers file because incorrect changes can lead to system instability or being locked out. Always make a backup of the original file and use a text editor that respects the file's integrity, such as visudo.

How can I edit the sudoers file safely? 

It is recommended to use the visudo command, which validates your changes before saving and prevents concurrent editing by multiple users, avoiding syntax errors that could lock you out.

Which editor should I use with visudo? 

By default, visudo uses the system's default editor. You can change the default editor by setting the VISUAL or EDITOR environment variables to your preferred editor, such as nano or vim.

What is the syntax used in the sudoers file? 

The sudoers file uses a specific syntax, with configuration lines structured as user host_list=(runas_list) command_list. It specifies which users can execute specific commands as other users on specific hosts.

How can I restrict a user or group from using sudo? 

To restrict a user or group from using sudo, you can comment out or remove the corresponding configuration line in the sudoers file. Make sure to follow the proper syntax and only remove the necessary lines.

Can I grant sudo access for specific commands only? 

Yes, you can grant sudo access for specific commands by specifying the command_list in the configuration line of the sudoers file. For example, my_user ALL=(ALL) /bin/ls allows my_user to execute only the ls command with sudo.

Can I include other configuration files in the sudoers file? 

Yes, you can include other configuration files in the sudoers file using the #includedir directive. This allows you to split the sudoers configuration into multiple files and directories for better organization.

Conclusion

With this knowledge, you should be able to read and modify the sudoers file and understand the different ways you can gain root privileges.

Keep in mind that regular users are not granted super-user privileges without good reason. You must be aware of what each command you use to access resources as root does. Do not undervalue the responsibility. Learn how to use these tools most effectively for your use case, and shut down any unnecessary functionality.

If you have any queries or doubts, please leave them in the comment below.