Categories: TutorialsUbuntu

7 Most Useful Steps to Configure ‘sudo’ in Linux Terminal

Sudo is the default utility on Unix-Linux systems, which is known as SuperUserDo. The Linux system forbids normal users from executing administrative commands. However, we can use this mechanism to allow regular users to run any application or command as a root user or to grant specific  commands to specific users. In order to run / execute the sudo prefix command, only those users who have the information in the /etc / sudoers file (which is the main configuration file for sudo) will be allowed access.

WARNING: If someone tries to use the sudo prefix without privileges they will be notified that “‘this user’ is not in the sudoers file. This incident will be reported.”

Sponsored

The use of a root account is quite dangerous in the day-to-day course of action, since it has full privileges to perform any actions. The simplest mistake when you are running a command can easily destroy the whole system without any scope for recovery except for re-installation. As a result, it is better to avoid using root accounts, except in the very specific cases where they are explicitly required. Hence, it is always recommended to use a normal account with sudo privilege instead of root, since we know that sudo has some extra security checks, such as asking for the user’s password prior to executing any administrative commands.

In most Linux distributions, sudo privilege can be granted simply by adding a user to the sudo group. In Redhat, CentOS, and Fedora, the sudo group name is “wheel”, which is mostly enabled by default; if not, it can be edited the /etc/sudoers file using the ‘visudo’ command in the Terminal, or directly using vi or vim. Following are the three different entries in the sudoers file that give you the privilege to use sudo prefix.

## Allow root to run any commands anywhere
root             ALL=(ALL)                ALL

## It means all the users with the root privilege can execute all the commands like root

## Allows people in the group wheel to run all commands
%wheel             ALL=(ALL)              ALL

## It means all the users that belong to the wheel group can execute all the commands like root

## Allows people in the group wheel to run all commands
username             ALL=(ALL)           ALL

## It means only the given user can execute all the commands like root

Note: Now, we can use the following command to add a user to the “wheel” group.

# usermod -aG wheel username

In this article, we will see the steps to the sudoer configuration in Linux System. This will help all desktop users, developers, and system admins. The following steps are in this guide tested on RHEL and CentOS 7.8. You can use this guide for all the versions of RHEL, CentOS, Fedora, and mostly it will be identical for other distros also.

Prerequisites :

Operating System        :     CentOS 7
package                 :     sudo
User account            :     root user or another account with sudo privileges
Access Point            :     Terminal Access / Command Line Interface

By default, all Linux distros come with a pre-installed package of sudo. You can check whether the packages are available or not in the system by using the following commands from the given options:

Option -A:  Open your terminal and simply type ‘sudo’ without a quote and press enter.

# sudo
Output: If the sudo package is not installed in the system, then it will display the output as like below:

-bash: /usr/bin/sudo: No such file or directory

 If the package is available in the system, then it will display the result as below:

usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] [VAR=value] [-i|-s] []
usage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] file ...

Option -B: To check the package using yum or rpm utilities.

# yum list installed | grep sudo     OR      # rpm -qi   sudo
Output:

libsss_sudo.x86_64          1.16.4-37.el7            @anaconda
sudo.x86_64                 1.8.23-9.el7             @base

Note: In the above output, you can see the package sudo is discovered in the system. If not, it will display either a “blank message” or “package sudo is not installed” message. To install the packages, we can use the following ‘yum’ command. Yum is a very powerful utility in Linux to check many things related to package management.

# yum install sudo

Note: In the first example, I will show you the steps on how to create a new user with a sudo prefix in the fresh Linux installed system without modifying/use the sudoers file.


1. Find one of the following options to create a new user with sudo privilege

Option – A:

(i) Use the following command to create a new user in Linux

# useradd linux

# passwd linux                             (create a password)

(ii) Now we can add a new user (linux) to the wheel group

# usermod -aG wheel linux

OR

Option – B:

Instead of using the above steps (i and ii ), we can also use the following command in a single line to create a new sudo user. There are many methods to create a user in Linux.

# useradd -G wheel linux

(iii) Now, we can use the ‘id’ command to get the user and group information of the newly created user (linux)

# id linux
Output:

uid=1005(linux) gid=1005(linux) groups=1005(linux),10(wheel)

Note: In the above output, you can see the user (linux) is a member of the “wheel” group. The important thing is, the members of the wheel group can execute any commands similar to the root user.

(iv) We can now test the sudo prefix with the new user account. For that, we use ‘su’ command to switch user account from root to the standard user (linux) account OR open a different terminal and log in as a new user. I will use the 1st option here.

[root@centos ~]# su - linux                       ## To switch                             
[linux@centos ~]$                                 ## After switched

Note: After switching to a standard user (linux), we can test the ‘sudo’ prefix to execute a command. Here we are going to get a list of all the files and folders of the /root directory. The root account only has the authority to list all the files and directories in the root folder and not anyone else. In our case, the user (linux) is already a member of the wheel group. Hence, we are authorized to use the sudo prefix to execute the following command. To execute a command with sudo prefix you will be asked by the user to enter the password. Now you can use the following command (ls -la) to get the complete list of files and directories of a root account, including hidden files with the long listing format. I believe the (ls) command is one of the very first commands you have trained when you get into the shell or command prompt.

$ sudo ls -la /root/
[sudo] password for linux:     
Output:

total 48
dr-xr-x---. 5 root root 245 May 31 14:40 .
dr-xr-xr-x. 17 root root 224 May 22 09:01 ..
-rw-------. 1 root root 1865 May 22 09:03 anaconda-ks.cfg
-rw-------. 1 root root 2955 Jun 5 23:13 .bash_history
-rw-r--r--. 1 root root 18 Dec 29 2013 .bash_logout
-rw-r--r--. 1 root root 176 Dec 29 2013 .bash_profile
-rw-r--r--. 1 root root 176 Dec 29 2013 .bashrc
drwx------. 4 root root 31 May 22 09:06 .cache
drwx------. 4 root root 30 May 22 09:06 .config
-rw-r--r--. 1 root root 100 Dec 29 2013 .cshrc
drwx------. 3 root root 25 May 22 09:04 .dbus
-rw-r--r--. 1 root root 15264 Sep 18 2019 epel-release-latest-7.noarch.rpm
-rw-r--r--. 1 root root 1913 May 22 09:05 initial-setup-ks.cfg
-rw-r--r--. 1 root root 129 Dec 29 2013 .tcshrc

Note: Always make sure that you are added to the user in a relevant group and apply the correct user password to use the ‘sudo’ command.


2. How do you permit a particular user to run/execute only specific commands as sudo?

Note: In the above example, we have added the user to a sudo group, which granted full access to execute all the commands like root account. Here we are going to assign a particular user to run only specific commands with sudo prefix. It can be accomplished by using the sudo main configuration file ‘/etc/sudoers’.

In this example, we are granting permission to the user “mkk” to execute only a single command “systemctl restart network ” as sudo. For a better understanding, let’s execute the same above command, with and without the privilege of sudo.

(i) Without privilege:

Sponsored
$ sudo systemctl restart network
[sudo] password for mkk:
Output:

mkk is not in the sudoers file. This incident will be reported.

Note: As you can see in the above output, it says that the respective user has not added the sudoers file to use sudo prefix. Now add the following entry into /etc/sudoers by using the ‘visudo’ command.

(ii) With privilege:

# visudo

mkk ALL = /usr/bin/systemctl restart network

Note: save and close the file using ‘:wq’ and then execute the same command.

$ sudo systemctl restart network
[sudo] password for mkk:

Note: The above command was executed successfully without any error or warning. Adding multiple commands to a particular user can use a comma (,) between the commands as like below:

mkk ALL = /usr/bin/systemctl restart network,/usr/bin/systemctl status network

3. How to permit users to run/execute a command using sudo without a password check?

mkk ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart network,/usr/bin/systemctl status network

Note: Normally when you execute a sudo command for the first time, it will ask the user to enter his password to complete the execution. By default, the sudo password will be cached in the next 5 minutes. If any execution happens within the next 5 minutes, it won’t require the password, but after the cached period again you will need to enter the password. However, this can be overridden and disable the password authentication option by using NOPASSWD in the sudoers file.


4. How to modify the default sudo password prompt timeout?

Note: By default, the sudo timed out reading password will be cached in only five minutes. This can be changed by the “timestamp_timeout option” in sudoers files. In this example, we will set the timeout to 15 minutes. It will be applied globally, to all the users in sudo.

Defaults timestamp_timeout=15

Note: We can add the following entry to set the timestamp_timeout for a particular user. To always do a password check, set the value as 0 (zero).

Defaults:linux timestamp_timeout=15

5. How to run the command as another user with sudo prefix?

Note: Here we are going to assign a user to run the command of other users without sharing the password. To do, add the following entry in the /etc/sudoers file. In this example, the user “britto” will execute a particular command, as a user mkk by using “britto’s” password.

britto ALL = (mkk) /usr/bin/systemctl status network

save and close the file using ‘:wq’

$ sudo -u mkk systemctl status network
[sudo] password for britto:
Output:

● network.service - LSB: Bring up/down networking
Loaded: loaded (/etc/rc.d/init.d/network; bad; vendor preset: disabled)
Active: active (exited) since Sun 2020-06-07 11:22:58 IST; 11h ago
Docs: man:systemd-sysv-generator(8)
Process: 5844 ExecStop=/etc/rc.d/init.d/network stop (code=exited, status=0/SUCCESS)
Process: 6016 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=0/SUCCESS)
Tasks: 0

6. How to create a customised log file for sudo?

Note: Just all the following entries in the sudoers file to achieve this task

Defaults logfile="/var/log/sudo.log"

Note: Now you can use the following command to view all the logs related to sudo command. It will show the history of who does what.

# cat /var/log/sudo.log
Output:

Jun 7 23:54:45 : linux : TTY=pts/0 ; PWD=/home/linux ; USER=root ;
COMMAND=/bin/bash
Jun 7 23:55:08 : mkk : TTY=pts/1 ; PWD=/home/mkk ; USER=root ;
COMMAND=/bin/systemctl status network

How can we use sudo command in Linux

Global Syntax of sudo command in Linux:

sudo [options] [command]

Note: The sudo command also comes with many possible options, but on a regular course mostly it will be used without any option unless there is such a requirement. However, I have added the most used options.


7. How to verify if a user belongs to a sudoer or not?

# sudo -l -U britto
Output:

User britto is not allowed to run sudo on centos.

Note:

Here you can see that user britto is not allowed to run any sudo commands

# sudo -l -U mkk
Output:

Matching Defaults entries for mkk on centos:
!visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR
LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT
LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET
XAUTHORITY", secure_path=/sbin:/bin:/usr/sbin:/usr/bin

User mkk may run the following commands on centos:
(ALL) NOPASSWD: /usr/bin/systemctl restart network, /usr/bin/systemctl status network

Note: If you get an output like above, it means this user is permitted to use the sudo command, and also, you can see the name of the commands that the user can run with sudo prefix. If you have several entries in this list, then better use a long listing format like the below example.

# sudo -ll -U mkk
Output:

User mkk may run the following commands on centos:

Sudoers entry:
RunAsUsers: ALL
Options: !authenticate
Commands:
/usr/bin/systemctl restart network
/usr/bin/systemctl status network

Thank you so much for reading this article! I hope this article will help you to understand the ‘sudo’ command in Linux.

If you have any questions, feel free to leave a comment below and we will get back to you as soon as possible!.

If you like this article, kindly please share it and it may help others as well.

Thank you!

If our tutorials helped you, please consider buying us a coffee. We appreciate your support!

Thank you for your support.

The post 7 Most Useful Steps to Configure ‘sudo’ in Linux Terminal appeared first on Linux Tutorial Hub.

Ubuntu Server Admin

Recent Posts

Life at Canonical: Victoria Antipova’s perspective as a new joiner in Product Marketing

Canonical is continuously hiring new talent. Being a remote- first company, Canonical’s new joiners receive…

23 hours ago

What is patching automation?

What is patching automation? With increasing numbers of vulnerabilities, there is a growing risk of…

2 days ago

A beginner’s tutorial for your first Machine Learning project using Charmed Kubeflow

Wouldn’t it be wonderful to wake up one day with a desire to explore AI…

3 days ago

Ubuntu brings comprehensive support to Azure Cobalt 100 VMs

Ubuntu and Ubuntu Pro supports Microsoft’s Azure Cobalt 100 Virtual Machines (VMs), powered by their…

3 days ago

Ubuntu Weekly Newsletter Issue 870

Welcome to the Ubuntu Weekly Newsletter, Issue 870 for the week of December 8 –…

4 days ago

Get Valkey security patching and support with Ubuntu Pro

Canonical is pleased to announce security patching and support for Valkey through the Ubuntu Pro…

4 days ago