Defender for Identity: Hunting for LDAP
In the ever-evolving realm of cybersecurity, where threats often lurk unseen, the role of defenders is increasingly becoming proactive. It’s a shift from merely guarding to actively hunting – seeking out the elusive adversaries before they strike.
Enter MDI, which empowers security teams to transform into vigilant hunters. With cyber threats becoming more sophisticated, the ability to detect them in their nascent stages is crucial.
One of the unique challenges is dealing with LDAP actions and searches. These can often be noticed, slipping past standard tools and PowerShell commands. However, MDI records LDAP actions – discovery, enumeration, or information gathering. This capability is vital for identifying potential or active attacks, offering a critical edge in cybersecurity defense.
The post “Defender for Identity: Hunting for LDAP” focuses on LDAP searches, the known and unknown actions, and Detection in Defender for Identity.
Life in the Tech Lane
Understanding the Security Implications of LDAP and Active Directory in Modern Networks
Understanding the intricacies of technologies like Active Directory and the LDAP is crucial in the ever-evolving security landscape. These technologies are not just components of a Directory infrastructure. They are also potential gateways for sophisticated cyber threats.
The Role of LDAP and Active Directory
LDAP is an industry-standard protocol established by the IETF, designed to enable users to query and update information in a directory service. In many networked environments, Active Directory, a service provided by Microsoft, utilizes LDAP as its primary access protocol. AD forms the backbone of identity management and access control in Windows environments, managing user and computer accounts, groups, and other directory objects.
LDAP Queries: A Double-Edged Sword
A core functionality of LDAP is facilitating queries that retrieve information from the Active Directory database. These queries can be about any object in the AD, such as users, computers, and groups. While this feature is fundamental for legitimate purposes like authentication and system administration, it also opens doors for potential misuse.
The Security Risks
LDAP’s flexibility and wide-ranging access can be a significant security liability. Since most directory objects are readable by authenticated users, it becomes relatively easy for an intruder with primary access to collect comprehensive information about the domain. This includes detailed data on every user, group, and system, which can be a goldmine for someone with malicious intent.
Reconnaissance: The First Step of an Attack
Threat actors typically perform internal reconnaissance upon gaining initial access to a network. They use legitimate tools and commands to extract data from Active Directory, often remaining under the radar. The information gathered can reveal users, permissions, and other valuable resources, setting the stage for further exploitation.
LDAP Reconnaissance: A Key Attacker Technique
Attackers extensively use LDAP queries for internal reconnaissance, uncovering crucial details about users, groups, and computers. This information is not just for understanding the environment; it is often the foundation for planning more advanced attack stages, such as privilege escalation and lateral movement.
Compromised Credentials: A Gateway for Exploitation
An adversary with access to internal credentials can authenticate in Active Directory, leveraging those credentials to perform extensive enumerations. They might use tools like BloodHound, PowerSploit, and ADExplorer to automate this process, efficiently mapping out the network’s structure and identifying potential targets for further attacks.
In a nutshell, LDAP and Active Directory are staples in modern infrastructures and Hybrid-Cloud environments. However, if not adequately secured, their inherent functionalities can provide adversaries with a roadmap to exploit network vulnerabilities. Organizations must understand these risks and implement robust security measures. Regularly updating and monitoring AD configurations, implementing least-privilege access, and conducting continuous network surveillance are essential to securing these critical components against sophisticated cyber threats.
While LDAP and Active Directory are indispensable for network operations, their security implications cannot be overlooked. A comprehensive approach to network security, encompassing awareness, vigilance, and advanced protective measures, is critical to safeguarding against the ever-present risks in our digital world.
Tools for Exploitation
Several tools are available that can perform LDAP queries against the AD LDAP catalog. These include ldapsearch.exe, PowerShell, ADExplorer, and SharpHound. While these tools are invaluable for administrators, they can also be used by attackers for reconnaissance and data collection.
The Tools
Which tools can collect Active Directory Data?
- SharpHound is provided as part of BloodHound and collects data from an Active Directory environment.
- AD Explorer can be used to interactively browse an Active Directory. Additionally, it can generate a snapshot of the Active Directory to a file.
- PowerView is a PowerShell tool to gain network situational awareness on Windows domains.
- More tools can be Nmap, enum4linux, windapsearch, ldapsearch, Jxplorer, DSquery, and more.
While tools can collect Active Directory data and visualize an attack path, the PowerShell commands can also do a great job and run behind the scenes. Why is that? Because the tools raise many ldap searches in the Event logs, and the PowerShell command raises a few events.
adsiSearcher via PowerShell
ADSI Searcher in PowerShell, particularly in the context of Red Team operations, can be a powerful tool for querying and interacting with Active Directory (AD). It utilizes LDAP (Lightweight Directory Access Protocol) to access and manage directory services, which is crucial for administrators and IT professionals in extracting information about users, computers, and other objects within an AD environment.
For attackers, ADSI Searcher can be used to gain insights into the AD environment, which can be pivotal in understanding the network’s structure, user roles, and other critical information. This information can be leveraged for further attacks or for gaining unauthorized access to sensitive areas of the network.
Here’s an example of an adsiSearcher command that attackers might use:
$searcher = [adsisearcher]”(objectCategory=user)”
$searcher.PageSize = 1000
$results = $searcher.FindAll()
foreach ($result in $results) {
$user = $result.GetDirectoryEntry()
echo “Name: $($user.name)”
echo “User Principal Name: $($user.userPrincipalName)”
echo “Email: $($user.mail)”
}
This script is designed to enumerate all user accounts in the Active Directory. It creates an ADSI Searcher object that sets the query to find all objects of the user category and then iterates through each result. It prints out each user name, principal name, and email address.
Attackers could use this kind of script to gather information about users in the network, potentially finding accounts with higher privileges or those that might be easier to compromise. However, it’s important to note that using such scripts for unauthorized access or activities is illegal and unethical, and cybersecurity professionals typically use such scripts in controlled environments to strengthen network defenses.
adsiSearcher one-liner can be as follows:
Search for all Domain Controllers (Based 8192)
([adsisearcher]'(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))’).FindAll()—————–
Search for all Domain Controllers (Group 516) – ([adsisearcher]'(&(objectCategory=computer)(primaryGroupID=516))’).FindAll()
Find all user SPNs – ([adsisearcher]'(&(objectCategory=user)(servicePrincipalName=*))’).FindAll()
—————–
Search for all accounts that do not require a password
([adsisearcher]'(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=32))’).FindAll()
—————–
Search for all objects with AdminSHHolder
([adsisearcher]'(adminCount=1)’).FindAll()—————–
Search for user accounts with SPN but not TGT accounts
([adsisearcher]'(&(objectCategory=user)(!(samAccountName=krbtgt)(servicePrincipalName=*)))’).FindAll()
When conventional methods like using pre-made PowerShell scripts or tools like ADExplorer or SharpHound become impractical or are blocked by security measures like EDR/XDR in a compromised system, Red Teams need to adapt by using alternative strategies for enumerating Active Directory environments.
Unveiling LDAP in Defender for Identity
In the realm of network security and administration, monitoring LDAP (Lightweight Directory Access Protocol) queries is crucial for maintaining the integrity of domain controllers. Microsoft Defender for Identity (MDI) steps in as a robust solution, offering an insightful peek into these queries. Let’s delve into how MDI aids in bolstering your cybersecurity measures.
What is MDI and How Does It Help? Microsoft Defender for Identity is a cutting-edge tool designed to protect your identity systems. It monitors LDAP queries executed against domain controllers, logging them meticulously. This logging is crucial in identifying potentially malicious activities and ensuring the security of your network.
A Peek into MDI’s LDAP Query Logs: MDI logs LDAP queries in the IdentityQueryEvents table, which can be queried through Advanced Hunting or Microsoft Sentinel. The ‘LDAP query’ action type is used for logging, providing a detailed view of each query executed.
Example of an LDAP Query Log: This example illustrates the level of detail MDI provides, including LDAP search filters in the Query attribute. Such detailed logging is instrumental in detecting and analyzing network activities.
Using MDI for Threat Detection: The logged information can be used to detect collection tools and other potential threats. The same Indicators of Compromise (IoCs) obtained previously can be employed to effectively identify and mitigate these threats.
LDAP in Advanced Hunting
When running specific commands or running specific tools, it creates many actions with Event ID 4662. Those event id’s provide a result for each object that was part of the discovery and information gathering. On average, it can be a hundred events of objects per PowerShell command. In this situation, we need to know when it’s a legitimate action, security testing, or an APT group.
- What do we need to know? The LDAP Search Hierarchy.
- What should be the potential? Many actions for commercial tools.
- When do we need a red light? When someone touches sensitive groups. Mostly from PowerShell commands.
In general, you need to know the LDAP query search in order to detect a potential or suspicious action. Otherwise, you will have a false positive. Below are two specific hunting queries for MDI. You can use it in Advanced Hunting or Microsoft Sentinel.
Note: These hunting queries are basic ones. You should write ones that are based on behavior.
The following queries are available at Hunting for LDAP.kusto
LDAP Hunting Query with Target
let LDAP_Filter = dynamic([“objectGUID=*”,“(objectClass=*)”,“(schemaIDGUID=*)”,“(samAccountType=805306368)”,“(&(objectclass=computer)(userAccountControl&8192))”,“( | (objectClass=user) (objectClass=group) ) (objectSid=S-1-5-21-1960408961-838170752-1801674531-512) )”,“objectCategory=CN=Organizational-Unit,CN=Schema,CN=Configuration”,“(|(samAccountType=805306368)(samAccountType=805306369)(objectclass=organizationalUnit))”,“(|(samaccounttype=268435456)(samaccounttype=268435457)(samaccounttype=536870912)(samaccounttype=536870913))”,“(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192)”]);let LDAP_Target = dynamic([“Domain Admins”,“Schema Admins”,“Enterprise Admins”,“AllDomains”,“AllTrustDomains”,“AllSites”,“AllGroupPolicies”]);IdentityQueryEvents| where Timestamp >= ago(1d)| where ActionType == “LDAP query”| where QueryTarget has_any (LDAP_Target)| where Query has_any (LDAP_Filter)

LDAP Hunting Query without Target
let LDAP_Filter = dynamic([
“objectGUID=*”,
“(objectClass=*)”,
“(schemaIDGUID=*)”,
“(samAccountType=805306368)”,
“(&(objectclass=computer)(userAccountControl&8192))”,
“( | (objectClass=user) (objectClass=group) ) (objectSid=S-1-5-21-1960408961-838170752-1801674531-512) )”,
“objectCategory=CN=Organizational-Unit,CN=Schema,CN=Configuration”,
“(|(samAccountType=805306368)(samAccountType=805306369)(objectclass=organizationalUnit))”,
“(|(samaccounttype=268435456)(samaccounttype=268435457)(samaccounttype=536870912)(samaccounttype=536870913))”,
“(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192)”
]);
IdentityQueryEvents
| where Timestamp >= ago(1d)
| where ActionType == “LDAP query”
| where Query has_any (LDAP_Filter)

The structure of those queries suggests it’s used for the following purposes:
- Filtering LDAP Queries: The LDAP_Filter array contains various LDAP query filters. These filters are used to specify criteria for selecting and filtering objects in an Active Directory environment. For example, filters like “objectGUID=*” or “(objectClass=*)” are used to select objects based on attributes like objectGUID, objectClass, etc.
- Identifying Specific Targets: The LDAP_Target array lists key Active Directory groups or roles like “Domain Admins”, “Schema Admins”, etc. This part of the query is designed to focus on activities related to these critical groups or roles.
Advanced Hunting Query Structure: The actual query, starting with IdentityQueryEvents, is a part of Microsoft Defender’s advanced hunting capabilities. It is designed to:- Search within the IdentityQueryEvents log for events within the last day.
- Filter for events where the action type is “LDAP query”.
- Further, refine the search to events where the LDAP query targets specific groups or objects and matches the specified filters.
The primary aim of such a query is to monitor and investigate LDAP query activities for signs of suspicious or unauthorized behavior, especially those targeting sensitive or high-privileged groups and objects in the Active Directory. This is crucial for maintaining the security of an organization’s IT infrastructure, as LDAP queries can be used to retrieve sensitive information or to perform reconnaissance for further attacks.
Event ID 4662
What does the Event ID 4662 look like in Event Viewer? It will create many events – for each action made by the PowerShell command or the Active Directory discover tools. You can search for each action at the Event Viewer. For example, the search for object Domain Admins might look as below.

MITRE ATT&CK
Adversaries seeking to gain unauthorized access or control over network resources often target domain-level groups and permission settings. Understanding these elements can provide significant insights into network organization and control. Here’s a closer look at how this is done and the tools involved:
- Domain-Level Permission Groups: These groups are critical in network management, as they define user roles and permissions. By gaining knowledge of these groups, an adversary can understand the network’s hierarchy and identify users with elevated permissions, like domain administrators. This information is invaluable for planning attacks or escalating privileges.
- Tools Used by Adversaries:
- Net Utility in Windows: The net group /domain command is a part of the Net utility in Windows environments. It’s used to list domain-level groups, providing information about group names and members. This command is particularly useful for identifying high-privilege groups like domain administrators.
- dscacheutil in macOS: On macOS systems, the command dscacheutil -q group is used. It queries the directory service cache for group information, revealing group memberships and permissions. This can be leveraged to find users with administrative rights.
- ldapsearch in Linux: ldapsearch is a command-line utility for searching and updating directories that use the Lightweight Directory Access Protocol (LDAP). It can be used to query LDAP directories for group information, which is crucial in environments where Linux servers are integrated into domain environments.
- Risks and Implications:
- Privilege Escalation: By understanding which users have elevated permissions, adversaries can target these accounts for privilege escalation attacks.
- Lateral Movement: Knowledge of group memberships can facilitate lateral movement within a network, as attackers identify and target less secure accounts with desirable access levels.
- Planning and Execution of Targeted Attacks: Detailed knowledge of the domain-level groups aids in planning more sophisticated, targeted attacks, potentially leading to more significant breaches.
Organizations must be vigilant in monitoring the use of such commands and tools within their networks. Regular audits, strict permission controls, and anomaly detection systems are essential to mitigate the risks associated with unauthorized access to domain-level group information.
Account Discovery – Domain Account (T0187.002)
Domain Trust Discovery (T1482)
Permission Groups Discovery (ID: T1069)
Permission Groups Discovery – Domain Groups (T1069.002)
References
More Defender for Identity posts in CYBERDOM.
Monitored user activities: Domain controller-based user operations.