I am root. Understanding Linux OS Privilege Escalation

I spent the first quarter of 2020 preparing for the OSCP exam. Searching for information on Google and a lot of "blind" attempts took up all my free time. It turned out to be especially difficult to understand the mechanisms for escalating privileges. The PWK course pays great attention to this topic, but methodological materials are always not enough. There are a lot of manuals on the Internet with useful commands, but I am not a supporter of blindly following the recommendations without understanding where this will lead.

I would like to share with you what I managed to learn during the preparation and successful passing of the exam (including periodic raids on Hack The Box). I felt a deep sense of gratitude for every bit of information that helped me walk the Try Harder path more consciously, now is my time to give back to the community.

I want to give you a guide to privilege escalation in OS Linux, which includes an analysis of the most common vectors and related features that you will definitely need. Often, the privilege escalation mechanisms themselves are quite simple, difficulties arise when structuring and analyzing information. Therefore, I decided to start with a "sightseeing tour" and then consider each vector in a separate article. I hope I will save you time to study the topic.

I am root. Understanding Linux OS Privilege Escalation

So, why is privilege escalation even possible in 2020 if the methods have been well known for a very long time? In fact, if the user handles the system correctly, it will really not be possible to increase privileges in it. The main global problem that gives rise to such opportunities is insecure configuration. The presence of outdated software versions containing vulnerabilities in the system is also a special case of an unsafe configuration.

Privilege escalation through insecure configuration

First of all, let's deal with the insecure configuration. Let's begin with IT professionals often use manuals and resources like stackoverflow, many of which contain unsafe commands and configs. A striking example is news that the code most copied from stackoverflow contained an error. An experienced admin will see the jamb, but this is in an ideal world. Even competent professionals increased workload capable of making mistakes. Imagine that the administrator is preparing and approving documentation for the next tender, at the same time delving into the new technology that will be introduced in the next quarter, while periodically solving user support tasks. And then he is given the task of quickly raising a couple of virtual machines and rolling out services on them. What do you think, what is the probability that the admin simply does not notice the jamb? Then the specialists change, but the crutches remain, while companies always strive to minimize costs, including those for IT specialists.

Pseudo shell and jailbreak

The system shell obtained during the production phase is often limited, especially if you obtained it by hacking a web server user. For example, shell restrictions can prevent you from using the sudo command with an error:

sudo: no tty present and no askpass program specified

After getting a shell, I recommend creating a full-fledged terminal, for example with Python.

python -c 'import pty;pty.spawn("/bin/bash")'

You ask: "Why do I need a thousand commands, if I can use one, for example, to transfer files?" The fact is that systems are configured differently, on the next host Python may not be installed, but Perl may be available. The skill is to be able to do familiar things in the system without familiar tools. A complete list of features can be found here.

A low privilege shell can be obtained using teams 1 ΠΈ teams 2 (surprisingly even GIMP).

View command history

Linux collects a history of all executed commands in a file ~ / .bash_history. If the server is in active use and its history is not cleared, there is a good chance that the credentials are found in this file. Clearing the history is banally inconvenient. If the administrator is forced to select ten-level commands via , of course, it will be more convenient for him to call this command from the history than to enter it again. Plus, many do not know about this "hack". If there are alternative shells like Zsh or Fish in the system, they have their own history. To display the history of commands in any shell, just type the command history.

cat ~/.bash_history
cat ~/.mysql_history
cat ~/.nano_history
cat ~/.php_history
cat ~/.atftp_history

There is shared hosting, in which the server is used to host several sites. Typically, with this configuration, each resource has its own user with a separate home directory and a virtual host. So, if configured incorrectly, you can find the .bash_history file in the root directory of the web resource.

Finding passwords in the file system and attacks on adjacent systems

Configuration files for various services may be readable by your current user. In them, you can find credentials in clear text - passwords for accessing the database or related services. The same password can be used both to access the database and to authorize the root user (credential staffing).
It happens that the found credentials belong to services on other hosts. The development of an attack on the infrastructure through a compromised host is no worse than the exploitation of other hosts. Adjacent systems can also be found by looking up IP addresses in the file system.

grep -lRi "password" /home /var/www /var/log 2>/dev/null | sort | uniq #Find string password (no cs) in those directories
grep -a -R -o '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' /var/log/ 2>/dev/null | sort -u | uniq #IPs inside logs

If the compromised host has a web application accessible from the Internet, it is better to exclude its logs from the search for IP addresses. The addresses of resource users from the Internet are unlikely to be useful to us, but the addresses of the internal network (172.16.0.0/12, 192.168.0.0/16, 10.0.0.0/8) and where they go, judging by the logs, may be of interest.

Sudo

The sudo command allows the user to execute a command in the context of root with their own password or without using it at all. Many operations in Linux require root privileges, but running as root is considered very bad practice. Instead, it is better to apply selective permission to execute commands in the root context. However, many Linux tools, including the standard ones like vi, can be used to escalate privileges in legitimate ways. To find the right way, I recommend to look here.

The first thing to do after gaining access to the system is to run the sudo -l command. It will display permission to use the sudo command. If a user without a password is obtained (such as apache or www-data), a sudo privilege escalation vector is unlikely. When using sudo, the system will ask for a password. Using the passwd command to set a password will also not work, it will ask for the current user password. But if sudo is still available, then, in fact, you need to look for:

  • any interpreters, anyone can spawn a shell (PHP, Python, Perl);
  • any text editors (vim, vi, nano);
  • any viewers (less, more);
  • any possibilities of working with the file system (cp, mv);
  • tools that have output in bash, either interactively or as an executable command (awk, find, nmap, tcpdump, man, vi, vim, ansible).

Suid/Sgid

There are many manuals on the Internet that advise building all suid / sgid commands, but a rare article gives specifics on what to do with these programs. Privilege escalation options that do not take into account the use of exploits can be found here. Also, a number of executable files have specific vulnerabilities for the OS version, for example.

In an ideal world, you should run all installed packages through at least searchsploit. In practice, this should be done with the most popular programs like sudo. It is also always an option to use and support the development of automated tools that will highlight interesting, from a privilege escalation point of view, executables with suid/sgid bits set. I will give a list of such tools in the corresponding section of the article.

Writable scripts run by Cron or Init in Root context

Cron jobs can run in the context of different users, including root. If there is a task in cron with a link to an executable file, and it is available for you to write, you can easily replace it with a malicious one and perform privilege escalation. At the same time, by default, files with cron tasks are available for reading by any user.

ls -la /etc/cron.d  # show cron jobs 

Similar is the case with init. The difference is that tasks in cron are executed periodically, and in init - at system startup. For operation, you will need to reboot the system, while some of the services may not rise (if they were not registered in autoload).

ls -la /etc/init.d/  # show init scripts 

You can also search for files writable by any user.

find / -perm -2 -type f 2>/dev/null # find world writable files

The method is quite well-known, experienced system administrators carefully use the chmod command. However, on the Web, the vast majority of manuals describe setting maximum rights. The β€œjust make it work” approach of inexperienced system administrators creates opportunities for privilege escalation in principle. If possible, it's best to look in the command history for unsafe uses of chmod.

chmod +w /path 
chmod 777 /path

Gaining shell access for other users

We look at the list of users in /etc/passwd. We pay attention to those who have a shell. You can brute these users - it is possible that through the resulting user you will eventually be able to increase privileges.

To improve security, I recommend that you always adhere to the principle of least privilege. It also makes sense to take the time to check unsafe configurations that could remain after troubleshooting - this is the "technical duty" of the system administrator.

Self-written code

It's worth taking a close look at the executables in the user's and web server's home directory (/var/www/ unless otherwise specified). These files can turn out to be a completely insecure solution and contain incredible crutches. Of course, if you have some framework in your web server directory, it doesn't make sense to search for zero-day in it as part of a pentest, but it is recommended to find and study custom modifications, plugins and components.

To increase security, it is better to avoid using credentials in self-written scripts, as well as potentially dangerous functionality, such as reading /etc/shadow or manipulating id_rsa, if possible.

Elevation of privilege through exploitation of vulnerabilities

Before attempting to elevate privileges through exploitation, it is important to understand the transferring files to the target host. In addition to the usual tools like ssh, ftp, http (wget, curl), there is a whole "zoo" of possibilities.

To improve the security of your system, update it regularly to the latest stable versions, and also try to use distributions designed for Enterprise. Otherwise, rarely, but there are situations when apt upgrade makes the system unusable.

Exploiting Services Running in the Context of the Root User

Some Linux services run as the privileged user root. They can be found using the ps aux | grep root. In this case, the service may not be announced on the Web and be available locally. If it has public exploits, they can be safely used: a service crash in case of failure is much less critical than an OS crash.

ps -aux | grep root # Linux

The most successful case can be considered the operation of a hacked service in the context of the root user. Operating the SMB service gives SYSTEM privileged access on Windows systems (eg via ms17-010). However, this is not common on Linux systems, so you can spend a lot of time on privilege escalation.

Exploiting Linux Kernel Vulnerabilities

This is the last path to take. Unsuccessful operation can lead to a system crash, and in the event of a reboot, some services (including those through which it was possible to get the original shell) may not rise. It happens that the administrator simply forgot to use the systemctl enable command. Plus it will cause a lot of dissatisfaction with your work if the exploitation has not been agreed upon.
If you decide to use the sources from exploitdb, be sure to read the comments at the beginning of the script. Among other things, it usually says how to compile this exploit correctly. If you were too lazy or needed β€œyesterday” due to deadlines, you can look for repositories with already compiled exploits, for example. However, it should be understood that in this case you will get a pig in a poke. On the other hand, if a programmer understood to the byte how a computer works and the software it uses, he would not have written a line of code in his entire life.

cat /proc/version
uname -a
searchsploit "Linux Kernel" 

Metasploit

In order to catch and handle a connection, it's always better to use the exploit/multi/handler module. The main thing is to set the correct payload, for example, generic/shell/reverce_tcp or generic/shell/bind_tcp. The shell obtained in Metasploit can be upgraded to Meterpreter using the post/multi/manage/shell_to_meterpreter module. With Meterpreter, you can automate the post-exploitation process. For example, the post/multi/recon/local_exploit_suggester module checks the platform, architecture, and exploitable entities and suggests Metasploit modules for privilege escalation on the target system. Thanks to Meterpreter, privilege escalation sometimes comes down to running the right module, but hacking without understanding what is happening under the hood is not true (you still have to write a report).

Tools

Tools to automate local collection of information will save you a lot of effort and time, but by themselves are not able to fully identify the privilege escalation path, especially in the case of exploiting kernel vulnerabilities. Automation tools will perform all the necessary commands for you to collect information about the system, but it is also important to be able to analyze received data. I hope my article will be useful to you in this. Of course, there are many more tools than I will list below, but they all do about the same thing - it's more a matter of taste.

Linpeas

A fairly fresh tool, the first commit is dated January 2019. Currently my favorite instrument. The bottom line is that it highlights the most interesting privilege escalation vectors. Agree, it is more convenient to get an expert assessment at this level than to parse monolithic raw data.

LinEnum

My second favorite tool, it also collects and organizes the data received as a result of local enumeration.

linux-exploit-suggester(1,2)

This exploit will analyze the system for suitable conditions for exploits. In fact, it will do a job identical to the Metasploit local_exploit_suggester module, but will offer links to exploit-db source codes rather than Metasploit modules.

Linuxprivchecker

This script will collect and organize by sections a large amount of information that can be useful for the formation of a privilege escalation vector.

Another time I will elaborate Linux privilege escalation via suid/sgid.

Source: habr.com

Add a comment