HIGH ldap injectionaspnet

Ldap Injection in Aspnet

How Ldap Injection Manifests in Aspnet

LDAP injection in ASP.NET applications typically occurs when user input is concatenated directly into LDAP queries without proper sanitization. This vulnerability is particularly dangerous in ASP.NET because many applications use Active Directory for authentication and authorization, creating a direct attack surface.

The most common attack pattern involves an attacker manipulating LDAP filters to bypass authentication. For example, consider this vulnerable ASP.NET code:

protected void Login_Click(object sender, EventArgs e) {
string username = txtUsername.Text;
string password = txtPassword.Text;

string filter = "(&(objectClass=user)(samAccountName=" + username + ")(userPassword=" + password + "))";
DirectorySearcher searcher = new DirectorySearcher(filter);

SearchResult result = searcher.FindOne();
if (result != null) {
// Authentication successful
}
}

An attacker could submit a username like admin)(userPassword=* which would create a filter that always returns true, effectively bypassing authentication. The resulting LDAP query would be:

(&(objectClass=user)(samAccountName=admin)(userPassword=*)(userPassword=*))

Another common pattern is attribute manipulation where attackers modify LDAP queries to extract sensitive directory information. Consider this vulnerable code that searches for users:

public DataTable SearchUsers(string department) {
string filter = "(department=" + department + ")";
DirectorySearcher searcher = new DirectorySearcher(filter);

searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("mail");
searcher.PropertiesToLoad.Add("telephoneNumber");

SearchResultCollection results = searcher.FindAll();
// Process results...
}

An attacker could submit Sales*)(mail=* as the department parameter, causing the filter to become:

(department=Sales*)(mail=*)

This would return all users in the Sales department along with their email addresses, potentially exposing more data than intended. The vulnerability becomes even more severe when combined with wildcard characters and logical operators that LDAP supports, allowing attackers to perform information disclosure, authentication bypass, and even modify directory entries if the application has write permissions.

Aspnet-Specific Detection

Detecting LDAP injection in ASP.NET applications requires both static code analysis and dynamic testing. From a code perspective, look for these patterns:

DirectorySearcher searcher = new DirectorySearcher(
"(&(objectClass=user)(samAccountName=" + username + "))"
);

Any string concatenation with user input in LDAP filters is a red flag. Use tools like SonarQube or Roslyn analyzers to scan your codebase for these patterns.

For runtime detection, middleBrick's black-box scanning can identify LDAP injection vulnerabilities without requiring source code access. The scanner tests unauthenticated endpoints by sending payloads designed to trigger LDAP-specific syntax errors or unexpected behaviors. For ASP.NET applications, middleBrick specifically checks:

  • Authentication endpoints that might construct LDAP filters from username/password inputs
  • Directory search APIs that accept filter parameters
  • Active Directory integration points
  • LDAP-based authorization mechanisms

middleBrick's LDAP injection tests include payloads like:

*)(objectClass=*
admin)(userPassword=*
)(cn=*))(|(cn=*
userPassword=*))(|(userPassword=*

These payloads test whether the application properly escapes special LDAP characters like (, ), *, , , and . The scanner also checks if the application implements proper error handling - LDAP injection often manifests through detailed error messages that reveal directory structure.

For comprehensive coverage, scan both authenticated and unauthenticated endpoints. Many LDAP injection vulnerabilities only appear when an attacker has some level of access to the directory service. middleBrick's continuous monitoring feature (Pro plan) can automatically rescan your APIs on a schedule, ensuring new vulnerabilities aren't introduced during development.

Aspnet-Specific Remediation

The primary defense against LDAP injection in ASP.NET is using parameterized LDAP queries instead of string concatenation. The DirectorySearcher class supports filter parameters that properly escape user input:

protected void Login_Click(object sender, EventArgs e) {
string username = txtUsername.Text;
string password = txtPassword.Text;

string filter = "(&(objectClass=user)(samAccountName={0})(userPassword={1}))";
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = string.Format(filter, username, password);

SearchResult result = searcher.FindOne();
if (result != null) {
// Authentication successful
}
}

However, this approach still has limitations. A more robust solution uses the System.DirectoryServices.AccountManagement namespace, which provides higher-level abstractions:

using System.DirectoryServices.AccountManagement;

public bool ValidateUser(string username, string password) {
try {
using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) {
return context.ValidateCredentials(username, password);
}
} catch (PrincipalServerDownException) {
// Handle directory service unavailable
return false;
}
}

This approach eliminates the need to construct LDAP filters manually and handles credential validation securely at the protocol level.

For search operations, use parameterized filters with proper escaping:

public DataTable SearchUsers(string department) {
using (DirectoryEntry entry = new DirectoryEntry("LDAP://yourdomain.com")) {
using (DirectorySearcher searcher = new DirectorySearcher(entry)) {
searcher.Filter = "(department={0})";
searcher.Filter = string.Format(searcher.Filter, EscapeLdapFilter(department));

searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("mail");
searcher.PropertiesToLoad.Add("telephoneNumber");

SearchResultCollection results = searcher.FindAll();
// Process results...
}
}
}

private string EscapeLdapFilter(string input) {
if (string.IsNullOrEmpty(input)) return input;

StringBuilder escaped = new StringBuilder();
foreach (char c in input) {
switch (c) {
case '\': escaped.Append("\\5c"); break;
case '*': escaped.Append("\\2a"); break;
case '(': escaped.Append("\\28"); break;
case ')': escaped.Append("\\29"); break;
case '': escaped.Append("\\00"); break;
case '/': escaped.Append("\\2f"); break;
default: escaped.Append(c); break;
}
}
return escaped.ToString();
}

For ASP.NET Core applications, consider using the Microsoft.AspNetCore.Authentication.ActiveDirectory package which provides built-in protection against LDAP injection through its abstraction layer.

middleBrick's GitHub Action can be integrated into your CI/CD pipeline to automatically scan for LDAP injection vulnerabilities before deployment. Add this to your workflow:

jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run middleBrick scan
run: middlebrick scan https://your-api-endpoint.com --format json

This ensures LDAP injection vulnerabilities are caught early in the development lifecycle rather than in production.

Frequently Asked Questions

How does LDAP injection differ from SQL injection in ASP.NET applications?
While both involve injecting malicious input into queries, LDAP injection targets directory services rather than databases. SQL injection typically uses UNION, SELECT, and comment syntax, while LDAP injection exploits special characters like *, (, ), and backslash. The attack surface differs too - LDAP injection often appears in authentication and directory search functionality, whereas SQL injection is more common in data access layers. ASP.NET applications frequently use LDAP for Active Directory integration, making this a distinct concern from SQL injection.
Can LDAP injection lead to complete Active Directory compromise?
Yes, in severe cases. If an application has write permissions to the directory and doesn't properly validate LDAP operations, an attacker could modify user attributes, add themselves to privileged groups, or even create new administrative accounts. The risk depends on the application's directory permissions - read-only applications have limited impact, while applications with modification rights pose a much greater threat. middleBrick's scanner tests for both read and write operation vulnerabilities to assess the full risk.