---
title: "17. LDAP"
date: 2025-01-20
draft: false
---

**Lightweight directory access protocol**
Protocol for managing and accessing directory information. 
Directory = hierarchical data store - containing information about users, groups, computers, and printers

Efficient, global naming model, extensible and flexible, compatible with many other software products, platform independent, and provides authentication mechanisms that enable users to sign on once to access multiple resources on the server securely 

Some significant issues: 
Compliance - Dir servers must be LDAP compliant for svc to be deployed - limiting choice of vendors and products. 
Complexity - difficult to use and understand for many devs and admins, who may not know how to config ldap clients securely
Encryption - LDAP does not encrypt its traffic by default - exposing sensitive data to potential eavesdropping and tampering (LDAPS or STartTLS must be used to enable encryption) 
Injection - Vulnerable to ldap injection attacks, where malicious users can manipulate LDAP queries and gain unauth access to data/resources
- To prevent: Input validation and output encoding must be implemented. 


---
LDAP is **commonly used** for providing a **central location** for **accessing** and **managing** directory services.
- Dir svcs: collections of info about:
	- The org
	- its users
	- assets - usernames, passwords
- LDAP enables org to store/manage/secure this info in a standardised way. 

|**Use Case**|**Description**|
|---|---|
|`Authentication`|LDAP can be used for `central authentication`, allowing users to have single login credentials across multiple applications and systems. This is one of the most common use cases for LDAP.|
|`Authorisation`|LDAP can `manage permissions` and `access control` for network resources such as folders or files on a network share. However, this may require additional configuration or integration with protocols like Kerberos.|
|`Directory Services`|LDAP provides a way to `search`, `retrieve`, and `modify data` stored in a directory, making it helpful for managing large numbers of users and devices in a corporate network. `LDAP is based on the X.500 standard` for directory services.|
|`Synchronisation`|LDAP can be used to `keep data consistent` across multiple systems by `replicating changes` made in one directory to another.|
Two popular implementations of LDAP:
**OpenLDAP**
- Opensource widely used + supported 
**Microsoft Active Directory**
- windows-based implementation seamlessly integrates into other microsoft products and services

LDAP and AD are RELATED but they serve different purposes. LDAP is a **protocol** , that specifies the method of accessing and modifying directory services. 
**AD** is a **directory service** that stores+manages user and computer data. 
- While LDAP can communicate with AD (and other directory services) it is not a directory service itself. 
- AD offers extra functionalities such as policy administration, single sign-on, and integration with various MS products. 

LDAP works by using a client-server architecture. 
- Client sends LDAP req to a server - 
	- Server searches directory service and returns response to client.
- LDAP protocol is simpler + more efficient than X.500 on which it is based. 
- Client requests send LDAP msgs encoded in ASN.1 (Abstract Syntax Notation One) and transmitted over TCP/IP 
- Servers process the req and send back msgs using the same format. LDAP supports various requests 
	- Bind
	- Unbind
	- Search
	- Compare
	- Add
	- Delete
	- Modify

LDAP reqs are messages client send to servers to perform operations on data stored in the directory service. LDAP request is comprised of several components. 
**Session connection**
- Client connects to server via ldap port (389, 636)
**Request type**
- Above - bind, search etc 
**Request parameters**
- Client provides add'tl info for request such as `distinguished name` (DN) of entry to be accessed or modified - scope/filter of search query - attributes and values to be added or changed etc
**Request ID**
- client assigns unique id to each req and match it with corresponding response from server

Once server received requst it processes it and sends back a response 
**Response type** - Indicates operation was performed in response to req
**Result code** - success and why 
**Matched DN** - If applicable - server returns DN of closest existing entry that matches request
**Referral** - Server returns URL of another server that may have more info about req, if applicable
**Response data** - any add'tl data related to response such as attributes/values of entry that was searched or modified 

---
`ldapsearch` is a cmdline util used to search for info stored in a dir using ldap protocol. commonly used to query and retrieve data from an LDAP dir svc 

```shell-session
ldapsearch -H ldap://ldap.example.com:389 -D "cn=admin,dc=example,dc=com" -w secret123 -b "ou=people,dc=example,dc=com" "(mail=john.doe@example.com)"
```

broken down: 
- connect to ldap.example.com on 389 
- bind (authenticate) as cn=admin,dc=example,dc=com with password secret123
- search under base DN `ou=people,dc=example,dc=com` 
- use filter `mail=john.doe@example` to find entries with that email 

server would process the request and send back a response like this: 

```ldap
dn: uid=jdoe,ou=people,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: John Doe
sn: Doe
uid: jdoe
mail: john.doe@example.com

result: 0 Success
```

response includes entry's distinguished name (DN) that matches search criteria and its attributes and values 

---
## LDAP Injection 

Exploits web applications that use LDAP for auth or storing user information. 
Attackers can inject malicious code or characters into LDAP queries to alter application behavior, bypass security measures, and access sensitive data stored in the LDAP directory
To test for LDAP injection you can use input values that contain `special characters or operators` that can change query's meaning: 

|Input|Description|
|---|---|
|`*`|An asterisk `*` can `match any number of characters`.|
|`( )`|Parentheses `( )` can `group expressions`.|
|`\|`|A vertical bar `\|` can perform `logical OR`.|
|`&`|An ampersand `&` can perform `logical AND`.|
|`(cn=*)`|Input values that try to bypass authentication or authorisation checks by injecting conditions that `always evaluate to true` can be used. For example, `(cn=*)` or `(objectClass=*)` can be used as input values for a username or password fields.|
These are similar to Sqli but target ldap dir svc instead of a database. 
EX: suppose application uses following LDAP query to authenticate users: 
```php
(&(objectClass=user)(sAMAccountName=$username)(userPassword=$password))
```

`$username` and `$password` contain user login creds. Attacker could inject `*` char into username or password to modify ldap query and bypass authentication. 

If attack injects `*` into username ldap query will match any user account with any password. This would allow the attacker to gain access to application with any password. 

```php
$username = "*";
$password = "dummy";
(&(objectClass=user)(sAMAccountName=$username)(userPassword=$password))
```

Alternatively if `*` injected in PW field - ldap query would match any user account with any password that contains the injected string. This would allow attacker to gain access to the application with any username shown below: 

```php
$username = "dummy";
$password = "*";
(&(objectClass=user)(sAMAccountName=$username)(userPassword=$password))
```

LDAP injections can have severe consequences, like unauth access / elevated priv, even full control over affected app/server. 
These attacks can considerably impact data integrity and availability as attackers may alter/remove data within dir svc causing disruptions. 

To mitigate risks associated with LDAP injection attacks it's critical to thoroughly validate and sanitize user input before incorporating it into LDAP queries. 
- Remove ldap-specific special chars 
- employing parameterised queries 

---
Example NMAP of LDAP being hosted: 

```shell-session
stejwes@htb[/htb]$ nmap -p- -sC -sV --open --min-rate=1000 10.129.204.229

Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-23 14:43 SAST
Nmap scan report for 10.129.204.229
Host is up (0.18s latency).
Not shown: 65533 filtered tcp ports (no-response)
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
PORT    STATE SERVICE VERSION
80/tcp  open  http    Apache httpd 2.4.41 ((Ubuntu))
|_http-server-header: Apache/2.4.41 (Ubuntu)
| http-cookie-flags: 
|   /: 
|     PHPSESSID: 
|_      httponly flag not set
|_http-title: Login
389/tcp open  ldap    OpenLDAP 2.2.X - 2.3.X

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

Injection: 
OpenLDAP runs on server it's safe to assume webapp running on port 80 uses ldap for authentication. 
Attemping to login using a wildcard character `(*)` in username password field tgrants access to the system, effectively bypassing any authentication measures that had been implemented. This is a significant security issue as it allows anyone with knowledge of the vuln to gain unauth access to system. 
