Securing Administrative User Accounts
local graph
Chapter 2 — Securing Administrative User Accounts
Section titled “Chapter 2 — Securing Administrative User Accounts”Managing users is one of the more challenging aspects of IT administration. You need to make sure that users can always access their stuff and that they can perform the required tasks to do their jobs. You also need to ensure that users’ stuff is always secure from unauthorized users and that users can’t perform any tasks that don’t fit their job description. It’s a tall order, but we aim to show that it’s doable. In this chapter, we’ll look at how to lock down user accounts and user credentials to protect them from attackers and snoopers. We’ll also look at how to prevent users from having any more privileges than they have to have in order to perform their jobs.
The specific topics covered in this chapter are as follows:
- The dangers of logging in as the root user
- The advantages of using
sudo - Setting up
sudoprivileges for full administrative users and for users with only certain delegated privileges - Advanced tips and tricks to use
sudo
The dangers of logging in as the root user
Section titled “The dangers of logging in as the root user”A huge advantage that Unix and Linux operating systems have over Windows is that Unix and Linux do a much better job of keeping privileged administrative accounts separated from normal user accounts. Indeed, one reason that older versions of Windows were so susceptible to security issues, such as drive-by virus infections, was the common practice of setting up user accounts with administrative privileges, without having the protection of the User Access Control (UAC) that’s in newer versions of Windows. (Even with UAC, Windows systems still do get infected, just not quite as often.) With Unix and Linux, it’s a lot harder to infect a properly configured system.
You probably already know that the all-powerful administrator account on a Unix or Linux system is the root account. If you’re logged in as the root user, you can do anything you want to do to that system. So you may think, “Yeah, that’s handy, so that’s what I’ll do.” However, always logging in as the root user can present a whole load of security problems. Logging in as the root user can do the following:
- Make it easier for you to accidentally perform an action that causes damage to the system
- Make it easier for someone else to perform an action that causes damage to the system
So if you always log on as the root user, or even if you just make the root user account readily accessible, you could say that you’re doing a big part of attackers’ and intruders’ work for them. Also, imagine if you were the head Linux administrator at a large corporation, and the only way to allow users to perform admin tasks was to give them all the root password. What would happen if one of those users were to leave the company? You wouldn’t want that person to still have the ability to log in to the systems, so you’d have to change the password and distribute the new one to all of the other users. And what if you just want users to have admin privileges only for certain tasks, instead of having full root privileges?
What we need is a mechanism that allows users to perform administrative tasks without incurring the risk of having them always log on as the root user, and that would also allow users to have only the admin privileges they really need to perform a certain job. In Linux and Unix, we have that mechanism in the form of the sudo utility.
The advantages of using sudo
Section titled “The advantages of using sudo”Used properly, the sudo utility can greatly enhance the security of your systems, and it can make an administrator’s job much easier. With sudo, you can do the following:
- Assign certain users full administrative privileges, while assigning other users only the privileges they need to perform tasks that are directly related to their respective jobs.
- Allow users to perform administrative tasks by entering their own normal user passwords so that you don’t have to distribute the root password to everybody and their brother.
- Make it harder for intruders to break into your systems. If you implement
sudoand disable the root user account, would-be intruders won’t know which account to attack because they won’t know which one has admin privileges. - Create
sudopolicies that you can deploy across an entire enterprise network, even if that network has a mix of Unix, BSD, and Linux machines. - Improve your auditing capabilities because you’ll be able to see what users are doing with their admin privileges.
With regard to that last bullet point, consider the following snippet from the secure log of my CentOS 7 virtual machine:
Sep 29 20:44:33 localhost sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ;USER=root ; COMMAND=/bin/su –Sep 29 20:44:34 localhost su: pam_unix(su-l:session): session opened foruser root by donnie(uid=0)Sep 29 20:50:39 localhost su: pam_unix(su-l:session): session closed foruser rootYou can see that I used su - to log in to the root command prompt and that I then logged back out. While I was logged in, I did several things that require root privileges, but none of that got recorded. What did get recorded though is something that I did with sudo. That is, because the root account is disabled on this machine, I used my sudo privilege to get su - to work for me. Let’s look at another snippet to show a bit more detail about how this works:
Sep 29 20:50:45 localhost sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ;USER=root ; COMMAND=/bin/less /var/log/secureSep 29 20:55:30 localhost sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ;USER=root ; COMMAND=/sbin/fdisk -lSep 29 20:55:40 localhost sudo: donnie : TTY=pts/0 ; PWD=/home/donnie ;USER=root ; COMMAND=/bin/yum upgradeSep 29 20:59:35 localhost sudo: donnie : TTY=tty1 ; PWD=/home/donnie ;USER=root ; COMMAND=/bin/systemctl status sshdSep 29 21:01:11 localhost sudo: donnie : TTY=tty1 ; PWD=/home/donnie ;USER=root ; COMMAND=/bin/less /var/log/secureThis time, I used my sudo privilege to open a log file, to view my hard drive configuration, to perform a system update, to check the status of the Secure Shell daemon, and to once again view a log file. So, if you were the security administrator at my company, you’d be able to see whether or not I’m abusing my sudo power.
Now, you’re asking, “What’s to prevent a person from just doing a sudo su - to prevent his or her misdeeds from being detected?” That’s easy. Just don’t give people the power to go to the root command prompt.
Setting up sudo privileges for full administrative users
Section titled “Setting up sudo privileges for full administrative users”Before we look at how to limit what users can do, let’s first look at how to allow a user to do everything, including logging in to the root command prompt. There are a couple of methods for doing that.
Adding users to a predefined admin group
Section titled “Adding users to a predefined admin group”The first method, which is the simplest, is to add users to a predefined administrators group and then, if it hasn’t already been done, to configure the sudo policy to allow that group to do its job. It’s simple enough to do except that different Linux distro families use different admin groups.
On Unix, BSD, and most Linux systems, you would add users to the wheel group. (Members of the Red Hat family, including CentOS and AlmaLinux, fall into this category.) When I do the groups command on any of my RHEL-type machines, I get this:
[donnie@localhost ~]$ groupsdonnie wheel[donnie@localhost ~]$This shows that I’m a member of the wheel group. By doing sudo visudo, I’ll open the sudo policy file. Scrolling down, we’ll see the line that gives the wheel group its awesome power:
## Allows people in group wheel to run all commands%wheel ALL=(ALL) ALLThe percent sign indicates that we’re working with a group. The three appearances of ALL mean that members of that group can perform ALL commands, as ALL users, on ALL machines in the network on which this policy is deployed. The only slight catch is that group members will be prompted to enter their own normal user account passwords in order to perform a sudo task. Scroll down a bit more and you’ll see this:
## Same thing without a password# %wheel ALL=(ALL) NOPASSWD: ALLIf we were to comment out the %wheel line in the former snippet and remove the comment symbol from in front of the %wheel line in this snippet, then members of the wheel group would be able to perform all of their sudo tasks without ever having to enter any password. That’s something that I really don’t recommend, even for home use. In a business setting, allowing people to have password-less sudo privileges is a definite no-no.
To add an existing user to the wheel group, use usermod with the -G option. You might also want to use the -a option, in order to prevent removing the user from other groups to which he or she belongs. For our example, let’s add Maggie:
sudo usermod -a -G wheel maggieYou can also add a user account to the wheel group as you create it. Let’s do that now for Frank:
sudo useradd -G wheel frankTip
Note that, with my usage of useradd, I’m assuming that we’re working with a member of the Red Hat family, which comes with predefined default settings to create user accounts. For non-Red Hat-type distros that use the wheel group, you’d need to either reconfigure the default settings or use extra option switches in order to create the user’s home directory and to assign the correct shell. Your command would then look something like this:
sudo useradd -G wheel -m -d /home/frank -s /bin/bash frankFor members of the Debian family, including Ubuntu, the procedure is the same, except that you would use the sudo group instead of the wheel group. (This kind of figures, considering that the Debian folk have pretty much always marched to the beat of a different drum.)
Tip
One way in which this technique would come in handy is whenever you need to create a virtual private server on a cloud service, such as Rackspace, DigitalOcean, or Vultr. When you log in to one of those services and initially create your virtual machine, the cloud service will have you log in to that virtual machine as the root user. (This even happens with Ubuntu, even though the root user account is disabled whenever you do a local installation of Ubuntu.)
The first thing that you’ll want to do in this scenario is to create a normal user account for yourself and give it full sudo privileges. Then, log out of the root account and log back in with your normal user account. You’ll then want to disable the root account with this command:
sudo passwd -l rootYou’ll also want to do some additional configuration to lock down Secure Shell access, but we’ll cover that in Chapter 7, SSH Hardening.
Creating an entry in the sudo policy file
Section titled “Creating an entry in the sudo policy file”Okay, adding users to either the wheel group or the sudo group works great if you’re either just working with a single machine or if you’re deploying a sudo policy across a network that uses just one of these two admin groups. But what if you want to deploy a sudo policy across a network with a mixed group of both Red Hat and Ubuntu machines? Or what if you don’t want to go around to each machine to add users to an admin group? Then, just create an entry in the sudo policy file. You can either create an entry for an individual user or create a user alias. If you do sudo visudo on either your CentOS or one of your AlmaLinux virtual machines, you’ll see a commented-out example of a user alias:
# User_Alias ADMINS = jsmith, mikemYou can uncomment this line and add your own set of usernames, or you can just add a line with your own user alias. To give members of the user alias full sudo power, add another line that would look like this:
ADMINS ALL=(ALL) ALLIt’s also possible to add a visudo entry for just a single user, and you might need to do that under very special circumstances. Here’s an example:
frank ALL=(ALL) ALLBut for ease of management, it’s best to go with either a user group or a user alias.
Tip
The sudo policy file is the /etc/sudoers file. I always hesitate to tell students that because, every once in a while, I have a student try to edit it in a regular text editor. That doesn’t work though, so please don’t try it. Always edit sudoers with the sudo visudo command.
Setting up sudo for users with only certain delegated privileges
Section titled “Setting up sudo for users with only certain delegated privileges”A basic tenet of IT security philosophy is to give network users enough privileges so that they can get their jobs done, but no privileges beyond that. So, you’ll want as few people as possible to have full sudo privileges. (If you have the root user account enabled, you’ll want even fewer people to know the root password.) You’ll also want a way to delegate privileges to people according to what their specific jobs are. Backup admins will need to be able to perform backup tasks, help desk personnel will need to perform user management tasks, and so on. With sudo, you can delegate these privileges and disallow users from doing any other administrative jobs that don’t fit their job description.
The best way to explain this is to have you open visudo on any of the RHEL-type virtual machines. CentOS 7, AlmaLinux 8, and AlmaLinux 9 all work well for this. So, go ahead and start up one of them and enter:
sudo visudoUnlike Ubuntu, the RHEL-type distros have a fully commented and well-documented sudoers file. I’ve already shown you the line that creates the ADMIN user alias, and you can create other user aliases for other purposes. You can, for example, create a BACKUPADMINS user alias for backup administrators, a WEBADMINS user alias for web server administrators, or whatever else you desire. So, you could add a line that looks something like this:
User_Alias SOFTWAREADMINS = vicky, cleopatraThat’s good, except that Vicky and Cleopatra still can’t do anything. You’ll need to assign some duties to the user alias.
If you look at the example user alias mentioned later, you’ll see a list of example command aliases. One of these examples just happens to be SOFTWARE, which contains the commands that an admin would need in order to either install or remove software or to update the system. It’s commented out, as are all of the other example command aliases, so you’ll need to remove the hash symbol from the beginning of the line before you can use it:
Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yumNow, it’s just a simple matter of assigning the SOFTWARE command alias to the SOFTWAREADMINS user alias:
SOFTWAREADMINS ALL=(ALL) SOFTWAREVicky and Cleopatra, both members of the SOFTWAREADMINS user alias, can now run the rpm, up2date, and yum commands with root privileges, on all servers on which this policy is installed.
All but one of these predefined command aliases are ready to use after you uncomment them and assign them to either a user, group, or user alias. The one exception is the SERVICES command alias:
Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctl start, /usr/bin/systemctl stop, /usr/bin/systemctl reload, /usr/bin/systemctl restart, /usr/bin/systemctl status, /usr/bin/systemctl enable, /usr/bin/systemctl disableThe problem with this SERVICES alias is that it also lists the different subcommands for the systemctl command. The way sudo works is that if a command is listed by itself, then the assigned user can use that command with any subcommands, options, or arguments. So, in the SOFTWARE example, members of the SOFTWARE user alias can run a command such as this:
sudo yum upgradeBut when a command is listed in the command alias with a subcommand, option, or argument, that’s all anyone who’s assigned to the command alias can run. With the SERVICES command alias in its current configuration, the systemctl commands just won’t work. To see why, let’s set Charlie and Lionel up in the SERVICESADMINS user alias and then uncomment the SERVICES command alias, as we did earlier:
User_Alias SERVICESADMINS = charlie, lionelSERVICESADMINS ALL=(ALL) SERVICESNow, watch what happens when Lionel tries to check the status of the Secure Shell service:
[lionel@centos-7 ~]$ sudo systemctl status sshd [sudo] password for lionel: Sorry, user lionel is not allowed to execute '/bin/systemctl status sshd' as root on centos-7.xyzwidgets.com. [lionel@centos-7 ~]$Okay, so Lionel can run sudo systemctl status, which is pretty much useless, but he can’t do anything meaningful, such as specifying the service that he wants to check. That’s a bit of a problem. There are two ways to fix this, but there’s only one way that you want to use. You could just eliminate all of the systemctl subcommands and make the SERVICES alias look like this:
Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctlBut if you do that, Lionel and Charlie will also be able to shut down or reboot the system, edit the services files, or change the machine from one systemd target to another. That’s probably not what you want. Because the systemctl command covers a lot of different functions, you have to be careful not to allow delegated users to access too many of those functions. A better solution would be to add a wildcard to each of the systemctl subcommands:
Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig, /usr/bin/systemctl start *, /usr/bin/systemctl stop *, /usr/bin/systemctl reload *, /usr/bin/systemctl restart *, /usr/bin/systemctl status *, /usr/bin/systemctl enable *, /usr/bin/systemctl disable *Now, Lionel and Charlie can perform any of the systemctl functions that are listed in this command alias, for any service:
[lionel@centos-7 ~]$ sudo systemctl status sshd[sudo] password for lionel:● sshd.service - OpenSSH server daemon Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-09-30 18:11:22 EDT; 23min ago Docs: man:sshd(8) man:sshd_config(5) Main PID: 13567 (sshd) CGroup: /system.slice/sshd.service └─13567 /usr/sbin/sshd -DSep 30 18:11:22 centos-7.xyzwidgets.com systemd[1]: Starting OpenSSH server daemon...Sep 30 18:11:22 centos-7.xyzwidgets.com sshd[13567]: Server listening on 0.0.0.0 port 22.Sep 30 18:11:22 centos-7.xyzwidgets.com sshd[13567]: Server listening on :: port 22.Sep 30 18:11:22 centos-7.xyzwidgets.com systemd[1]: Started OpenSSH server daemon.[lionel@centos-7 ~]$Keep in mind that you’re not limited to using user aliases and command aliases. You can also assign privileges to either a Linux group or an individual user. You can also assign individual commands to a user alias, Linux group, or individual user. Here’s an example:
katelyn ALL=(ALL) STORAGEgunther ALL=(ALL) /sbin/fdisk -l%backup_admins ALL=(ALL) BACKUPKatelyn can now do all of the commands in the STORAGE command alias, whereas Gunther can only use fdisk to look at the partition tables. The members of the backup_admins Linux group can do commands in the BACKUP command alias.
The last thing we’ll look at in this topic is the host aliases examples that you see preceding the user alias example:
# Host_Alias FILESERVERS = fs1, fs2# Host_Alias MAILSERVERS = smtp, smtp2Each host alias consists of a list of server hostnames. This is what allows you to create one sudoers file on one machine and deploy it across the network. For example, you could create a WEBSERVERS host alias, a WEBADMINS user alias, and a WEBCOMMANDS command alias with the appropriate commands. Your configuration would look something like this:
Host_Alias WEBSERVERS = webserver1, webserver2User_Alias WEBADMINS = junior, kaylaCmnd_Alias WEBCOMMANDS = /usr/bin/systemctl status httpd, /usr/bin/systemctl start httpd, /usr/bin/systemctl stop httpd, /usr/bin/systemctl restart httpdWEBADMINS WEBSERVERS=(ALL) WEBCOMMANDSNow, when a user types a command into a server on the network, sudo will first look at the hostname of that server. If the user is authorized to perform that command on that server, then sudo allows it. Otherwise, sudo denies it. In a small to medium-sized business, it would probably work just fine to manually copy the master sudoers file to all the servers on the network. But in a large enterprise, you’ll want to streamline and automate the process. For this, you could use something like Puppet, Chef, or Ansible. (These three technologies are beyond the scope of this book, but you’ll find plenty of books and video courses about all three of them.)
All of these techniques will work on your Ubuntu VM as well as on the CentOS VM. The only catch is that Ubuntu doesn’t come with any predefined command aliases, so you’ll have to type them in yourself.
Anyway, I know that you’re tired of reading, so let’s do some work.
Hands-on lab for assigning limited sudo privileges
Section titled “Hands-on lab for assigning limited sudo privileges”In this lab, you’ll create some users and assign them different levels of privileges. To simplify things, let’s use the AlmaLinux 9 virtual machine:
- Log in to the AlmaLinux virtual machine and create user accounts for Lionel, Katelyn, and Maggie:
sudo useradd lionelsudo useradd katelynsudo useradd Maggiesudo passwd lionelsudo passwd katelynsudo passwd Maggie
- Open
visudo:sudo visudo
Find the STORAGE command alias and remove the comment symbol from in front of it.
- Add the following lines to the end of the file, using tabs to separate the columns:
lionel ALL=(ALL) ALLkatelyn ALL=(ALL) /usr/bin/systemctl status sshdmaggie ALL=(ALL) STORAGE
Save the file and exit visudo.
- To save time, we’ll use
suto log in to the different user accounts. That way, you won’t need to log out of your own account to perform these steps. First, log in to Lionel’s account and verify that he has fullsudoprivileges by running several root-level commands:su – lionelsudo su –exitsudo systemctl status sshdsudo fdisk -lexit - This time, log in as Katelyn and try to run some root-level commands. Don’t be too disappointed if they don’t all work, though:
su – katelynsudo su –sudo systemctl status sshdsudo systemctl restart sshdsudo fdisk -lexit
- Finally, log in as Maggie, and run the same set of commands that you ran for Katelyn.
- Keep in mind that, although we only had three individual users for this lab, you could just as easily have handled more users by setting them up in user aliases or Linux groups.
Since sudo is such a great security tool, you would think that everyone would use it, right? Sadly, that’s not the case. Pretty much any time you look at either a Linux tutorial website or a Linux tutorial YouTube channel, you’ll see the person who’s doing the demo logged in at the root user command prompt. In some cases, I’ve seen the person remotely logged in as the root user on a cloud-based virtual machine. Now, if logging in as the root user is already a bad idea, then logging in across the Internet as the root user is an even worse idea. In any case, seeing everybody do these tutorial demos from the root user’s shell drives me absolutely crazy.
Having said all this, there are some things that don’t work with sudo. Bash shell internal commands such as cd don’t work with it, and using echo to inject kernel values into the /proc filesystem also doesn’t work with it. For tasks such as these, a person would have to go to the root command prompt. Still, though, make sure that only users who absolutely have to use the root user command prompt have access to it.
Next, let’s look at some more advanced sudo usage.
Advanced tips and tricks for using sudo
Section titled “Advanced tips and tricks for using sudo”Now that we’ve looked at the basics of setting up a good sudo configuration, we’re confronted with a bit of a paradox. That is, even though sudo is a security tool, certain things that you can do with it can make your system even more insecure than it was. Let’s see how to avoid that.
The sudo timer
Section titled “The sudo timer”By default, the sudo timer is set for 5 minutes. This means that once a user performs one sudo command and enters a password, he or she can perform another sudo command within 5 minutes without having to enter the password again. Although this is obviously handy, it can also be problematic if users were to walk away from their desks with a command terminal still open.
If the 5-minute timer hasn’t yet expired, someone else could come along and perform some root-level task. If your security needs require it, you can easily disable this timer by adding a line to the Defaults section of the sudoers file. This way, users will have to enter their passwords every time they run a sudo command. You can make this a global setting for all users, or you can just set it for certain individual users.
Let’s also say that you’re sitting in your nice, cozy cubicle, logged in to a remote Linux server that still has the 5-minute timer enabled. If you need to leave your desk for a moment, your best action would be to log out of the server first. Short of that, you could just reset the sudo timer by running this command:
sudo -kThis is one of the few sudo actions you can do without entering a password. But the next time you do a sudo command, you will have to enter your password, even if it has been less than 5 minutes since you entered your password previously.
View your sudo privileges
Section titled “View your sudo privileges”Are you unsure of what sudo privileges you possess? Not to worry, you have a way to find out. Just run this command:
sudo -lWhen I do this for myself, I first see some of the environmental variables for my account, and then I see that I have full sudo privileges:
donnie@packtpub1:~$ sudo -l [sudo] password for donnie: Matching Defaults entries for donnie on packtpub1: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User donnie may run the following commands on packtpub1: (ALL : ALL) ALL donnie@packtpub1:~$When Frank, my formerly feral flamepoint Siamese cat, does this for his account, he sees that he can only do the fdisk -l command:
frank@packtpub1:~$ sudo -l [sudo] password for frank: Matching Defaults entries for frank on packtpub1: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User frank may run the following commands on packtpub1: (ALL) /sbin fdisk -l frank@packtpub1:~$But since he’s a cat, he doesn’t complain. Instead, he’ll just try to do something sneaky, as we’ll see in just a bit.
Hands-on lab for disabling the sudo timer
Section titled “Hands-on lab for disabling the sudo timer”For this lab, you’ll disable the sudo timer on your AlmaLinux VM:
- Log in to the same AlmaLinux virtual machine that you used for the previous lab. We’ll be using the user accounts that you’ve already created.
- At your own user account command prompt, enter the following commands:
sudo fdisk -lsudo systemctl status sshdsudo iptables -L
You’ll see that you only needed to enter the password once to do all three commands
- At your own user account command prompt, run the following:
sudo fdisk -lsudo -ksudo fdisk -l
Note how the sudo -k command resets your timer, so you’ll have to enter your password again. Open visudo with the following command:
sudo visudoIn the Defaults specification section of the file, add the following line:
Defaults timestamp_timeout = 0Save the file and exit visudo.
- Perform the commands that you performed in step 2. This time, you should see that you have to enter a password every time.
- Open
visudoand modify the line that you added so that it looks like this:Defaults:lionel timestamp_timeout = 0
Save the file and exit visudo.
- From your own account shell, repeat the commands that you performed in step 2. Then, log in as Lionel and perform the commands again.
- View your own
sudoprivileges by running the following:sudo -l
Note that this procedure also works for Ubuntu.
Preventing users from having root shell access
Section titled “Preventing users from having root shell access”Let’s say that you want to set up a user with limited sudo privileges, and you decide to do so by adding a line like this:
maggie ALL=(ALL) /bin/bash, /bin/zshI’m sorry to say that you haven’t limited Maggie’s access at all. You have effectively given her full sudo privileges with both the Bash shell and the ZSH shell. So, don’t add lines like this to your sudoers because it will get you into trouble.
Preventing users from using shell escapes
Section titled “Preventing users from using shell escapes”Certain programs, especially text editors and pagers, have a handy shell escape feature. This allows a user to run a shell command without having to exit the program first. For example, from the command mode of the Vi and Vim editors, someone could run the ls command by running :!ls. Executing the command would look like this:
# useradd defaults fileGROUP=100HOME=/homeINACTIVE=-1EXPIRE=SHELL=/bin/bashSKEL=/etc/skelCREATE_MAIL_SPOOL=yes~~:!lsThe output would look like this:
[donnie@localhost default]$ sudo vim useradd [sudo] password for donnie: grub nss useradd Press ENTER or type command to continue grub nss useradd Press ENTER or type command to continueThat was a harmless command, as you can see. But, the user could just as easily have executed a command that requires root privileges, or even have used the :shell command to go to the root user’s shell.
Now, imagine that you want Frank to be able to edit the sshd_config file and only that file. You might be tempted to add a line to your sudo configuration that would look like this:
frank ALL=(ALL) /bin/vim /etc/ssh/sshd_configThis looks like it would work, right? Well, it doesn’t, because once Frank has opened the sshd_config file with his sudo privilege, he can then use Vim’s shell escape feature to perform other root-level commands, which includes being able to edit other configuration files, create new users, manipulate system services, or install malware. Let’s see how this works.
Here, we see that Frank has used his sudo power to open the sshd_config file in the Vim editor. At the bottom of the screen, he’ll type the :shell command:
. . .. . .# Authentication:#LoginGraceTime 2m:shellNow, watch what happens when Frank hits the Enter key:
[frank@localhost ~]$ sudo vim /etc/ssh/sshd_config[sudo] password for frank:[root@localhost frank]#Yikes! That is not good. By assigning Frank the sudo power to edit a single system configuration file, we’ve effectively given Frank full root privileges on the system.
You can fix this problem by having Frank use sudoedit instead of vim. Let’s change the sudoers rule to reflect that:
frank ALL=(ALL) sudoedit /etc/ssh/sshd_configsudoedit doesn’t allow users to escape to a shell with root privileges, so you can safely allow Frank to use it. With this new configuration, Frank can no longer open the sshd_config file in Vim:
[frank@localhost ~]$ sudo vim /etc/ssh/sshd_config[sudo] password for frank:Sorry, user frank is not allowed to execute '/bin/vim /etc/ssh/sshd_config' as root on localhost.localdomain.[frank@localhost ~]$However, he can open it with sudoedit:
[frank@localhost ~]$ sudoedit /etc/ssh/sshd_config[sudo] password for frank:sudoedit: /etc/ssh/sshd_config unchanged[frank@localhost ~]$We see that Frank decided not to actually make any edits, but that’s okay. Let’s have him open the file again, and try to escape to a root shell. First, he’ll type in the :shell command, as he did before:
. . .. . .# Authentication:#LoginGraceTime 2m:shellWatch what happens this time when he hits the Enter key:
[frank@localhost ~]$ sudoedit /etc/ssh/sshd_config[frank@localhost ~]$He can still escape to a shell, but it’s his own non-privileged shell instead of the root user’s shell.
Other programs that have a shell escape feature include the following:
emacslessviewmore
So, how do we deal with these? That’s easy. We’ll use the NOEXEC: option when we set up our sudoers rules. For example, let’s say that we want to grant Vicky the power to view files that are only readable by the root user. We could set up a rule that looks like this:
vicky ALL=(ALL) /usr/bin/lessShe now decides to view the system log file:
[vicky@localhost ~]$ cd /var/log[vicky@localhost log]$ sudo less messagesTo open a shell from within less, Vicky will type !bash instead of :shell:
. . .. . .Jan 15 13:02:23 localhost NetworkManager[902]: <info> [1673805743.2807] settings: Loaded settings plugin: keyfile (internal)Jan 15 13:02:23 localhost systemd[1]: Starting Network Manager Script Dispatcher Service...Jan 15 13:02:23 localhost NetworkManager[902]: <info> [1673805743.3039] settings: Loaded settings plugin: ifcfg-rh ("/usr/lib64/NetworkManager/1.40.0-1.el9/libnm-settings-plugin-ifcfg-rh.so!bashOnce again, watch what happens when she hits the Enter key:
. . .. . .!done (press RETURN)[root@localhost log]#Obviously, that’s not what we want to happen. Let’s fix that by adding the NOEXEC: option to the sudoers rule:
vicky ALL=(ALL) NOEXEC: /usr/bin/lessThis prevents Vicky from escaping to even her own shell:
. . .. . .!done (press RETURN)That looks much better, and we have achieved coolness.
Preventing users from using other dangerous programs
Section titled “Preventing users from using other dangerous programs”Some programs that don’t have shell escapes can still be dangerous if you give users unrestricted privileges to use them. These include the following:
catcutawksed
If you must give someone sudo privileges to use one of these programs, it’s best to limit their use to only specific files. And that brings us to our next tip.
Limiting the user’s actions with commands
Section titled “Limiting the user’s actions with commands”Let’s say that you create a sudo rule so that Sylvester can use the systemctl command:
sylvester ALL=(ALL) /usr/bin/systemctlThis allows Sylvester to have full use of the systemctl features. He can control daemons, edit service files, shut down or reboot, and carry out every other function that systemctl does. That’s probably not what you want. It would be better to specify what systemctl functions Sylvester is allowed to do. Let’s say that you want him to be able to control just the Secure Shell service. You can make the line look like this:
sylvester ALL=(ALL) /usr/bin/systemctl * sshdSylvester can now do everything he needs to do with the Secure Shell service, but he can’t shut down or reboot the system, edit other service files, or change systemd targets. But what if you want Sylvester to do only certain specific actions with the Secure Shell service? Then you’ll have to omit the wildcard and specify all of the actions that you want Sylvester to do:
sylvester ALL=(ALL) /usr/bin/systemctl status sshd, /usr/bin/systemctl restart sshdNow, Sylvester can only restart the Secure Shell service or check its status.
Tip
When writing sudo policies, you’ll want to be aware of the differences between the different Linux and Unix distributions on your network. For example, on Red Hat-type systems, the systemctl binary file is located in the /usr/bin directory. On Debian/Ubuntu systems, it’s located in the /bin directory. If you have to roll out a sudoers file to a large enterprise network with mixed operating systems, you can use host aliases to ensure that servers will only allow the execution of commands that are appropriate for their operating systems.
Also, be aware that some system services have different names on different Linux distributions. On Red Hat-type systems, the Secure Shell service is sshd. On Debian/Ubuntu systems, it’s just plain ssh.
Letting users run as other users
Section titled “Letting users run as other users”In the following line, (ALL) means that Sylvester can run the systemctl commands as any user:
sylvester ALL=(ALL) /usr/bin/systemctl status sshd, /usr/bin/systemctl restart sshdThis effectively gives Sylvester root privileges for these commands because the root user is definitely any user. You could, if desired, change that (ALL) to (root) in order to specify that Sylvester can only run these commands as the root user:
sylvester ALL=(root) /usr/bin/systemctl status sshd, /usr/bin/systemctl restart sshdOkay, there’s probably not much point in that because nothing changes. Sylvester had root privileges for these systemctl commands before, and he still has them now. But there are more practical uses for this feature. Let’s say that Vicky is a database admin, and you want her to run as the database user:
vicky ALL=(database) /usr/local/sbin/some_database_script.shVicky could then run the command as the database user by entering the following command:
sudo -u database some_database_script.shThis is one of those features that you might not use that often, but keep it in mind anyway. You never know when it might come in handy.
Preventing abuse via a user’s shell scripts
Section titled “Preventing abuse via a user’s shell scripts”So, what if a user has written a shell script that requires sudo privileges? To answer that, let’s have Frank create the frank_script.sh shell script that looks like this:
#!/bin/bashecho "This script belongs to Frank the Cat."Okay, he wouldn’t need sudo privileges for that, but let’s pretend that he does. After he sets the executable permission and runs it with sudo, the output will look like this:
frank@packtpub1:~$ sudo ./frank_script.sh[sudo] password for frank:Sorry, user frank is not allowed to execute './frank_script.sh' as root on packtpub1.tds.frank@packtpub1:~$Naturally frustrated, Frank requested that I create a sudo rule so that he can run the script. So, I open visudo and add this rule for Frank:
frank ALL=(ALL) /home/frank/frank_script.shNow, when Frank runs the script with sudo, it works:
frank@packtpub1:~$ sudo ./frank_script.sh[sudo] password for frank:This script belongs to Frank the Cat.frank@packtpub1:~$But since this file is in Frank’s own home directory and he is its owner, he can edit it any way he wants. So, being the sneaky type, he adds the sudo -i line to the end of the script so that it now looks like this:
#!/bin/bash
echo "This script belongs to Frank the Cat."sudo -iBe prepared for a shock as you watch what happens next:
frank@packtpub1:~$ sudo ./frank_script.shThis script belongs to Frank the Cat.root@packtpub1:~#As you can see, Frank is now logged in as the root user.
What sudo -i does is to log a person in to the root user’s shell, the same way that sudo su - does. If Frank were to do sudo -i from his own command prompt, it would fail because he doesn’t have the privilege to do that. But he does have the sudo privilege to run his own shell script. By leaving the shell script in his own home directory, Frank can put root-level commands into it. By running the script with sudo, the root-level commands in the script will execute with root-level privileges.
To remedy this, I’ll use my awesome powers of sudo to move Frank’s script to the /usr/local/sbin/ directory and change the ownership to the root user so that Frank won’t be able to edit it. And of course, before I do that, I’ll make sure to delete that sudo -i line from it:
donnie@packtpub1:~$ sudo -iroot@packtpub1:~# cd /home/frankroot@packtpub1:/home/frank# mv frank_script.sh /usr/local/sbinroot@packtpub1:/home/frank# chown root: /usr/local/sbin/frank_script.shroot@packtpub1:/home/frank# exitlogoutdonnie@packtpub1:~$Finally, I’ll open visudo and change his rule to reflect the new location of the script. The new rule looks like this:
frank ALL=(ALL) /usr/local/sbin/frank_script.shFrank can still run the script, but he can’t edit it:
frank@packtpub1:~$ sudo frank_script.shThis script belongs to Frank the Cat.frank@packtpub1:~$Detecting and deleting default user accounts
Section titled “Detecting and deleting default user accounts”One challenge of dealing with Internet of Things (IoT) devices is that you don’t do a normal operating system installation on them as you would when setting up a normal server. Instead, you download an image that has the operating system pre-installed and burn that image to a microSD card. The installed operating system is set up with a default user account, and many times, that user is set up with full sudo privileges and isn’t required to enter a sudo password. Let’s take, for example, the RaspEX Linux distribution for the Raspberry Pi. (RaspEX is built from Ubuntu source code.) On the documentation page of the RaspEX download site, we see that the default user is raspex, and the default password for that user is also raspex. We also see that the default password for the root user is root:

Figure 2.1: The default username and password
So, the default credentials are out there for all the world to see. Obviously, the first thing you want to do when setting up an IoT device is to set up your own user account, give it a good password, and give it sudo privileges. Then get rid of that default account, because leaving it in place, especially if you leave the default password, is just asking for trouble.
But let’s dig deeper. Look in the /etc/password file on RaspEX, and you’ll see the default user there:
raspex:x:1000:1000:,,:/home/raspex:/bin/bashThen, look in the /etc/sudoers file, and you’ll see this line, which allows the raspex user to do all sudo commands without having to enter a password:
raspex ALL=(ALL) NOPASSWD: ALLAnother thing to watch out for is that some Linux distributions for IoT devices have this rule in a separate file in the /etc/sudoers.d directory, instead of in the main sudoers file. Either way, you’ll want to delete this rule, as well as the default user account, when you set up your IoT device. And of course, you’ll also want to change the root user password, and then lock the root user account.
All right, let’s take a quick look at some new features that have been recently added to sudo.
New sudo features
Section titled “New sudo features”I mentioned before that one of the beautiful things about sudo is that it allows you to see what users are doing with their sudo privileges. Beginning with sudo version 1.9.0, the sudo logging experience has been greatly enhanced. You can now save sudo log messages in JSON format, which allows sudo to log much more information than it normally would, in a format that’s easier to parse. Beginning with sudo version 1.9.4, you can also have sudo send its log messages to a central log server, making it more difficult for bad actors to delete mention of their dirty deeds from the system log files.
Unfortunately, space constraints don’t allow me to do a full write-up about these new features here. That’s okay, though. Over at https://opensource.com/, Mr. Peter Czanik has written a great article that explains them very well. So, I’ll just refer you to him:
5 new sudo features sysadmins need to know in 2022 – https://opensource.com/article/22/2/new-sudo-features-2022
I should also mention that in order to know which new sudo features your Linux distro supports, you’ll need to know which version of sudo that it includes. Find out by doing:
sudo --versionNext, let’s look at some SUSE quirkiness.
Special sudo considerations for SUSE and OpenSUSE
Section titled “Special sudo considerations for SUSE and OpenSUSE”If you’ve ever worked with any kind of SUSE machine, you may have been puzzled by the fact that it asks for the root user’s password, rather than your own password, when you perform a sudo command. That’s because SUSE has a whole different way of doing business with sudo.
When you install a SUSE distro, you’ll see a user creation screen that looks similar to the one that you’ve seen on the RHEL-type distros.

Figure 2.2: The OpenSUSE installer
However, when you check the Use this password for system administrator box, it doesn’t add your user account to the wheel group as the RHEL-type distros do. Instead, it automatically assigns the same password that you created for yourself to the root user account. So, you and the root user will both have the same password.
When you do sudo visudo on a SUSE machine, you’ll see these two lines that you don’t see on any other Linux distro:
Defaults targetpw # ask for the password of the target user i.e. rootALL ALL=(ALL) ALL # WARNING! Only use this together with 'Defaults targetpw'!This means that any user who has the root user password can perform all sudo commands. To be fair though, the comments that precede these two lines inform us that this is only for the initial system setup, and that we should reconfigure sudo in the normal way before putting the machine into production use. To do that, first add your own user account to the wheel group, like so:
donnie@localhost:~> sudo usermod -a -G wheel donnie[sudo] password for root:donnie@localhost:~>Cause the group membership to take effect by logging out of the system and then logging back in. Use the groups command to verify wheel group membership, like so:
donnie@localhost:~> groupsusers wheeldonnie@localhost:~>Next, do sudo visudo, and comment out the two lines that we looked at before. They should now look like this:
#Defaults targetpw # ask for the password of the target user i.e. root#ALL ALL=(ALL) ALL # WARNING! Only use this together with 'Defaults targetpw'!(Or, better yet, just delete the lines.)
Scroll down in the file until you see this line:
# %wheel ALL=(ALL:ALL) ALLRemove the preceding comment symbol to make the line look like this:
%wheel ALL=(ALL:ALL) ALLSave the file and exit visudo. Now, when you do a sudo command, you’ll be asked to enter your own password instead of the root user’s password:
donnie@localhost:~> sudo fdisk -l[sudo] password for donnie:. . .. . .Of course, the root user account is still enabled, so let’s disable it, like so:
donnie@localhost:~> sudo passwd -l rootpasswd: password expiry information changed.donnie@localhost:~>All righty, that pretty much covers the sudo topic. Let’s wrap up and move on.
Summary
Section titled “Summary”We covered a lot of ground in this chapter, and hopefully, you found some suggestions that you can actually use. We started out by showing you the dangers of always logging in as the root user and how you should use sudo instead. In addition to showing you the basics of sudo usage, we also looked at some good sudo tips and tricks.
In the next chapter, we’ll look at some best practices for securing the accounts of normal users. I’ll see you there.
Questions
Section titled “Questions”- What is the best way to grant administrative privileges to users?
- Give every administrative user the root user password.
2. Add each administrative user to either the
sudogroup or thewheelgroup. 3. Createsudorules that only allow administrative users to do tasks that are directly related to their jobs. 4. Add each administrative user to thesudoersfile and grant them full administrative privileges.
- Give every administrative user the root user password.
2. Add each administrative user to either the
- Which of the following is true?
- When users log in as the root user, all the actions that they perform will be recorded in the
auth.logor thesecurelog file. 2. When users usesudo, all the actions that they perform will be recorded in themessagesor thesyslogfile. 3. When users log in as the root user, all the actions that they perform will be recorded in themessagesor thesyslogfile. 4. When users usesudo, all the actions that they perform will be recorded in theauth.logor thesecurelog file.
- When users log in as the root user, all the actions that they perform will be recorded in the
- Which of the following methods would you use to create
sudorules for other users?- Open the
/etc/sudoersfile in your favorite text editor. 2. Open the/etc/sudoersfile withvisudo. 3. Add asudoersfile to each user’s home directory. 4. Open the/var/spool/sudoersfile withvisudo.
- Open the
- Which one of the following represents best security practice?
- Always give the root user password to all users who need to perform administrative tasks.
2. Always give full
sudoprivileges to all users who need to perform administrative tasks. 3. Always just give specific, limitedsudoprivileges to all users who need to perform administrative tasks. 4. Always edit thesudoersfile in a normal text editor, such asnano,vim, oremacs.
- Always give the root user password to all users who need to perform administrative tasks.
2. Always give full
- Which of the following statements is true?
sudocan only be used on Linux. 2.sudocan be used on Linux, Unix, and BSD operating systems. 3. When a user performs a task usingsudo, the task does not get recorded in a security log. 4. When usingsudo, users must enter the root user password.
- You want specific users to edit a specific system configuration file, but you don’t want them to use a shell escape that would allow them to perform other administrative tasks. Which two of the following could you do?
- In the
sudoersfile, specify that the users can only usevimto open a specific configuration file. 2. In thesudoersfile, specify that the users can usesudoeditto edit a specific configuration file. 3. In thesudoersfile, specify theno shell escapeoption for these users. 4. In thesudoersfile, place these users into a group that does not have shell escape privileges.
- In the
Further reading
Section titled “Further reading”- Linux Privilege Escalation exploiting sudo rights: https://medium.com/schkn/linux-privilege-escalation-using-text-editors-and-files-part-1-a8373396708d
- sudo Main Page: https://www.sudo.ws/
- Granting sudo access: https://www.golinuxhub.com/2013/12/how-to-give-permission-to-user-to-run.html
Answers
Section titled “Answers”- c
- d
- b
- c
- b
- b