How to use sudo in Linux and master the sudoers file

  • sudo allows you to execute commands as another user (usually root) in a controlled and temporary manner.
  • Permission settings are defined in /etc/sudoers and in the /etc/sudoers.d files using visudo.
  • Groups like sudo or wheel and aliases in sudoers make it easier to grant specific privileges to specific users.
  • Options like NOPASSWD allow you to adjust security and convenience when using sudo in different scenarios.

using sudo in Linux

If you work with Linux dailySooner or later you'll come across the command sudoIt's the key that allows you to perform administrative tasks without having to log in as a user. root All the time, which is not only inconvenient but also quite dangerous. Understanding how it works, what options it has, and how to configure it is crucial if you don't want to accidentally break the system or leave a security vulnerability without realizing it.

In this article we're going to go into detail. what exactly is it about? sudoWhat is its relationship with the user? root and with the file /etc/sudoersWhat are the differences between using su y sudoand how you can fine-tune the settings to grant very specific permissions (even without requiring a password) to certain users or groups. The idea is that, by the time you finish reading, you'll be very clear on when to use sudoWhat it does underneath and how to control it without fear.

What is sudo and why is it so important in Linux?

The command sudo It is one of the key pieces of any modern Linux system. Its name is usually explained as “superuser do” or “substitute user and do”, and its function is simple but powerful: it allows an authorized user to execute commands as if they were another user on the system, normally rootfor a limited time.

In practice, this means that a normal user can perform administrative tasks -installing packages, modifying system settings, managing services, changing permissions for sensitive files- without log in directly as rootThis separation between the regular user and the superuser is one of the pillars of security in Linux.

Most current distributions (Debian, Ubuntu, many derivatives, SLE-type systems, etc.) bring sudo It is pre-installed, and it is not recommended to uninstall or tamper with it lightly. Furthermore, on many systems, the user created during installation is automatically added to the administrative group that has permission to use it. sudo, becoming the default privileged user.

Something very important to keep in mind es que sudo It does not "convert" a user into root It doesn't grant full access to the system, but rather allows users to execute specific commands as another user, under rules defined in its configuration. This way, very specific permissions can be granted without giving full access to the system.

How sudo works internally

The basic operation of sudo It's very simple from the user's point of view: you place the word sudo before the command we want to execute with privileges. For example, to update the package list with apt-get In Debian or Ubuntu, a normal user will need to do something like:

> sudo apt-get update

If you try to run an administrative command without sudoMost commonly, you will receive errors such as "Permission denied" or messages indicating that a certain locked file cannot be opened in /var/lib or in another system directory. As soon as you repeat the same command adding sudo Next, the system will ask for your password and, if everything is configured correctly, the command will be executed with superuser privileges.

When you execute a command with sudoThe program first checks if your user is authorized to use it and for which specific commands, by consulting the configuration file. /etc/sudoers and, in many systems, the additional files in the directory /etc/sudoers.d/If the rules allow it, sudo It asks for the password (usually yours, not theirs). root) and temporarily elevates your privileges to run the command as the target user.

A curious detail that often throws you off at first When you're prompted for your password at the terminal, no characters appear, not even asterisks, as you type. This is perfectly normal: the input is "blind" and is part of the security measures to prevent the length of your password from being seen.

Furthermore, Sudo maintains a kind of "trust session"After successfully entering the password, elevated privileges remain active for a period of time (by default, about 15 minutes in many distributions) in that same terminal. During this period, you can execute more commands with sudo without it asking you for the password again and again.

Basic syntax and most useful options of sudo

The general syntax of sudo It is very simple:

> sudo command

The most common way to use it is simply , the sudo comandoHowever, it has a good number of interesting options. Some of the most used (and highlighted in many official guides) are the following:

  • -h: Displays a help message with the syntax and all available options of the program sudo.
  • -V: shows the current version of sudo and some compilation details.
  • -v: Renews the authentication "grace time", that is, refreshes the counter so that your privileges do not expire and you do not have to re-enter your password soon.
  • -k: immediately invalidates stored credentials; it's like telling sudo that "forgets" that you have already authenticated, forcing you to ask for your password again next time.
  • -l: shows which commands you are authorized to run with sudo according to the current configuration of sudoers.

There are also very useful options for running commands like other users. other than root. For example, with -u You can specify a target user for a specific command:

> sudo -u pedro whoami

In this case, even if your session belongs to another user, the command whoami It will return "pedro" because it was executed as if you were that user. This is very convenient for testing permissions or performing tasks associated with service accounts without having to manually switch sessions.

sudo versus su and the root user

In Linux, several mechanisms coexist. To obtain administrator privileges: register directly as root, use the command su and use sudoEach one has its pros and cons, and understanding them will save you a lot of trouble.

Log in directly as root (for example, with ssh root@servidorThis gives you full access to the system from the start. This is very convenient, but also extremely dangerous: any mistyped command can wipe half the system, change critical permissions, or render the machine unusable. Therefore, in most cases, working with login sessions is not recommended. root open permanently.

The command su (substitute user) It allows you to switch to another user within the same terminal. The original session remains in the background and "encapsulates" the new one. If you run su pedroYou will be asked for your password. pedro and, once inside, if you type exit You will revert to the previous user. If you do not specify a username, su By default, it tries to switch to root.

There is an important nuance with su: if you don't pass the login option (su -, su -l o su --login), changes user but not environment. This means you will remain in the working directory and with the variables of the previous user, which can cause permission errors (for example, when trying to list the home (of the original user with the new user's credentials).

In contrast, sudo It offers a safer and more controllable approachYou don't need to know the password for rootbut your own password, and the system decides, by /etc/sudoerswhich users can execute which commands, such as which users and from which machines. Furthermore, each use of sudo It is recorded in the logs, which makes it easier to audit what has been done with elevated permissions.

For interactive sessions “as another user” with sudoThere are some very practical variations:

  • sudo -s: opens a shell as the target user inheriting the current user's environment.
  • sudo -i: starts a full login shell for the target user, with their environment and directory clean. $HOME, loading files like .profile o .bash_profile.

Both options are useful for working on a one-off basis. as another user (usually root or any service account) without having to remember and use your password, while maintaining control and a record of the actions performed.

The /etc/sudoers file and the /etc/sudoers.d directory

The heart of the sudo configuration it's in the archive /etc/sudoersThat's where it's defined who can use it sudofrom where, such as which user and which specific commands can be executed. In addition, many distributions include a directive that automatically loads all additional configuration files located in /etc/sudoers.d/.

It is crucial to understand that /etc/sudoers You shouldn't edit "without the proper editing" with any text editor. It must always be modified using the command visudo, which opens the file with an editor (by default vi o nano(depending on the configuration), but it adds a layer of security: it checks the syntax before saving and prevents two people from editing it at the same time.

The typical use for editing sudoers is

> sudo visudo -f /etc/sudoers

You can also create specific files in /etc/sudoers.d/ to separate configurations by user groups, services, etc. For example, you can have a file /etc/sudoers.d/networking with specific rules for network administration, without mixing it with the rest of the general configuration.

When opening /etc/sudoers on a typical systemYou'll see lines like these (not counting comments):

  • root ALL=(ALL:ALL) ALL: the user root You can execute any command on any host, as any user and any group.
  • %admin ALL=(ALL) ALL: anyone within the group admin has full permissions to use sudo.
  • % sudo ALL = (ALL: ALL) ALLThe same applies to the group sudo, which in Ubuntu and derivatives is usually the key group.
  • #include /etc/sudoers.d: indicates that the files in that directory should also be read (even if a #(This is not a comment in this specific context).

In addition to user and group rules, sudoers It allows defining aliases to simplify complex configurations: user aliases (User_Alias), of commands (Cmnd_Alias), of execution groups (Runas_Alias) or of hosts (Host_Alias).

Manage users and groups with sudoers

A common practice on servers is controlling access to sudo through groups. For example, in many systems it is enough to add a user to the group sudo o wheel so that you can obtain full administrative permits.

To check which users belong to a group determined (for example, sudo), you can use:

> grep 'sudo' /etc/group

If you want to give sudo permissions to a userThe usual practice is to add it to the corresponding group. For example, to incorporate bill To the group sudo:

> sudo adduser bill sudo

When you need to revoke those privilegesSimply remove it from the group:

> sudo deluser bill sudo

Another, much finer possibility It involves granting permissions only for certain commands, without giving free rein. To do this, specific files are usually created in /etc/sudoers.d/For example, you could define a file /etc/sudoers.d/networking with something like:

Cmnd_Alias ​​CAPTURE = /usr/sbin/tcpdump
Cmnd_Alias ​​SERVERS = /usr/sbin/apache2ctl, /usr/bin/htpasswd
Cmnd_Alias ​​NETALL = CAPTURE, SERVERS
%netadmin ALL = NETALL

With this configuration, any user in the group netadmin you will be able to execute the commands defined under the alias NETALL (which groups the aliases) CAPTURE y SERVERSwithout having full access to everything sudoAll that's needed is to add to bill To the group netadmin so that you can use tcpdump and the defined server tools.

Common commands that require sudo

In the day-to-day administration of systemsThere are several types of tasks that almost always go hand in hand with sudobecause they involve modifying the system or accessing privileged information.

Package management: in distributions based on zypper, apt or other package managers, any operation that installs, removes, or updates software requires privileges. For example:

> sudo zypper install package
> sudo apt-get install docker-ce

However, queries that only read information, such as listing repositories, can usually be run without sudoIt's a matter of testing and seeing when the system itself returns a permissions error.

Service management with systemd It is usually done through systemctlActions such as starting, stopping, or restarting services typically require sudo:

> sudo systemctl restart apache2

In contrast, more innocuous commands such as checking the status of a service They can function without privileges on many systems:

> systemctl status NetworkManager

Managing user accounts also requires care. Commands like usermod, useradd o deluser They should almost always go with sudo, since they modify the system's user database:

> sudo usermod -L -f 30 tux

Finally, file permissions and ownership management with chown And company usually needs privileges when it affects system paths or other users. For example, to make all files and subdirectories of /home/test/tux-files become the property of the user tux You could use:

> sudo chown -R tux:tux /home/test/tux-files

Practical examples of using sudo

Let's look at some real cases. where sudo It makes the difference between a permissions error and a correct administrative operation.

Updating package indexes in Debian/Ubuntu Without privileges, it will give errors because it cannot manipulate files. /var/lib/apt/listsThe command:

> apt-get update

It will end in "Permission denied" messagesAs soon as you repeat it like that, things change:

> sudo apt-get update

The system will ask for your password.and if your user is authorized in sudoersThe update will run without problems. It's a recurring pattern: permissions error without sudocorrect execution with sudo.

Another very common example is copying files to system pathsas the /usr/local/binIf you try to copy a script there with a simple:

> cp script.sh /usr/local/bin/

It's normal for the terminal to complain that you don't have permission to write to that directory. If you repeat the operation by adding sudo:

> sudo cp script.sh /usr/local/bin/

You will be asked for your password and, after successfully authenticating,The copy will be made and recorded as executed with elevated privileges.

You can also combine sudo with the option -u to execute specific commands as another user, without changing sessions or using su. For example: uterine

> whoami
> sudo -u pedro whoami

The first order will display your real username., while the second will return “pedro”, demonstrating that the execution has been carried out as that target user.

Granting permissions without a password and other advanced options

One of the most powerful things about sweats This feature allows you to adjust the extent to which a password is requested and for which specific commands. Sometimes, you might want certain users to be able to execute specific commands without having to enter their password each time, for example, for automated scripts or shutdown buttons in a desktop environment.

This is achieved with the label NOPASSWD in the rules of sudoersFor example, if you want to miusuario can execute /bin/cat with sudo Without requiring a password, you could add a line:

myuser ALL = NOPASSWD: /bin/cat

Similarly, you could allow it to manage the shutdown of the equipment. without repeated authentication, adding something like:

myuser ALL = NOPASSWD: /sbin/shutdown, /sbin/halt, /sbin/reboot, /sbin/restart

For cleaner and more scalable configurationsIt's advisable to use aliases. A typical example is defining a user group, a command group, and, if necessary, an execution user alias:

User_Alias ​​GROUP = pepe, perico, andres
Cmnd_Alias ​​POWER = /sbin/shutdown, /sbin/halt, /sbin/reboot, /sbin/restart
Runas_Alias ​​WEB = www-data, apache

With these definitions you could then write Much more readable rules, such as:

ALL GROUP = POWER

Thus, any user included in the alias GRUPO You will be able to turn off or restart the computer with sudoand you can adjust whether you want to require a password or not using NOPASSWD o PASSWDYou can also restrict usage to specific hosts with Host_Alias so that it is only valid from a specific network.

Beyond NOPASSWDThere are other labels , the NOEXEC (to prevent a command from launching other programs with elevated permissions) or small curiosities like adding insults to the line Defaults, so that sudo I'll make a joke in English every time you fail to enter the password.

All of this demonstrates that sudoers is much more than a simple "root switch"When properly configured, it allows you to design a very granular permissions model, tailored to your needs and with a level of security far superior to the typical "enter as root and do whatever you want".

Having a tool like sudoproperly understood and properly configuredIt is almost mandatory on any modern Linux system where multiple users work or where you want to minimize risks, even if you are the only user. Taking advantage of the combination of sudo, /etc/sudoers, groups such as sudo o wheel and advanced tags such as NOPASSWDYou can achieve a very reasonable balance between comfort, fine control, and safety, without having to be constantly glued to a session. root nor rely solely on good luck.

root user in linux
Related article:
Root user in Linux: permissions, risks and best practices