HTBA : Active Directory Intro
Why AD ?
AD is a directory service for Windows networks; it is made for centralized management of users, computers, groups, network devices, file shares, group policies, devices, trusts. It provides authentication and authorization within a domain. Its security flaws come from its backwards-compatibility, AND the fact that everything is not secure by default.Is is basically a read-only database accessible to everyone - anyone can enumerate a directory.
95% of companies run AD, making it a prime target. Any vuln on AD is interesting and exploiotable, since a simple AD user account allows enumerating the whole domain.
The goal here is to learn the foundations of AD enumeration and attack. We will get to know the structure and function of AD, its objects, user rights, tools, processes, etc.
History
Comes from the X.500 directory (same as LDAP !). Introduced in the 90s and came to be with WinServ 2000. LDAP and Kerberos were adopted later. WinServ 2003 added forests, allowing admins to create containers for domains, users, etc. ADFS came with WinServ 2008 to provide SSO - users can access applications with a single login across organizational boundaries. ADFS is claim-based identity, meaning it identifies users by a set of claims related to their identity, which are then packaged in a token.
Winserv 2016 brought cloud migration, security enhancement, user access monitoring... And also Group Managegement Service Accounts (here) which offers a more secure way to run automated tasks - often recommended against "kerberoasting". It also saw the release of AAD Connect, pushing more and more towards the cloud.
AD and its companions (Exchange...) suffer regularly from misconfigurations and flaws. Running AD in an org requires to stay up-to-date and is a lot of work (I know about it !). AD is hard to maintain and a requirement for a lot of people, especially on-prem.
Over the years
Since 2014, many tools relating to AD in the research emerged. AD and AzureAD form a large surface; flaws are being discovered regularly such as noPac in dec. 2021.
A few important tools when it comes to AD and security, taken from the timeline (from oldest to newest), would be:
- Responder - used for poisoning, obtaining password hashes, perfom SMB relay attacks, etc.
- Impacket is a collection of Python classes used for working with network protocols, which is a staple in pentesting. Useful with AD.
- Bloodhound for visualizing attack paths.
- ACL attacks
- Rubeus toolkit for attacking Kerberos
- PingCastle for auditing
- More kerberoasting
- ZeroLogon attack (2020) allowing DC impersonation.
- PrintNightmare - remote code execution; Shadow Credentials - privilege escalation; noPac - gain domain control. All three from 2021
Structure
A directory Service such as ADDS (AD Domain Services) gives an org ways to store data and make them available. AD stores information and manages the rights needed to access them. AD flaws and misconfigurations can often be used to get a foothold in an infra, move laterally and vertically within a network, gain access to protected resources.
A basic AD user with no added privileges can enumerate most objects within AD, including :
- Computers
- Users
- Group Information
- OUs
- Default Domain Policy
- Functional Domain Levels
- Password policy
- GPOs
- Domain Trusts
- ACLs
We must understand the basics of set up and admin of AD before attacking.
AD is a tree structure with a forest at the top, containing one or more domains. Domains can have nested subdomains. A forest is the security boundary in which all objects are under administrative control; each forest containing one or more domains. A forest has built-in OUs, such as Domain Controllers, Users, Computers... and admin-made OUs. OUs contain sub-OUs and objects, allowing for Group Policies.
Here is a simplistic example:
INLANEFREIGHT.LOCAL/ ├── ADMIN.INLANEFREIGHT.LOCAL │ ├── GPOs │ └── OU │ └── EMPLOYEES │ ├── COMPUTERS │ │ └── FILE01 │ ├── GROUPS │ │ └── HQ Staff │ └── USERS │ └── barbara.jones ├── CORP.INLANEFREIGHT.LOCAL └── DEV.INLANEFREIGHT.LOCAL
Here, INLANEFREIGHT.LOCAL is the root domain and contains subdomains (ADMIN, CORP, DEV), as well as other objects. It is common to see multiple domains or forests linked via trust relationships in orgs that perform a lot of acquisitions. It is often quicker to add a trust relationship to a newly acquired domain than recreating everything. Domain trusts introduce a lot of security issues if improperly administered.
2 forests can have a bidirectional trust relationship, meaning they both can access the other's resources. Each forest can have child domains.
Here, the 2 forests have a bidirectional trust between their roots; inlanefreight.local can access freightlogistics.local's resources, and vice-versa. But the child domains from forest A do not necessarily have a trust relationship with the forest B's children. A user from admin.dev.inlanefreight.local could not authenticate as such on dev.freightlogistics.local.
Terminology
A few common ones
- Object : any resource present in an AD : OU, printer, computer, etc
- Attributes : Every object in AD has a set of attributes used to define its characteristics. All attributes have a corresponding LDAP name that can be used (displayName for Full Name, for ex.)
- Schema : the schema is the blueprint of the AD environment : what types of objects can exists, and their attributes. Each object has mandatory and / or optional attributes to set. When an object is created from a class, it is "instanciated".
- Domain : logical group of objects. Domains can be idnependent or have trust relationships between them.
- Forest : Collection of domains. Topmost container and contains all AD objects.
- Tree : Collection of domains that begins with a root domain. A forest is a collection of AD trees. Each domain in a tree has a boundary with other domains in the tree, and the tree elements have a parent-child trust relationship.
- Container : objects that hold other objects and have a defined place in the subtree.
- Leaf : do not contain other objects and are at the end of the subtree.
- GUID : Globally Unique IDentifier. A unique 128-bit value assigned when a domain user or group is created. Unique across the org, like a MAC address. Every single object created by AD has a GUID, stored in the objectGUID attribute. When querying for an AD object, it is an attribute we can use in Powershell for example. Most precise value to use to look for smthing.
- Security Principals : anything the OS can authenticate, including users, computer accounts, and even threads that run in the context of a user or computer account (eg a service running with a service account). We can also have local users and groups, managed not by AD but by the SAM (Security Accounts Manager).
- SID (Security Identifier) : Unique identifier for a security principal or security group. Every account, group, process has one, issued by the DC and stored in a secure DB. SIDs are used only once; even if the security principal is deleted, this SID can't be reused. When a user logs in, the system creates a token containing their SID, rights, SIDs of their groups. This token is used to check the user's rights when performing an action. There are also well-known SIDs that are used to identify generic users and groups. These are the same across all operating systems. An example is the Everyone group.
- DN (Distinguished Name) : Full path of an object in AD (like LDAP), like " cn=bjones, ou=IT, ou=Employees, dc=inlanefreight, dc=local". Must be unique in their directory.
- RDN (Relative DN) : A DN is made of multiple RDNs (cn=bjones is an RDN). RDNs must be unique in their OU.
- sAMAccountName : user's logon name. Must be unique and < 20 characters : johnsmith for example.
- userPrincipalName : another way to identify a user in AD. has a prefix (account name) and suffix (domain). eg johnsmith@themmatrix.local
- Global Catalog (GC) : a DC that stores copies of ALL objects in the forest (full copy in their domain, partial with the rest of the forest). Standard domain controllers hold a complete replica of objects belonging to its domain but not those of different domains in the forest. GC allows finding info about any object in any domain of the forest. Must be enabled on the DC and allows authentication and object search.
- Read-Only DC (RODC) : An RODC has an AD database, but no AD account passwords are cached on it. No changes can be pushed through it, its SYSVOL, or DNS. They also are Read-Only DNS.
- Replication : happens in Ad when AD objects are updated and transferred.When a DC is added, connection objects are added by the KCC (Knowledge Consistency Checker - present on all DC) service to handle replication.
- Service Principal Name (SPN) : uniquely identifies a service instance. Used by kerberos for service to logon account association.
- GPO (Group Policy Object) : virtual collection of policy settings. Each GPO as a GUID. Can contain local or AD settings, can be applied to users or computers, or defined by OU.
- ACL : Collection of Access Control Entities (ACEs) that apply to an object
- ACE : identifies a trustee (user, group, logon session) and lists access rights that are allowed, denied, audited for the given trustee.
- Discretionary Access Control List (DACL) : DACLs define which security principles are granted or denied access to an object; it contains a list of ACEs. When a process tries to access a securable object, the system checks the ACEs in the object's DACL to determine whether or not to grant access. If an object does NOT have a DACL, then the system will grant full access to everyone, but if the DACL has no ACE entries, the system will deny all access attempts. ACEs in the DACL are checked in sequence until a match is found that allows the requested rights or until access is denied.
- SACL (System ACL) : Allows admins to log access attempts made to secure objects. ACEs specify the type of atttempts that are to be recorded.
- FQDN : Same as with DNS.
- Tombstone : AD Container holding deleted objects. A deleted object remains for a period know as "Tombstone Lifetime", with its isDeleted attribute set to TRUE. After that it is deleted. Generally between 60-180 days.If an object is deleted in a domain that does not have an AD Recycle Bin, it will become a tombstone object. When this happens, the object is stripped of most of its attributes and placed in the Deleted Objects container for the duration of the tombstoneLifetime. It can be recovered, but any attributes that were lost can no longer be recovered.
- AD Recycle Bin : First introduced in Windows Server 2008 R2 to facilitate the recovery of deleted AD objects. When the AD Recycle Bin is enabled, any deleted objects are preserved for a period of time, facilitating restoration if needed. Sysadmins can set how long an object remains in a deleted, recoverable state. If this is not specified, the object will be restorable for a default value of 60 days. The biggest advantage of using the AD Recycle Bin is that most of a deleted object's attributes are preserved.
- SYSVOL : The SYSVOL folder, or share, stores copies of public files in the domain such as system policies, Group Policy settings, logon/logoff scripts, and often contains other types of scripts that are executed to perform various tasks in the AD environment. The contents of the SYSVOL folder are replicated to all DCs within the environment using File Replication Services (FRS).
- AdminSDHolder : This object is used to manage ACLs for members of built-in groups in AD marked as privileged. It acts as a container that holds the Security Descriptor applied to members of protected groups. The SDProp (SD Propagator) process runs on a schedule on the PDC Emulator Domain Controller. When this process runs, it checks members of protected groups to ensure that the correct ACL is applied to them. It runs every hour by default
- dsHeuristics : string value set in the Directory Service object used to define multiple forest-wide configuration settings. One of these settings is to exclude built-in groups from the Protected Groups list. Groups in this list are protected from modification via the AdminSDHolder object. If a group is excluded via the dsHeuristics attribute, then any changes that affect it will not be reverted when the SDProp process runs.
- adminCount : attribute determining wether or not the SDProp process protects a user. If 0 or unspecified, the user is not protected.
Attackers often look for accounts with adminCount to 1 as a target.
- AD Users and Computers (ADUC) : GUI Console used for AD management (users, groups, computers, contacts). Can be replaced by Powershell commands.
- ADSI Edit : GUI tool used to manage objects in AD. More complete than ADUC, can be used to manipulate attributes, and manipulate objects. Use with caution !
- sIDHistory : attribute holding any SID that an object received in the past. Usually used in migrations so a user can maintain the same level of access when migrated from one domain to another. This attribute can potentially be abused if set insecurely, allowing an attacker to gain prior elevated access that an account had before a migration if SID Filtering (or removing SIDs from another domain from a user's access token that could be used for elevated access) is not enabled.
- NTDS.DIT : The NTDS.DIT file can be considered the heart of Active Directory. It is stored on a Domain Controller at C:\Windows\NTDS\ and is a database that stores AD data such as information about user and group objects, group membership, and, most important to attackers and penetration testers, the password hashes for all users in the domain. Once full domain compromise is reached, an attacker can retrieve this file, extract the hashes, and either use them to perform a pass-the-hash attack or crack them offline using a tool such as Hashcat to access additional resources in the domain. If the setting Store password with reversible encryption is enabled, then the NTDS.DIT will also store the cleartext passwords for all users created or who changed their password after this policy was set. While rare, some organizations may enable this setting if they use applications or protocols that need to use a user's existing password (and not Kerberos) for authentication.
- MSBROWSE : Microsoft Networking Protocol used in early versionof Windows-based LANs. It was used maintain a list of resources available on the network. Today, MSBROWSE is largely obsolete and is no longer in widespread use. Modern Windows-based LANs use the Server Message Block (SMB) protocol for file and printer sharing, and the Common Internet File System (CIFS) protocol for browsing services.
FSMO roles
When having mutliple DCs, they used to fight over which one makes changes, which was an issue. Then Microsoft implemented the system of having a master DC that made all the changes, which solved it but was a SPOF. To resolve it, they introduced Flexible Single Master Operation roles. They allow DCs to continue authenticating users and grant permissions without interruption. There are 5 roles:
- Domain Naming Master and Schema Master (1 of each per forest)
- Relative ID (RID) Master, 1 per domain
- Primary Domain Controller (PDC) Emulator, 1 per domain
- Infrastructure Master, 1 per domain.
These roles are assigned to the first DC in the forest root in a new forest. Each time a new domain is added to a forest, only the RID master, PDC emulator and Infra Master are assigned to the new domain. These roles help replication in AD run smoothly and ensure that critical services are operating. They can be transferred as needed. More on them later.
Objects
Users
Leaf objects, they can't contain anything else; they represent real people. Another object of a leaf object is a mailbox. A user is a Security Principal and has an SID and a GUID. They may have many possible attributes : display name, last login time, email, etc. There can be more than 800 : see [ https://www.easy365manager.com/how-to-get-all-active-directory-user-object-attributes/ here]. Usually way less, but shows AD's complexity. Users a crucial target.
Contacts
Usally used to represent a user outside of our org. Contains their name, email address, telephone number, etc. Leaf objects but NOT security Principals, so no SID (only GUID).
Printers
Points to a printer on the network. Leaf object, not a security Principal, only a GUID. Have attributes such as name, driver information, etc.
Computers
Represents any computer joined to the AD network (server or workstation). Leaf object. Are security Principals : have an SID and GUID. Like users, they are prime targets since full adminstrative access to a computer (as the all powerful NT AUTHORITY\SYSTEM account) allows to act a standard user and can do mostly the same enumeration.
Points to a shared folder on the specific computer where the folder resides. Shared folders can have stringent access control applied to them and can be either accessible to everyone (even those without a valid AD account), open to only authenticated users (which means anyone with even the lowest privileged user account OR a computer account (NT AUTHORITY\SYSTEM) could access it), or be locked down to only allow certain users/groups access. Anyone not explicitly allowed access will be denied. They are NOT Securoty Principals.
Groups
A group is a container object. They can contains users, computers, other groups. A group IS a Security Principal and has an SID and a GUID. Used to manage permissions and access to other securable objects. Nested group are a common way to have unintended rights and is often leveraged during pentesting. The tool "Bloodhound" illustrates them in a graphical manner, since it's sued to discover attack paths. Groups have many attributes.
Organizational Unit
A container that admins use to store similar objects for ease of management. Often used for administrative delegation of tasks without granting full administrative rights. Nested OUs allow easy management : if I have the rights on an OU, I have rights on its children.
Domain
Structure of an AD network. They contain leaf objects organized in container objects. Every domain has its own separate database and sets of policies that can be appled to any / all objects in the domain. Some policies are default such as the domain password policy.
Domain Controller
They are the brain of an AD network. Handle auth requests, verify users on the network, control access to various resources. All access requests are validated via the domain controller and privileged access requests are based on predetermined roles assigned to users. It also enforces security policies and stores information about every other object in the domain.
Sites
A set of computers across one or more subnets connecting via fast links. Used for efficient replication. (Think of a site == a datacenter).
Built-in
Container holding all default groups of the domain. Predefined at domain creation.
Foreign Security Principals (FSP)
Object created in AD to represent a security principal that belongs to a trusted external forest. Created when a user, computer, group from another forest is added to the current domain. Created automatically after adding a security principal to a group. Every Foreign security Principal is a placeholder holding the SID of the foreign object. Windows uses this SID to resolve the object's name via the trust relationship. FSPs are created in a specific container named ForeignSecurityPrincipals with a distinguished name like cn=ForeignSecurityPrincipals,dc=inlanefreight,dc=local.
Functionnality
FSMO
The FSMO roles can be defined as such:
- Schema Master : Manages read / write on the AD schema.
- Domain Naming Master : Manages domain names and avoids having 2 of the same name on its domain.
- Relative ID (RID) master : Assigns blocks of RIDs to other DCs in the domain so they can assign them, and makes sure RIDs are uniquely assigned. Domain SIDs are the domain SID combined with object's RID.
- PDC Emulator : Authoritative DC responding to auth requests, password changes, GPO management, and NTP.
- Infrastructure Master : Translates GUIDs, SIDs, DNs between domains. Used when having multiple domains in a single forest. If this role is not properly functionnal, ACLs will show SIDs instead of names.
Issues with FSMO lead to authentication and authorization problems in a domain.
Domain and Forest functionnal level
Functional levels determine the level of features available in ADDS at domain and forest level. Also define the WinServ version a server must have to be a DC.
The Microsoft documentation has more details.
Trusts
A trust is an established forest-forest or domain-domain authentication, allowing users access to resources. A trust creates a link in the authentication system between 2 domains. There are several trust types:
- Parent-child : Domains within a forest. The child trusts the parent in a "two-way transitive" trust - parent and child trust each other for authentication (2-way) and if the child domain trusts something, parent does too (transitive).
- Cross-link : a trust between child domains to speed up authentication.
- External : Non transitive trust between 2 domains from 2 non-joined forests. Uses SID filtering.
- Tree-root : Two way transitive trust between a forest root domain and new tree root domain. Created by design when adding a new tree root domain.
- Forest : Transitive trust between 2 forest root domains.
Example :
Improperly set up trusts often offer an attack path. Trusts set up for ease of use tend to be forgotten, and not reviewed later for security implications. Mergers and acquisition can lead to bidirectional trusts with acquired organizations, introducing risks.
Protocols
AD requires a few protocols to operate : kerberos, ldap, dns, and msrpc.
Kerberos
Uses port 88/TCP and 88/UDP. Scanning for it is a good way to find DCs in a domain.
It is the default authentication protocol since Windows 2000. An open standard. It implements mutual auth : the user and the server each prove their identity.
Kerberos is stateless and based on tickets - instead of transmitting user passwords on the network. As part of ADDS, DCs have a Kerberos Key Distribution Center (or KDC) that issues tickets. The goal is to decouple user credentials from their requests, ensuring no password is transmitted on the network. The KDC does not keep previous authentications in memory. The procedure is as follows :
- The user emits an Authentication Service Request (AS-REQ) to the KDC, encrypting it with their password.
- The KDC checks the AS-REQ with the DC. If OK, it send back a Ticket Granting Ticket or TGT, encrypted with the user's password NTLM hash.
- The user presents the TGT to the DC, asking for access to a service, which is materialized by a TGS-REQ (Ticket Granting Service Request). If the TGS is valid, its data is copied to the TGS.
- The TGS is encrypted with the NTLM passw hash of the service or computer account the user is trying to access, and is then delivered to the user in TGS_REP.
- The user presents the TGS to the service, and if valid, is permitted to connect (AP_REQ).
DNS
DNS particularities in AD : AD maintains a Database of services in the network in the form of Service Records in its DNS (SRV records). They allow AD clients to locate the services they need : file server, printer, DC, etc. Dynamic DNS is used to automate IP changes. The SRV records are what is used by the client to retrieve by a client coming into an AD network to locate a DC. An example with dig :
justine@~ > dig _ldap._tcp.dc._msdcs.SMTH.LOCAL -t srv [...] ;; ANSWER SECTION: _ldap._tcp.dc._msdcs.AUTH.LOCAL. 600 IN SRV 0 100 389 ad5auth.auth.local. _ldap._tcp.dc._msdcs.AUTH.LOCAL. 600 IN SRV 0 100 389 ad4auth.auth.local. [...]
MSRPC
MSRPC is Microsoft's implementation of RPC, Remote Procedure Call. RPC is an interprocess communication technique used in client-server applications. Windows systems use MSRPC to access systems in AD using 4 key RPC interfaces :
- lsarpc : LSA is Local Security Authority - a system that manages local security policies and audit policies on a computer. LSARPC is used to do management tasks on domain security policies.
- netlogon : Used to authenticate users and other services in the domain environment. Service that continuously runs in the background.
- samr : Remote SAM. Provides management functionnality for the domain account database, storing info about users and groups. Sysadmins use it to manage users, groups, computers by enabling admins to create, read, update, delete info about security principles. Samr can be used by attackers to recon the internal domain by using tools such as BloodHound - which creates a visual map of the AD network and its "attack paths". By default, all authenticated users can make samr queries and access all info - a behaviour that can be limited to admins by changing a registry key.
- drsuapi : Microsoft API that implements the Directory Replication Services (DRS) Remote Protocol - used for replication related things across DCs. Can be used by attackers to create a copy of the AD domain database (NTDS.dit) to retrieve password hashes. These hashes can then be used in pass-the-hash attacks or cracked offline.
NTLM authentication
Aside from Kerberos and LDAP, AD uses other authentication methods : LM, NTLM, NTLMv1 and v2. LM and NTLM are the hash names, and NTLMv1 and v2 auth protocols using the LM or NT hash. The below comparison shows that kerberos is often the best protocol, even if it's not perfect.
LM
Lan Manager (LM or LANMAN) hashes are the oldest password storage used by Windows, having debuted in 1987 on OS/2. If used, they are stored in the SAM database and NTDS.DIT db on a DC. Turned off by default since Vista due to security concerns - but can still be found on dinosaurs today ! Passwords using LM are limited to 14 characters, not case sensitive because they are considered uppercase. This hash is easy to crack.
Hash process : if < 14 characters, fill the password with NULLs. Split it in two chunks of 7 chars. 2 DES keys are created for each chunk. These chunks are then encrypted using the string "KGS!@#$%", creating 2 8-byte ciphertext values which are concatenated together, giving us an LM hash.An LM hash can be cracked by attacking 2 7-char strings instead of one of 14 which can be quick using a GPU and Hashcat. A password < 7 chars will always have the same second half which can be easily determined visually.
The use of LM hashes can be turned off via a GPO.
NTHash (NTLM)
New Technology Lan Manager (NTLM) hashes are used on modern Windows Systems. It is a challenge-response protocol that uses 3 messages to authenticate :
- Client sends NEGOCIATE_MESSAGE to the server
- Server send CHALLENGE_MESSAGE to the client
- Client send AUTHENTICATE_MESSAGE to the server
These hashes are stored in the SAM database or NTDS.DIT. The protocol has 2 possible hashes for the password : LM hash (see above), or NT hash. NT hash is the MD4 hash of the little-endian UTF-16 value of the password. The algo can be visualized as : MD4(UTF-16-LE(password)).
NT hashes are way stronger than LM, because thanks to UTF-16 (which stores unicode code points on at least 2 bytes each) it has access to all 65536 characters of unicode. But they can still be attacked : GPU attacks show that the entire NTLM 8-character-keyspace can be brute-forced in under 3 hours. Longer hashes can be challenging to crack, but can still be bruteforced with an offline dictionnary attack and rules. NTLM is also vulnerable to pass-the-hash, which means an attacker only needs the NTLM hash to authenticate to target systems.
An NT hash takes the form of b4b9b02e6f09a9bd760f388b67351e2b, which is the second half of the full NTLM hash. An NTLM hash looks like this:
Rachel:500:aad3c435b514a4eeaad3b935b51304fe:e46b9e548fa0d122de7f59fb6d48eaa2:::
- Rachel is the username
- 500 is the RID - 500 being the known RID for the admin account
- e46b... is the NT hash.
An example of a successful pass-the-hash using CrackMapExec:
squi@htb[/htb]$ crackmapexec smb 10.129.41.19 -u rachel -H e46b9e548fa0d122de7f59fb6d48eaa2 SMB 10.129.43.9 445 DC01 [*] Windows 10.0 Build 17763 (name:DC01) (domain:INLANEFREIGHT.LOCAL) (signing:True) (SMBv1:False) SMB 10.129.43.9 445 DC01 [+] INLANEFREIGHT.LOCAL\rachel:e46b9e548fa0d122de7f59fb6d48eaa2 (Pwn3d!)
IMPORTANT note : Neither NTLM or LM use a salt...
NTLMv1
TODO