Attacking the OS
Last updated
Last updated
User Account Control (UAC) is a feature that enables a consent prompt for elevated activities. Applications have different integrity
levels, and a program with a high level can perform tasks that could potentially compromise the system. When UAC is enabled, applications and tasks always run under the security context of a non-administrator account unless an administrator explicitly authorizes these applications/tasks to have administrator-level access to the system to run. It is a convenience feature that protects administrators from unintended changes but is not considered a security boundary.
When UAC is in place, a user can log into their system with their standard user account. When processes are launched using a standard user token, they can perform tasks using the rights granted to a standard user. Some applications require additional permissions to run, and UAC can provide additional access rights to the token for them to run correctly.
This page discusses how UAC works in great depth and includes the logon process, user experience, and UAC architecture. Administrators can use security policies to configure how UAC works specific to their organization at the local level (using secpol.msc), or configured and pushed out via Group Policy Objects (GPO) in an Active Directory domain environment. The various settings are discussed in detail here. There are 10 Group Policy settings that can be set for UAC. The following table provides additional detail:
FilterAdministratorToken
Disabled
EnableUIADesktopToggle
Disabled
ConsentPromptBehaviorAdmin
Prompt for consent for non-Windows binaries
ConsentPromptBehaviorUser
Prompt for credentials on the secure desktop
EnableInstallerDetection
Enabled (default for home) Disabled (default for enterprise)
ValidateAdminCodeSignatures
Disabled
EnableSecureUIAPaths
Enabled
EnableLUA
Enabled
PromptOnSecureDesktop
Enabled
EnableVirtualization
Enabled
UAC should be enabled, and although it may not stop an attacker from gaining privileges, it is an extra step that may slow this process down and force them to become noisier.
The default RID 500 administrator
account always operates at the high mandatory level. With Admin Approval Mode (AAM) enabled, any new admin accounts we create will operate at the medium mandatory level by default and be assigned two separate access tokens upon logging in. In the example below, the user account sarah
is in the administrators group, but cmd.exe is currently running in the context of their unprivileged access token.
Checking Current User
Confirming Admin Group Membership
Reviewing User Privileges
Confirming UAC is Enabled
Checking UAC Level
The value of ConsentPromptBehaviorAdmin
is 0x5
, which means the highest UAC level of Always notify
is enabled. There are fewer UAC bypasses at this highest level.
Checking Windows Version
UAC bypasses leverage flaws or unintended functionality in different Windows builds. Let's examine the build of Windows we're looking to elevate on.
This returns the build version 14393, which using this page we cross-reference to Windows release 1607
.
The UACME project maintains a list of UAC bypasses, including information on the affected Windows build number, the technique used, and if Microsoft has issued a security update to fix it. Let's use technique number 54, which is stated to work from Windows 10 build 14393. This technique targets the 32-bit version of the auto-elevating binary SystemPropertiesAdvanced.exe
. There are many trusted binaries that Windows will allow to auto-elevate without the need for a UAC consent prompt.
According to this blog post, the 32-bit version of SystemPropertiesAdvanced.exe
attempts to load the non-existent DLL srrstr.dll, which is used by System Restore functionality.
When attempting to locate a DLL, Windows will use the following search order.
The directory from which the application loaded.
The system directory C:\Windows\System32
for 64-bit systems.
The 16-bit system directory C:\Windows\System
(not supported on 64-bit systems)
The Windows directory.
Any directories that are listed in the PATH environment variable.
Reviewing Path Variable
Let's examine the path variable using the command cmd /c echo %PATH%
. This reveals the default folders below. The WindowsApps
folder is within the user's profile and writable by the user.
We can potentially bypass UAC in this by using DLL hijacking by placing a malicious srrstr.dll
DLL to WindowsApps
folder, which will be loaded in an elevated context.
First, let's generate a DLL to execute a reverse shell.
Starting Python HTTP Server on Attack Host
Downloading DLL Target
Starting nc Listener on Attack Host
Testing Connection
If we execute the malicious srrstr.dll
file, we will receive a shell back showing normal user rights (UAC enabled). To test this, we can run the DLL using rundll32.exe
to get a reverse shell connection.
Once we get a connection back, we'll see normal user rights.
Executing SystemPropertiesAdvanced.exe on Target Host
Before proceeding, we should ensure that any instances of the rundll32
process from our previous execution have been terminated.
Optionally:
Now, we can try the 32-bit version of SystemPropertiesAdvanced.exe
from the target host.
Receiving Connection Back
Checking back on our listener, we should receive a connection almost instantly.
This is successful, and we receive an elevated shell that shows our privileges are available and can be enabled if needed.
Permissions on Windows systems are complicated and challenging to get right. A slight modification in one place may introduce a flaw elsewhere. As penetration testers, we need to understand how permissions work in Windows and the various ways that misconfigurations can be leveraged to escalate privileges. The permissions-related flaws discussed in this section are relatively uncommon in software applications put out by large vendors (but are seen from time to time) but are common in third-party software from smaller vendors, open-source software, and custom applications. Services usually install with SYSTEM privileges, so leveraging a service permissions-related flaw can often lead to complete control over the target system. Regardless of the environment, we should always check for weak permissions and be able to do it both with the help of tools and manually in case we are in a situation where we don't have our tools readily available.
Running SharpUp
We can use SharpUp from the GhostPack suite of tools to check for service binaries suffering from weak ACLs.
Checking Permissions with icacls
Replacing Service Binary
This service is also startable by unprivileged users, so we can make a backup of the original binary and replace it with a malicious binary generated with msfvenom
. It can give us a reverse shell as SYSTEM
, or add a local admin user and give us full administrative control over the machine.
Reviewing SharpUp Again
Let's check the SharpUp
output again for any modifiable services. We see the WindscribeService
is potentially misconfigured.
Next, we'll use AccessChk from the Sysinternals suite to enumerate permissions on the service. The flags we use, in order, are -q
(omit banner), -u
(suppress errors), -v
(verbose), -c
(specify name of a Windows service), and -w
(show only objects that have write access). Here we can see that all Authenticated Users have SERVICE_ALL_ACCESS rights over the service, which means full read/write control over it.
Checking the local administrators group confirms that our user htb-student
is not a member.
We can use our permissions to change the binary path maliciously. Let's change it to add our user to the local administrator group. We could set the binary path to run any command or executable of our choosing (such as a reverse shell binary).
Stopping Service
Starting the Service
Since we have full control over the service, we can start it again, and the command we placed in the binpath
will run even though an error message is returned. The service fails to start because the binpath
is not pointing to the actual service executable. Still, the executable will run when the system attempts to start the service before erroring out and stopping the service again, executing whatever command we specify in the binpath
.
Confirming Local Admin Group Addition
Another notable example is the Windows Update Orchestrator Service (UsoSvc), which is responsible for downloading and installing operating system updates. It is considered an essential Windows service and cannot be removed. Since it is responsible for making changes to the operating system through the installation of security and feature updates, it runs as the all-powerful NT AUTHORITY\SYSTEM
account. Before installing the security patch relating to CVE-2019-1322, it was possible to elevate privileges from a service account to SYSTEM
. This was due to weak permissions, which allowed service accounts to modify the service binary path and start/stop the service.
We can clean up after ourselves and ensure that the service is working correctly by stopping it and resetting the binary path back to the original service executable.
Reverting the Binary Path
Starting the Service Again
If all goes to plan, we can start the service again without an issue.
Verifying Service is Running
Querying the service will show it running again as intended.
When a service is installed, the registry configuration specifies a path to the binary that should be executed on service start. If this binary is not encapsulated within quotes, Windows will attempt to locate the binary in different folders. Take the example binary path below.
Service Binary Path
Windows will decide the execution method of a program based on its file extension, so it's not necessary to specify it. Windows will attempt to load the following potential executables in order on service start, with a .exe being implied:
C:\Program
C:\Program Files
C:\Program Files (x86)\System
C:\Program Files (x86)\System Explorer\service\SystemExplorerService64
Querying Service
If we can create the following files, we would be able to hijack the service binary and gain command execution in the context of the service, in this case, NT AUTHORITY\SYSTEM
.
C:\Program.exe\
C:\Program Files (x86)\System.exe
However, creating files in the root of the drive or the program files folder requires administrative privileges. Even if the system had been misconfigured to allow this, the user probably wouldn't be able to restart the service and would be reliant on a system restart to escalate privileges. Although it's not uncommon to find applications with unquoted service paths, it isn't often exploitable.
It is also worth searching for weak service ACLs in the Windows Registry. We can do this using accesschk
.
Checking for Weak Service ACLs in Registry
Changing ImagePath with PowerShell
We can abuse this using the PowerShell cmdlet Set-ItemProperty
to change the ImagePath
value, using a command such as:
Check Startup Programs
We can use WMIC to see what programs run at system startup. Suppose we have write permissions to the registry for a given binary or can overwrite a binary listed. In that case, we may be able to escalate privileges to another user the next time that the user logs in.
This post and this site detail many potential autorun locations on Windows systems.
It's a big challenge to ensure that all user desktops and servers are updated, and 100% compliance for all computers with security patches is likely not an achievable goal. Assuming a computer has been targeted for installation of updates, for example, using SCCM (Microsoft System Center Configuration Manager) or WSUS (Windows Server Update Services), there are still many reasons they could fail to install. Over the years, there have been many kernel exploits that affect the Windows operating system from Windows 2000/XP up to Windows 10/Server 2016/2019. Below can be found a detailed table of known remote code execution/local privilege escalation exploits for Windows operating systems, broken down by service pack level, from Windows XP onward to Server 2016.
Service Pack
SP0
SP1
SP2
SP3
SP0
SP1
SP2
SP0
SP1
SP2
SP0
SP2
SP0
SP1
SP0
SP1
MS03-026
•
•
•
•
•
•
•
MS05-039
•
•
•
•
•
MS08-025
•
•
•
•
•
•
•
•
•
MS08-067
•
•
•
•
•
•
•
•
•
•
MS08-068
•
•
•
•
•
•
•
•
•
•
MS09-012
•
•
•
•
•
•
•
•
•
•
MS09-050
•
•
•
•
•
MS10-015
•
•
•
•
•
•
•
•
MS10-059
•
•
•
•
•
•
•
MS10-092
•
•
•
•
•
•
•
MS11-011
•
•
•
•
•
•
•
•
•
•
•
MS11-046
•
•
•
•
•
•
•
•
•
•
•
•
•
MS11-062
•
•
•
•
MS11-080
•
•
•
•
MS13-005
•
•
•
•
•
•
•
•
•
•
•
MS13-053
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS13-081
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS14-002
•
•
•
•
MS14-040
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS14-058
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS14-062
•
•
•
MS14-068
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS14-070
•
•
•
MS15-001
•
•
•
•
•
•
•
•
MS15-010
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS15-051
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS15-061
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS15-076
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS15-078
•
•
•
•
•
•
•
•
•
•
•
•
•
MS15-097
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS16-016
•
•
•
•
•
•
•
•
•
MS16-032
•
•
•
•
•
•
•
•
•
•
•
•
MS16-135
•
•
•
•
•
•
•
•
•
•
•
•
•
•
MS17-010
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
CVE-2017-0213: COM Aggregate Marshaler
•
•
•
•
•
•
•
•
•
•
Hot Potato
•
•
•
•
•
•
•
•
•
SmashedPotato
•
•
•
•
•
•
•
•
•
This table is not 100% complete, and does not go past 2017. As of today, there are more known vulnerabilities for the newer operating system versions and even Server 2019.
This site is handy for searching out detailed information about Microsoft security vulnerabilities. This database has 4,733 security vulnerabilities entered at the time of writing, showing the massive attack surface that a Windows environment presents.
It is important to note that while some of the examples above are
remote code execution vulnerabilities, we can just as easily use them to escalate privileges.
One example is if we gain access to a system and notice a port such as 445 (SMB service) not accessible from the outside, we may be able to privilege escalate if it is vulnerable to something such as EternalBlue (MS17-010). In this case, we could either port forward the port in question to be accessible from our attack host or run the exploit in question locally to escalate privileges.
Over the years, there have been many high-impact Windows vulnerabilities that can be leveraged to escalate privileges, some being purely local privilege escalation vectors and others being remote code execution (RCE) flaws that can be used to escalate privileges by forwarding a local port. One example of the latter would be landing on a box that does not allow access to port 445 from the outside, performing port forward to access this port from our attack box, and leveraging a remote code execution flaw against the SMB service to escalate privileges. Below are some extremely high-impact Windows vulnerabilities over the years that can be leveraged to escalate privileges.
MS08-067
- This was a remote code execution vulnerability in the "Server" service due to improper handling of RPC requests. This affected Windows Server 2000, 2003, and 2008 and Windows XP and Vista and allows an unauthenticated attacker to execute arbitrary code with SYSTEM privileges. Though typically encountered in client environments as a remote code execution vulnerability, we may land on a host where the SMB service is blocked via the firewall. We can use this to escalate privileges after forwarding port 445 back to our attack box. Though this is a "legacy" vulnerability, I still do see this pop up from time to time in large organizations, especially those in the medical industry who may be running specific applications that only work on older versions of Windows Server/Desktop. We should not discount older vulnerabilities even in 2021. We will run into every scenario under the sun while performing client assessments and must be ready to account for all possibilities. The box Legacy on the Hack The Box platform showcases this vulnerability from the remote code execution standpoint. There are standalone as well as a Metasploit version of this exploit.
MS17-010
- Also known as EternalBlue is a remote code execution vulnerability that was part of the FuzzBunch toolkit released in the Shadow Brokers leak. This exploit leverages a vulnerability in the SMB protocol because the SMBv1 protocol mishandles packets specially crafted by an attacker, leading to arbitrary code execution on the target host as the SYSTEM account. As with MS08-067, this vulnerability can also be leveraged as a local privilege escalation vector if we land on a host where port 445 is firewalled off. There are various versions of this exploit for the Metasploit Framework as well as standalone exploit scripts. This attack was showcased in the Blue box on Hack The Box, again from the remote standpoint.
ALPC Task Scheduler 0-Day
- The ALPC endpoint method used by the Windows Task Scheduler service could be used to write arbitrary DACLs to .job
files located in the C:\Windows\tasks
directory. An attacker could leverage this to create a hard link to a file that the attacker controls. The exploit for this flaw used the SchRpcSetSecurity API function to call a print job using the XPS printer and hijack the DLL as NT AUTHORITY\SYSTEM via the Spooler service. An in-depth writeup is available here. The Hack The Box box Hackback can be used to try out this privilege escalation exploit.
Summer of 2021 revealed a treasure trove of new Windows and Active Directory-related remote code execution and local privilege escalation flaws to the delight of penetration testers (and real-world attackers), and I'm sure groans from our hard-working colleagues on the defense side of things.
CVE-2021-36934 HiveNightmare, aka SeriousSam
is a Windows 10 flaw that results in ANY user having rights to read the Windows registry and access sensitive information regardless of privilege level. Researchers quickly developed a PoC exploit to allow reading of the SAM, SYSTEM, and SECURITY registry hives and create copies of them to process offline later and extract password hashes (including local admin) using a tool such as SecretsDump.py. More information about this flaw can be found here and this exploit binary can be used to create copies of the three files to our working directory. This script can be used to detect the flaw and also fix the ACL issue. Let's take a look.
We can check for this vulnerability using icacls
to check permissions on the SAM file. In our case, we have a vulnerable version as the file is readable by the BUILTIN\Users
group.
Successful exploitation also requires the presence of one or more shadow copies. Most Windows 10 systems will have System Protection
enabled by default which will create periodic backups, including the shadow copy necessary to leverage this flaw.
This PoC can be used to perform the attack, creating copies of the aforementioned registry hives:
These copies can then be transferred back to the attack host, where impacket-secretsdump
is used to extract the hashes:
CVE-2021-1675/CVE-2021-34527 PrintNightmare
is a flaw in RpcAddPrinterDriver which is used to allow for remote printing and driver installation. This function is intended to give users with the Windows privilege SeLoadDriverPrivilege
the ability to add drivers to a remote Print Spooler. This right is typically reserved for users in the built-in Administrators group and Print Operators who may have a legitimate need to install a printer driver on an end user's machine remotely. The flaw allowed any authenticated user to add a print driver to a Windows system without having the privilege mentioned above, allowing an attacker full remote code execution as SYSTEM on any affected system. The flaw affects every supported version of Windows, and being that the Print Spooler runs by default on Domain Controllers, Windows 7 and 10, and is often enabled on Windows servers, this presents a massive attack surface, hence "nightmare." Microsoft initially released a patch that did not fix the issue (and early guidance was to disable the Spooler service, which is not practical for many organizations) but released a second patch in July of 2021 along with guidance to check that specific registry settings are either set to 0
or not defined. Once this vulnerability was made public, PoC exploits were released rather quickly. This version by @cube0x0 can be used to execute a malicious DLL remotely or locally using a modified version of Impacket. The repo also contains a C# implementation. This PowerShell implementation can be used for quick local privilege escalation. By default, this script adds a new local admin user, but we can also supply a custom DLL to obtain a reverse shell or similar if adding a local admin user is not in scope.
We can quickly check if the Spooler service is running with the following command. If it is not running, we will receive a "path does not exist" error.
First start by bypassing the execution policy on the target host:
Now we can import the PowerShell script and use it to add a new local admin user.
The first step is looking at installed updates and attempting to find updates that may have been missed, thus, opening up an attack path for us.
Examining Installed Updates
We can examine the installed updates in several ways. Below are three separate commands we can use.
We can search for each KB (Microsoft Knowledge Base ID number) in the Microsoft Update Catalog to get a better idea of what fixes have been installed and how far behind the system may be on security updates. A search for KB5000808
shows us that this is an update from March of 2021, which means the system is likely far behind on security updates.
Next, let's exploit Microsoft CVE-2020-0668: Windows Kernel Elevation of Privilege Vulnerability, which exploits an arbitrary file move vulnerability leveraging the Windows Service Tracing.
Setting a custom MaxFileSize value that is smaller than the size of the file prompts the file to be renamed with a .OLD
extension when the service is triggered. This move operation is performed by NT AUTHORITY\SYSTEM
, and can be abused to move a file of our choosing with the help of mount points and symbolic links.
Let's verify our current user's privileges.
We can use this exploit for CVE-2020-0668, download it, and open it in Visual Studio within a VM. Building the solution should create the following files.
At this point, we can use the exploit to create a file of our choosing in a protected folder such as C:\Windows\System32. We aren't able to overwrite any protected Windows files. This privileged file write needs to be chained with another vulnerability, such as UsoDllLoader or DiagHub to load the DLL and escalate our privileges.
However, the UsoDllLoader technique may not work if Windows Updates are pending or currently being installed, and the DiagHub service may not be available.
We can also look for any third-party software, which can be leveraged, such as the Mozilla Maintenance Service. This service runs in the context of SYSTEM and is startable by unprivileged users. The (non-system protected) binary for this service is located below.
C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe
icacls
confirms that we only have read and execute permissions on this binary based on the line BUILTIN\Users:(I)(RX)
in the command output.
Let's generate a malicious maintenanceservice.exe
binary that can be used to obtain a Meterpreter reverse shell connection from our target.
Or use reverse_tcp
We can download it to the target using cURL after starting a Python HTTP server on our attack host like in the User Account Control
section previously. We can also use wget from the target.
For this step we need to make two copies of the malicious .exe file. We can just pull it over twice or do it once and make a second copy.
We need to do this because running the exploit corrupts the malicious version of maintenanceservice.exe
that is moved to (our copy in c:\Users\htb-student\Desktop
that we are targeting) c:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe
which we will need to account for later. If we attempt to utilize the copied version, we will receive a system error 216
because the .exe file is no longer a valid binary.
Next, let's run the exploit. It accepts two arguments, the source and destination files.
We can overwrite the maintenanceservice.exe
binary in c:\Program Files (x86)\Mozilla Maintenance Service
with a good working copy of our malicious binary created earlier before proceeding to start the service. In this example, we downloaded two copies of the malicious binary to C:\Users\htb-student\Desktop
, maintenanceservice.exe
and maintenanceservice2.exe
. Let's move the good copy that was not corrupted by the exploit maintenanceservice2.exe
to the Program Files directory, making sure to rename the file properly and remove the 2
or the service won't start. The copy
command will only work from a cmd.exe window, not a PowerShell console.
Next, save the below commands to a Resource Script file named handler.rc
.
Or use reverse_tcp
:
We may be able to escalate privileges on well-patched and well-configured systems if users are permitted to install software or vulnerable third-party applications/services are used throughout the organization. Some services/applications may allow us to escalate to SYSTEM. In contrast, others could cause a denial-of-service condition or allow access to sensitive data such as configuration files containing passwords.
The output looks mostly standard for a Windows 10 workstation. However, the Druva inSync
application stands out.
A quick Google search shows that version 6.6.3
is vulnerable to a command injection attack via an exposed RPC service. We may be able to use this exploit PoC to escalate our privileges. From this blog post which details the initial discovery of the flaw, we can see that Druva inSync is an application used for “Integrated backup, eDiscovery, and compliance monitoring,” and the client application runs a service in the context of the powerful NT AUTHORITY\SYSTEM
account. Escalation is possible by interacting with a service running locally on port 6064.
Next, let's map the process ID (PID) 3324
back to the running process.
Enumerating Running Service
At this point, we have enough information to determine that the Druva inSync application is indeed installed and running, but we can do one last check using the Get-Service
cmdlet.
Druva inSync PowerShell PoC
With this information in hand, let's try out the exploit PoC, which is this short PowerShell snippet.
Modifying PowerShell PoC
For our purposes, we want to modify the $cmd
variable to our desired command. We can do many things here, such as adding a local admin user (which is a bit noisy, and we want to avoid modifying things on client systems wherever possible) or sending ourselves a reverse shell. Let's try this with Invoke-PowerShellTcp.ps1.
Download the script to our attack box, and rename it something simple like shell.ps1
. Open the file, and append the following at the bottom of the script file (changing the IP to match our address and listening port as well):
Modify the $cmd
variable in the Druva inSync exploit PoC script to download our PowerShell reverse shell into memory.
Finally, start a Netcat
listener on the attack box and execute the PoC PowerShell script on the target host (after modifying the PowerShell execution policy with a command such as Set-ExecutionPolicy Bypass -Scope Process
). We will get a reverse shell connection back with SYSTEM
privileges if all goes to plan.
DLL injection
is a method that involves inserting a piece of code, structured as a Dynamic Link Library (DLL), into a running process. This technique allows the inserted code to run within the process's context, thereby influencing its behavior or accessing its resources.
DLL injection
finds legitimate applications in various areas. For instance, software developers leverage this technology for hot patching
, a method that enables the amendment or updating of code seamlessly, without the need to restart the ongoing process immediately. A prime example of this is Azure's use of hot patching for updating operational servers, which facilitates the benefits of the update without necessitating server downtime.
There are several different methods for actually executing a DLL injection.
LoadLibrary
is a widely utilized method for DLL injection, employing the LoadLibrary
API to load the DLL into the target process's address space.
The LoadLibrary
API is a function provided by the Windows operating system that loads a Dynamic Link Library (DLL) into the current process’s memory and returns a handle that can be used to get the addresses of functions within the DLL.
The first example shows how LoadLibrary
can be used to load a DLL into the current process legitimately.
The second example illustrates the use of LoadLibrary
for DLL injection. This process involves allocating memory within the target process for the DLL path and then initiating a remote thread that begins at LoadLibrary
and directs towards the DLL path.
Manual Mapping
is an incredibly complex and advanced method of DLL injection. It involves the manual loading of a DLL into a process's memory and resolves its imports and relocations. However, it avoids easy detection by not using the LoadLibrary
function, whose usage is monitored by security and anti-cheat systems.
A simplified outline of the process can be represented as follows:
Load the DLL as raw data into the injecting process.
Map the DLL sections into the targeted process.
Inject shellcode into the target process and execute it. This shellcode relocates the DLL, rectifies the imports, executes the Thread Local Storage (TLS) callbacks, and finally calls the DLL main.
Reflective DLL injection
is a technique that utilizes reflective programming to load a library from memory into a host process. The library itself is responsible for its loading process by implementing a minimal Portable Executable (PE) file loader. This allows it to decide how it will load and interact with the host, minimising interaction with the host system and process.
Stephen Fewer has a great GitHub demonstrating the technique. Borrowing his explanation below:
"The procedure of remotely injecting a library into a process is two-fold. First, the library you aim to inject must be written into the target process’s address space (hereafter referred to as the 'host process'). Second, the library must be loaded into the host process to meet the library's runtime expectations, such as resolving its imports or relocating it to an appropriate location in memory.
Assuming we have code execution in the host process and the library we aim to inject has been written into an arbitrary memory location in the host process, Reflective DLL Injection functions as follows.
Execution control is transferred to the library's ReflectiveLoader
function, an exported function found in the library's export table. This can happen either via CreateRemoteThread()
or a minimal bootstrap shellcode.
As the library's image currently resides in an arbitrary memory location, the ReflectiveLoader
initially calculates its own image's current memory location to parse its own headers for later use.
The ReflectiveLoader
then parses the host process's kernel32.dll
export table to calculate the addresses of three functions needed by the loader, namely LoadLibraryA
, GetProcAddress
, and VirtualAlloc
.
The ReflectiveLoader
now allocates a continuous memory region where it will proceed to load its own image. The location isn't crucial; the loader will correctly relocate the image later.
The library's headers and sections are loaded into their new memory locations.
The ReflectiveLoader
then processes the newly loaded copy of its image's import table, loading any additional libraries and resolving their respective imported function addresses.
The ReflectiveLoader
then processes the newly loaded copy of its image's relocation table.
The ReflectiveLoader
then calls its newly loaded image's entry point function, DllMain,
with DLL_PROCESS_ATTACH
. The library has now been successfully loaded into memory.
Finally, the ReflectiveLoader
returns execution to the initial bootstrap shellcode that called it, or if it were called via CreateRemoteThread
, the thread would terminate."
DLL Hijacking
is an exploitation technique where an attacker capitalizes on the Windows DLL loading process. These DLLs can be loaded during runtime, creating a hijacking opportunity if an application doesn't specify the full path to a required DLL, hence rendering it susceptible to such attacks.
The default DLL search order used by the system depends on whether Safe DLL Search Mode
is activated. When enabled (which is the default setting), Safe DLL Search Mode repositions the user's current directory further down in the search order. It’s easy to either enable or disable the setting by editing the registry.
Press Windows key + R
to open the Run dialog box.
Type in Regedit
and press Enter
. This will open the Registry Editor.
Navigate to HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager
.
In the right pane, look for the SafeDllSearchMode
value. If it does not exist, right-click the blank space of the folder or right-click the Session Manager
folder, select New
and then DWORD (32-bit) Value
. Name this new value as SafeDllSearchMode
.
Double-click SafeDllSearchMode
. In the Value data field, enter 1
to enable and 0
to disable Safe DLL Search Mode.
Click OK
, close the Registry Editor and Reboot the system for the changes to take effect.
With this mode enabled, applications search for necessary DLL files in the following sequence:
The directory from which the application is loaded.
The system directory.
The 16-bit system directory.
The Windows directory.
The current directory.
The directories that are listed in the PATH environment variable.
However, if 'Safe DLL Search Mode' is deactivated, the search order changes to:
The directory from which the application is loaded.
The current directory.
The system directory.
The 16-bit system directory.
The Windows directory
The directories that are listed in the PATH environment variable
DLL Hijacking involves a few more steps. First, you need to pinpoint a DLL the target is attempting to locate. Specific tools can simplify this task:
Process Explorer
: Part of Microsoft's Sysinternals suite, this tool offers detailed information on running processes, including their loaded DLLs. By selecting a process and inspecting its properties, you can view its DLLs.
PE Explorer
: This Portable Executable (PE) Explorer can open and examine a PE file (such as a .exe or .dll). Among other features, it reveals the DLLs from which the file imports functionality.
After identifying a DLL, the next step is determining which functions you want to modify, which necessitates reverse engineering tools, such as disassemblers and debuggers. Once the functions and their signatures have been identified, it's time to construct the DLL.
Let’s take a practical example. Consider the C program below:
It loads an add
function from the library.dll
and utilises this function to add two numbers. Subsequently, it prints the result of the addition. By examining the program in Process Monitor (procmon), we can observe the process of loading the library.dll
located in the same directory.
First, let's set up a filter in procmon to solely include main.exe
, which is the process name of the program. This filter will help us focus specifically on the activities related to the execution of main.exe
. It is important to note that procmon only captures information while it is actively running. Therefore, if your log appears empty, you should close main.exe
and reopen it while procmon is running. This will ensure that the necessary information is captured and available for analysis.
Then if you scroll to the bottom, you can see the call to load library.dll
.
We can further filter for an Operation
of Load Image
to only get the libraries the app is loading.
Create a new library: We will create a new library serving as the proxy for library.dll
. This library will contain the necessary code to load the Add
function from library.dll
and perform the required tampering.
Load the Add
function: Within the new library, we will load the Add
function from the original library.dll
. This will allow us to access the original function.
Tamper with the function: Once the Add
function is loaded, we can then apply the desired tampering or modifications to its result. In this case, we are simply going to modify the result of the addition, to add + 1
to the result.
Return the modified function: After completing the tampering process, we will return the modified Add
function from the new library back to main.exe
. This will ensure that when main.exe
calls the Add
function, it will execute the modified version with the intended changes.
Either compile it or use the precompiled version provided. Rename library.dll
to library.o.dll
, and rename tamper.dll
to library.dll
.
Running main.exe
then shows the successful hack.
Another option to execute a DLL Hijack attack is to replace a valid library the program is attempting to load but cannot find with a crafted library. If we change the procmon filter to focus on entries whose path ends in .dll
and has a status of NAME NOT FOUND
we can find such libraries in main.exe
.
As we know, main.exe
searches in many locations looking for x.dll
, but it doesn’t find it anywhere. The entry we are particularly interested in is:
Where it is looking to load x.dll
from the app directory. We can take advantage of this and load our own code, with very little context of what it is looking for in x.dll
.
This code defines a DLL entry point function called DllMain
that is automatically called by Windows when the DLL is loaded into a process. When the library is loaded, it will simply print Hijacked... Oops...
to the terminal, but you could theoretically do anything here.
Either compile it or use the precompiled version provided. Rename hijack.dll
to x.dll
, and run main.exe
.