HIGH ldap injectionaxum

Ldap Injection in Axum

How Ldap Injection Manifests in Axum

Ldap Injection in Axum applications occurs when user input is directly incorporated into LDAP queries without proper sanitization. This vulnerability allows attackers to manipulate directory service queries, potentially accessing unauthorized data, bypassing authentication, or modifying directory information.

In Axum, this typically manifests in route handlers that process authentication requests or search operations. Consider a common pattern where an application uses LDAP for authentication:

use axum::{routing::get, Router};
use axum_extra::extract::Query;
use ldap3::{LdapConn, Scope, SearchOptions};

#[derive(serde::Deserialize)]
struct LoginQuery {
    username: String,
    password: String,
}

async fn login(Query(params): Query) -> &'static str {
    let ldap = LdapConn::new("ldap://localhost:389").unwrap();
    let user_dn = format!("uid={},ou=users,dc=example,dc=com", params.username);
    let simple = ldap.simple_bind(user_dn, &params.password).await;
    
    match simple {
        Ok(_) => "Login successful",
        Err(_) => "Login failed",
    }
}

let app = Router::new().route("/login", get(login));

The vulnerability here is in the user_dn construction. An attacker can inject LDAP-specific characters like *, (, ), or to manipulate the query. For example, submitting username=john)(&(uid=*)) could potentially return true for any user, bypassing authentication entirely.

Another common manifestation is in search operations where user input filters directory queries:

async fn search(Query(params): Query) -> Result {
    let ldap = LdapConn::new("ldap://localhost:389").unwrap();
    let filter = format!("(&(objectClass=person)(cn={}))", params.search_term);
    
    let (result, _meta) = ldap.search(
        "ou=users,dc=example,dc=com",
        Scope::Sub,
        &filter,
        vec!["cn", "sn", "mail"]
    ).await?;
    
    Ok(serde_json::to_string(&result)?)
}

Here, an attacker could submit search_term=*)(cn=* to retrieve all users' information, causing a data exposure vulnerability. The lack of input validation in Axum route handlers makes this particularly dangerous, as the framework doesn't automatically sanitize LDAP inputs.

Axum-Specific Detection

Detecting Ldap Injection in Axum applications requires examining both the code structure and runtime behavior. The most effective approach combines static analysis with dynamic scanning.

Static analysis involves reviewing route handlers that interact with LDAP. Look for patterns where user input is directly interpolated into LDAP queries without validation. In Axum, this often appears in handlers using Query, Json, or Path extractors that pass data directly to LDAP operations.

middleBrick's scanning approach for Axum applications includes:

  • Authentication Bypass Testing: The scanner attempts LDAP injection payloads like )(&(uid=*)) and admin)(userPassword=*)) to test if authentication can be bypassed
  • Directory Traversal Attempts: Testing for payloads that could navigate outside intended search bases, such as *) or cn=admin
  • Special Character Injection: Testing with LDAP metacharacters like *, (, ), , and to see if they're properly escaped
  • Boolean Logic Manipulation: Testing payloads that could alter query logic, such as )(cn=* or admin)(&

The scanner specifically targets Axum's async handler patterns, identifying where LDAP connections are established and how user input flows into LDAP operations. It examines the ldap3 crate usage patterns common in Rust web applications.

For runtime detection, middleBrick can be integrated into your CI/CD pipeline using the GitHub Action. This allows continuous monitoring of your Axum APIs:

name: API Security Scan

on:
  pull_request:
    branches: [ main ]

jobs:
  security-scan:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Run middleBrick Scan
      uses: middlebrick/middlebrick-action@v1
      with:
        target_url: ${{ secrets.API_URL }}
        fail_below_score: B
        token: ${{ secrets.MIDDLEBRICK_TOKEN }}

This configuration ensures that any Ldap Injection vulnerabilities introduced in new code are caught before deployment. The scanner's 12 security checks include specific LDAP injection testing that examines how your Axum application handles directory service queries.

Axum-Specific Remediation

Remediating Ldap Injection in Axum requires a defense-in-depth approach that combines input validation, proper LDAP query construction, and secure coding practices specific to Rust and Axum.

The first line of defense is input validation using Rust's type system and validation libraries:

use axum_extra::extract::Query;
use serde::Deserialize;
use validator::{Validate, ValidationError};

#[derive(Deserialize, Validate)]
struct LoginQuery {
    #[validate(length(min = 3, max = 50))]
    username: String,
    
    #[validate(length(min = 8, max = 128))]
    password: String,
}

async fn login(Query(params): Query) -> Result<&'static str> {
    // Input is already validated by the Validate trait
    let ldap = LdapConn::new("ldap://localhost:389").unwrap();
    
    // Use parameterized queries or proper escaping
    let user_dn = format!("uid={},ou=users,dc=example,dc=com", params.username);
    let simple = ldap.simple_bind(user_dn, &params.password).await;
    
    match simple {
        Ok(_) => Ok("Login successful"),
        Err(_) => Ok("Login failed"),
    }
}

For more robust protection, use LDAP's built-in mechanisms for safe query construction. The ldap3 crate provides methods that automatically handle escaping:

use ldap3::{LdapConn, Scope, SearchOptions, Escape};

async fn search(Query(params): Query) -> Result {
    let ldap = LdapConn::new("ldap://localhost:389").unwrap();
    
    // Properly escape the search term
    let escaped_term = Escape::new(&params.search_term).to_string();
    let filter = format!("(&(objectClass=person)(cn={}))", escaped_term);
    
    let (result, _meta) = ldap.search(
        "ou=users,dc=example,dc=com",
        Scope::Sub,
        &filter,
        vec!["cn", "sn", "mail"]
    ).await?;
    
    Ok(serde_json::to_string(&result)?)
}

For authentication scenarios, consider using LDAP's compare operation instead of constructing DN strings:

async fn secure_login(Query(params): Query) -> Result<&'static str> {
    let ldap = LdapConn::new("ldap://localhost:389").unwrap();
    
    // Use compare operation to avoid DN injection
    let filter = format!("(&(objectClass=person)(uid={}))", params.username);
    let (result, _meta) = ldap.search(
        "ou=users,dc=example,dc=com",
        Scope::Sub,
        &filter,
        vec!["userPassword"]
    ).await?;
    
    if let Some(entry) = result.first() {
        let user_dn = entry.dn().to_string();
        let compare = ldap.compare(user_dn, "userPassword", &params.password).await?;
        
        if compare.result() == ldap3::CompareResult::Equal {
            return Ok("Login successful");
        }
    }
    
    Ok("Login failed")
}

Integrate middleBrick's CLI into your development workflow for continuous security validation:

npm install -g middlebrick

# Scan your Axum API
middlebrick scan https://your-axum-api.com/login

# Check the report for LDAP injection findings
# The report will show:
# - Authentication bypass attempts
# - Directory traversal tests
# - Input validation effectiveness
# - Remediation guidance for each finding

This combination of input validation, proper LDAP usage patterns, and continuous scanning provides comprehensive protection against Ldap Injection in Axum applications.

Frequently Asked Questions

How does Ldap Injection differ from SQL Injection in Axum applications?
While both involve injecting malicious input into queries, Ldap Injection targets directory services rather than databases. In Axum, SQL Injection typically occurs with database crates like sqlx or diesel, while Ldap Injection involves the ldap3 crate and LDAP-specific syntax. The attack patterns differ: LDAP uses filters with parentheses and boolean operators, while SQL uses quotes and SQL keywords. middleBrick's scanner tests for both, but uses different payloads and detection methods for each.
Can middleBrick detect Ldap Injection in my Axum application during development?
Yes, middleBrick's free tier allows you to scan your Axum API endpoints during development. The scanner tests for LDAP injection by sending payloads designed to manipulate LDAP queries and observing the responses. You can run it locally with the CLI tool or integrate it into your CI/CD pipeline using the GitHub Action to catch vulnerabilities before deployment.