# Directory Service

## **Directory Service and LDAP**

**Directory Service** is a specialized database that stores information about objects on a network, such as users, computers, printers, and other resources. It provides centralized management of these objects, as well as their authentication and authorization.

Some examples of directory services:

* **Active Directory (AD)** - the most common directory service from Microsoft.
* OpenLDAP - an open-source implementation of an LDAP server, often used in Linux environments.
* FreeIPA - a solution based on OpenLDAP.
* **Azure Active Directory (Azure AD, now Microsoft Entra ID)** – a cloud service from Microsoft, integrated with on-premises AD.

Directory services typically use the **LDAP (Lightweight Directory Access Protocol)** protocol to access data.

**LDAP (Lightweight Directory Access Protocol)** is a protocol for accessing directory services. It allows clients to request and modify data stored in the directory, such as information about users, groups, computers, and other objects.

**Key LDAP Components**

1. **Objects**:
   * Each element in the directory (user, group, computer) is represented as an object.
   * Objects have a unique identifier (DN — Distinguished Name).
2. **Distinguished Name (DN)**:
   * A unique path to an object in the directory.
   * Example: `cn=JohnDoe,ou=Users,dc=example,dc=com` — the "JohnDoe" object in the "Users" organizational unit of the "example.com" domain.
3. **Attributes**:
   * Objects consist of attributes that store information (e.g., `cn` — common name, `mail` — email address).
   * Different object types have different attributes.
   * To get a complete list of attributes for an LDAP object (e.g., user, group, or computer) from Active Directory, you can use the following commands:

     ```
     Get-ADObject -Identity "DN_object" -Properties *
     ```
4. **Schema**:

   * Defines the types of objects and their attributes.
   * For example, the schema might specify that a "user" object must have `cn`, `mail`, and `uid` attributes.
   * To get a list of all possible attributes in the Active Directory schema:

   <pre><code><strong>Get-ADObject -SearchBase (Get-ADRootDSE).schemaNamingContext -Filter {objectClass -eq "attributeSchema"} -Properties * | Select-Object name, lDAPDisplayName
   </strong></code></pre>

Attackers use the LDAP protocol for reconnaissance and searching for vulnerabilities, such as weak access rights or incorrectly configured objects.

Popular tools: **BloodHound, ldapsearch, AD Explorer, Powerview**. Also, information from the domain can be obtained using built-in Windows utilities: the ActiveDirectory PowerShell module, and `net.exe`.

{% hint style="info" %}
BloodHound/SharpHound is a powerful tool for analyzing Active Directory domains, which helps attackers (and defenders) visualize the relationships between domain objects and find paths for privilege escalation.
{% endhint %}

## Active Directory Domain

A domain is a logical group of computers, users, and other objects that are centrally managed by a directory service, such as Active Directory.

Key domain elements that are important for understanding its structure and functioning.

**Domain Controllers (DC)** - servers that manage the domain and store the Active Directory database.

**Key functions**:

* User authentication. ([**Kerberos**](/blue-team-cookbook/en/a-d/kerberos.md) — authentication protocol)
* Storing information about domain objects. (**LDAP** — directory access protocol)
* Replicating data between domain controllers. (Replication mechanisms are used for DCShadow and DCSync attacks).

The primary domain controller usually also hosts the DNS server for name resolution.

{% content-ref url="/pages/5JnNh2aJfEcLA8EPrSQk" %}
[DNS and Name Resolution](/blue-team-cookbook/en/other/dns.md)
{% endcontent-ref %}

### Master Controllers and FSMO Roles

Domain controllers in Active Directory (AD) are generally equal participants in replication and can perform the same functions, including writing and changing data in the AD database. This model is called multimaster replication, where each domain controller can make changes that are then replicated to other controllers.

However, AD has operations that cannot be performed simultaneously on multiple domain controllers to avoid conflicts. For these tasks, special roles – FSMO (Flexible Single Master Operations) – are assigned to unique domain controllers in the forest or domain. There are five such roles:

* Schema Master - manages changes to the **Active Directory schema** (e.g., adding new attributes). Only a DC with this role can change the schema.
* Domain Naming Master - controls the creation and deletion of domains in the forest.
* Infrastructure Master - is responsible for updating links between domains (e.g., if a user from one domain is added to a group in another domain).
* RID Master - generates **RID** (Relative Identifiers) for new objects (users, groups, computers). Cannot create new objects without it.
* PDC Emulator - is responsible for time, passwords, account lockouts, and GPOs.

FSMO roles can be transferred to another controller. Or seized.

| **Action**              | **When to use**                                      | **Risks**                                         |
| ----------------------- | ---------------------------------------------------- | ------------------------------------------------- |
| **Transfer** (transfer) | If the old DC is **available** and functioning.      | Safe.                                             |
| **Seize** (seize)       | If the old DC is **unavailable** (e.g., burned out). | **Requires deleting the old DC from the domain!** |

Active Directory **does not provide automatic seizure of FSMO roles**. This is done manually to prevent conflicts. It can be done via PowerShell (requires the AD module):

```
Move-ADDirectoryServerOperationMasterRole -Identity "NEW-DC" -OperationMasterRole PDCEmulator, RIDMaster, InfrastructureMaster, SchemaMaster, DomainNamingMaster -Force
```

The `-Force` key performs a **seize**, not a transfer.

### SYSVOL, NETLOGON, NTDS

In Active Directory (AD), there are several system folders that play a key role in the operation of the domain. They store critical data, such as Group Policy Objects (GPOs), login scripts, authentication services, and replication.

**SYSVOL** (`\\<domain>\SYSVOL\<domain>\`) **-** A network folder that is replicated between all domain controllers. It stores Group Policy Objects (GPOs) in XML format, login/logout scripts, and other domain-wide files (e.g., configuration files for all computers in the domain).

Many administrators store passwords in GPOs (e.g., for automatic configuration of services). These passwords can be extracted.

If an attacker gains write access to `SYSVOL`, they can replace `logon.bat` and execute code on all domain computers.

**NETLOGON** (`\\<domain>\NETLOGON\` or `C:\Windows\SYSVOL\sysvol<domain>\SCRIPTS`) **-** A network folder used to store domain logon scripts (`Logon Scripts`) that are executed when a user logs in to the system. **Available to all authenticated users** by default.

An attacker can search for passwords in scripts.

**NTDS** (`C:\Windows\NTDS`) - stores: The AD database, all domain objects (users, groups, computers), Transaction log files **(`edb*.log`)** – for data integrity. Kerberos ticket cache (if caching is enabled).

An attacker with replication rights can dump all password hashes of all domain users.

{% content-ref url="<https://github.com/Vasilisa-L/blue-team-cookbook/blob/main/en/ad/domain-takeover.md>" %}
<https://github.com/Vasilisa-L/blue-team-cookbook/blob/main/en/ad/domain-takeover.md>
{% endcontent-ref %}

## **Users**

Accounts that represent individuals or services. Users can be regular or privileged (e.g., members of the "Domain Admins" or "Enterprise Admins" groups).

* **Key attributes**:
  * `sAMAccountName` — user login.
  * `userPrincipalName` (UPN) — unique identifier (e.g., `user@domain.com`). Also used for service accounts SPN.
  * `memberOf` — groups the user belongs to.

<details>

<summary>SPN (<strong>Service Principal Name</strong>)</summary>

**SPN** is a unique identifier that links a service (e.g., SQL Server, IIS) to the account under which it runs in the domain. SPN is used in the Kerberos protocol for service authentication. Example SPN: `MSSQLSvc/sqlserver.example.com:1433`.

SPN indicates what services exist in the domain, what accounts are used to run services (e.g., SQL Server, Exchange).

Also SPN is used for Silver Ticket attacks (see [Kerberos](/blue-team-cookbook/en/a-d/kerberos.md) for more details).

</details>

**What is interesting to the attacker:** Privileged accounts (e.g., members of the "Domain Admins" group). Analyzing group membership to find paths for privilege escalation. Searching for inactive or outdated accounts that may be compromised (Information about last login (`lastLogon`) and password change (`pwdLastSet`)).

## **Computers**

Accounts representing computers joined to the domain.

* `sAMAccountName` — computer name (ends with `$`, e.g., `PC01$`).

**What is interesting to the attacker:** Information about delegation settings, such as **Unconstrained Delegation**, **Constrained Delegation**, and **Resource-Based Constrained Delegation.** Information about computers that use LAPS. Attributes related to LAPS, such as `ms-Mcs-AdmPwd`.

<details>

<summary>LAPS (Local Administrator Password Solution)</summary>

**LAPS** is a Microsoft solution for managing local administrator passwords on computers in a domain. It automatically generates unique, strong passwords for local administrator accounts on each computer and stores them in Active Directory (AD). This simplifies password management and improves security, as passwords are changed regularly.

**How LAPS works**

1. **LAPS Installation**:
   * LAPS consists of two components: a client part (installed on computers) and a server part (installed on domain controllers).
   * The client part is responsible for generating and changing passwords.
   * The server part stores passwords in attributes of computer objects in AD.
2. **Password Generation**:
   * LAPS automatically generates strong passwords for the local administrator account on each computer.
   * Passwords are changed at regular intervals (default is every 30 days).
3. **Password Storage**:
   * Passwords are stored in attributes of the computer object in Active Directory.
   * These attributes are protected by ACLs so that only authorized users or groups can read the passwords.
4. **Password Retrieval**:
   * Administrators can use tools such as **LAPS UI** or PowerShell to retrieve the local administrator password for a specific computer.

**LAPS Attributes in LDAP Objects**

LAPS uses two main attributes in computer objects to store password information:

1. **ms-Mcs-AdmPwd**:
   * This attribute stores the current local administrator password in plain text.
   * **Important**: This attribute is only accessible to users or groups that have been explicitly granted read permissions.
2. **ms-Mcs-AdmPwdExpirationTime**:
   * This attribute stores the expiration time of the current password.
   * **Example value**: `132558739200000000` (this value represents the date and time in FILETIME format).
   * Used to determine when the password should be changed.

***

If access rights to LAPS attributes are not configured correctly, an attacker can gain access to passwords. If an attacker gains access to the `ms-Mcs-AdmPwd` attribute, they can obtain the local administrator password for the computer.

</details>

## **Groups**

Collections of users, computers, or other groups that simplify access rights management.

* **Group types**:
  * **Security Groups** — used to manage access to resources.
  * **Distribution Groups** — used for sending messages (e.g., email lists).
* **Examples of groups**:
  * **Domain Admins** — full control over the domain.
  * **Enterprise Admins** — full control over all domains in the forest.
  * **Domain Users** — all domain users.

**What is interesting to the attacker:** Groups with high privileges (e.g., "Domain Admins", "Enterprise Admins"). Groups that have dangerous rights to other objects (e.g., the right to modify membership in other groups). Users who can be added to privileged groups.

### Dangerous Object Rights

In Active Directory (AD), object rights define what actions users or groups can perform on specific objects. These rights are defined through **ACL (Access Control List)** — access control lists that are attached to each object.

* **Dangerous rights**:
  * **GenericAll**: Gives full control over the object, including changing attributes, adding to groups, and deleting the object. An attacker can change a user's password, add themselves to privileged groups, or delete an object.
  * **GenericWrite**: Allows you to change the attributes of the object, but does not give full control. Can be used to change group membership or other attributes, which allows you to escalate privileges.
  * **WriteDACL**: Allows you to change the access control list (ACL) of the object. An attacker can change the access rights to the object, granting themselves additional privileges.
  * **WriteOwner**: Allows you to change the owner of the object. An attacker can become the owner of the object and then change its ACL or other attributes.
* **Examples of exploitation**:
  * **GenericAll on the "Domain Admins" group**:
    * An attacker can add themselves to the "Domain Admins" group and gain full control over the domain.
  * **WriteDACL on a user object**:
    * An attacker can change the ACL of a user, granting themselves the `GenericAll` right, and then change the user's password.
  * **WriteOwner on a computer object**:
    * An attacker can become the owner of a computer object, change its ACL, and then use it for attacks.
  * **GenericWrite on the "IT Support" group**:
    * An attacker can add themselves to the "IT Support" group, which has access to critical resources.

## **Organizational Units (OU)**

Containers for grouping objects (users, groups, computers) in a domain.

* **Why are they needed**:
  * Simplify object management.
  * Applying Group Policy Objects (GPOs) to specific groups of objects.
* **Example**:
  * `OU=Sales,DC=example,DC=com` — organizational unit for the sales department.

## **Group Policy Objects (GPO)**

Group Policies are used to centrally manage user and computer settings in a domain.

They allow, for example, to restrict access to certain functions of the operating system, configure security settings, or automatically install software.

GPOs can be linked to the domain, site, or organizational unit (OU).

**What is interesting to the attacker:** Searching for weak security settings in GPOs.

Policies that can be used to distribute malware or escalate privileges. An attacker with rights to edit GPOs can add a **local administrator** to all computers, implement a **persistent backdoor** (through autorun), disable protection (e.g., Defender), and much more.

Administrators often store passwords in GPO settings (e.g., for automatic mapping of network drives or launching services). These passwords are stored in encrypted form in files like `Groups.xml`, `Services.xml`, and others, but **the encryption key is known** (AES-256 with a fixed key `MS-SAM`). Attackers can extract these passwords using tools like **Get-GPPPassword**.

### **Tools for exploiting GPO**

| Tool                              | Description                               |
| --------------------------------- | ----------------------------------------- |
| **SharpGPOAbuse**                 | Deploying malicious settings through GPO. |
| **PowerSploit (Get-GPPPassword)** | Extracting passwords from GPO.            |
| **Grouper2**                      | Analyzing GPO for vulnerabilities.        |

## **Forest and Tree**

* **Forest** - the highest level of logical structure in AD, consisting of one or more **domains** united by common:

  * **Schema** — defines the types of objects (users, computers, etc.).
  * **Configuration** — settings for sites, replication.
  * **Global Catalog** — contains partial information about all objects in the forest.

  **Each forest has a unique name** (e.g., `contoso.com`).
* **Tree** - A hierarchy of domains that share a common root domain name (e.g., `example.com` and `sales.example.com`). All domains in the tree automatically **trust each other** (two-way transitive trusts).

### **Trust Relationships**

Mechanisms that allow domains to interact with each other. For example, users from domain A can access resources in domain B if a trust relationship is established between them.

* **Types of trust**:
  * **One-way** — one domain trusts another, but not vice versa.
  * **Two-way** — both domains trust each other.
  * **Transitive** — trust extends to other domains in the forest.

**What is interesting to the attacker:** Searching for ways to move between domains (e.g., using transitive trust). Searching for domains that trust the current domain for attacks such as **SID History.**

<details>

<summary>SID-History Attack</summary>

**SID-History** is an attribute of user objects in Active Directory (AD) that is used to migrate users between domains. It allows you to preserve old security identifiers (SIDs) of a user to maintain access to resources in the old domain after migration. However, this attribute can be used by attackers to escalate privileges in the domain.

**When is it possible?**

* SID Filtering is disabled
* There are domains with trust relationships

**How does it work?**

* When a user authenticates, the system checks not only their current groups, but also the SIDs specified in the `SID-History` attribute.
* If \`SID-History contains the SID of a privileged group, the system grants the user the corresponding rights.

**Attack steps**:

* The attacker gains access to an account with rights to change the `SID-History` attribute (e.g., using the **WriteProperty** or **GenericAll** right).
* The attacker adds the SID of a privileged group (e.g., "Domain Admins") to the `SID-History` attribute of their account.
* After that, the attacker gains access to resources available to that group.

</details>

## Monitoring

### **Event ID 1644**

To detect reconnaissance in the domain (without binding to a specific tool), monitoring LDAP queries (**Event ID 1644**) or LDAP traffic will help. Pay special attention to requests for specific LDAP attributes related to delegation, LAPS, SPN, and the certificate service. Also, pay attention to massive downloads of objects from the directory service (but such rules can generate many False Positives), as some domain-authenticated services also obtain information about users, their groups, and rights.

### **Event ID 5136**

**Event ID 5136** will help track object changes. Such as SID-History, GPO changes, delegation settings, Shadow Cred, and many others.

Interesting LDAP attributes to monitor for changes: [\[Cheat Sheet\] Interesting LDAP Attributes](/blue-team-cookbook/en/a-d/directory-service/top-ldap-attributes.md)

{% embed url="<https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=5136>" %}

### Sysmon 11

This event will help track the creation or modification of files in SYSVOL or NETLOGON.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://vasilisa-l.gitbook.io/blue-team-cookbook/en/a-d/directory-service.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
