HIGH ldap injectionactixbearer tokens

Ldap Injection in Actix with Bearer Tokens

Ldap Injection in Actix with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Ldap Injection occurs when user-controlled input is concatenated into an LDAP query without proper validation or escaping. In Actix web applications that rely on LDAP for authentication or group membership checks, this often happens in server-side helper modules that build filter strings. Even when endpoints are protected by Bearer Tokens, injection can be exposed if token validation logic passes unchecked identifiers into LDAP queries. For example, extracting a username from a validated JWT and using it to construct a filter like (uid={username}) can allow an attacker to break query structure with crafted input such as admin)(objectClass=*), potentially bypassing intended filters or revealing additional directory entries.

Bearer Tokens themselves do not prevent injection; they provide authentication context. If the application resolves the token to a username or group list and then directly interpolates that value into an LDAP filter, the attack surface remains. Common patterns include using the token’s subject or a custom claim to dynamically search for the user in LDAP. An attacker who can control the token’s username (e.g., via account creation or a trusted upstream system) or who can inject through other identity sources may exploit string building to manipulate the LDAP filter. This can lead to unauthorized authentication binding or data exfiltration via LDAP responses, representing a BOLA/IDOR-like risk in the context of directory access.

In an Actix service, this often appears in authorization handlers that verify group membership by performing an LDAP search. If the handler builds filters using format strings without escaping parentheses, asterisks, or null bytes, the LDAP server may interpret them as logical operators. For instance, a filter like (&(objectClass=person)(cn=*{input}*)) becomes dangerous when input includes unmatched parentheses. The runtime behavior depends on how the LDAP client is configured, but improperly constructed filters can return more entries than intended, enabling horizontal privilege escalation or information disclosure.

Bearer Tokens-Specific Remediation in Actix — concrete code fixes

To mitigate Ldap Injection in Actix when using Bearer Tokens, ensure that any identity-derived values used in LDAP filters are properly escaped and that token validation does not implicitly trust identity claims for query construction. Use parameterized LDAP APIs where available, or implement strict allow-list validation on characters before including values in filters. Below are concrete Actix code examples that demonstrate a vulnerable pattern and a remediated approach.

Vulnerable pattern (do not use)

use actix_web::{web, HttpResponse, Error};
use ldap3::{LdapConnAsync, Scope, SearchEntry};

async fn check_membership_ldap(token_subject: String) -> Result {
    let (conn, mut ldap) = LdapConnAsync::new("ldap://ldap.example.com").await?;
    // UNSAFE: directly interpolating token_subject into filter
    let filter = format!("(uid={})", token_subject);
    let (rs, _) = ldap.search(
        "ou=people,dc=example,dc=com",
        Scope::Subtree,
        &filter,
        vec!["dn"],
    ).await?.success()?;
    for entry in rs {
        let _parsed = SearchEntry::construct(entry);
    }
    Ok(!rs.is_empty())
}

Remediated pattern with strict validation and parameterized usage

use actix_web::{web, HttpResponse, Error};
use ldap3::{LdapConnAsync, Scope, SearchEntry, LdapParams, Scope};
use regex::Regex;

/// Allow only alphanumeric, underscore, hyphen, and dot for uid-like identifiers.
fn is_safe_username(value: &str) -> bool {
    let re = Regex::new(r"^[A-Za-z0-9._-]+$").unwrap();
    re.is_match(value)
}

async fn check_membership_safe(token_subject: String) -> Result {
    if !is_safe_username(&token_subject) {
        return Ok(false);
    }
    let (conn, mut ldap) = LdapConnAsync::new("ldap://ldap.example.com").await?;
    // SAFE: validated input used in filter construction
    let filter = format!("(uid={})", token_subject);
    let (rs, _) = ldap.search(
        "ou=people,dc=example,dc=com",
        Scope::Subtree,
        &filter,
        vec!["dn"],
    ).await?.success()?;
    for entry in rs {
        let _parsed = SearchEntry::construct(entry);
    }
    Ok(!rs.is_empty())
}

/// Example Actix handler showing token extraction and safe LDAP usage.
async fn members_handler(
    req: actix_web::HttpRequest,
) -> Result {
    // In practice, extract Bearer token via middleware and validate via your auth provider.
    let token_subject = req.headers()
        .get("X-User-Name")
        .and_then(|hv| hv.to_str().ok())
        .map(|s| s.to_string())
        .unwrap_or_default();

    match check_membership_safe(token_subject).await {
        Ok(true) => Ok(HttpResponse::Ok().body("Member")),
        Ok(false) => Ok(HttpResponse::Forbidden().body("Not a member")),
        Err(_) => Ok(HttpResponse::InternalServerError().body("LDAP error")),
    }
}

For production Actix deployments, combine these practices with runtime security scans. middleBrick can evaluate your API endpoints for Ldap Injection and related BOLA/IDOR findings, including how Bearer Token handling intersects with directory queries. Use the CLI (middlebrick scan <url>) or GitHub Action to integrate checks into your pipeline, and refer to the dashboard to track improvements over time.

Frequently Asked Questions

Does using Bearer Tokens prevent Ldap Injection in Actix?
No. Bearer Tokens authenticate requests but do not sanitize identity values used in LDAP filters. If usernames or claims are interpolated into LDAP queries without validation or escaping, Ldap Injection can still occur.
What is a secure way to handle usernames from Bearer Tokens in Actix LDAP checks?
Validate usernames against an allow-list (e.g., alphanumeric, underscore, hyphen, dot) before using them in LDAP filters, and prefer parameterized LDAP APIs when available. Always treat token-derived values as untrusted input.