HIGH ldap injectionactixapi keys

Ldap Injection in Actix with Api Keys

Ldap Injection in Actix with Api Keys — 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 applications that rely on Api Keys for authentication, an insecure LDAP integration can expose the attack surface even when access is gated by a key. Consider an Actix handler that first validates an Api Key and then uses a username from the request to build an LDAP filter such as (uid={username}). If the username is not sanitized, an attacker can supply admin)(uid=*) to enumerate all users or admin'(&objectClass=*) to bypass authentication logic. Because the Api Key is checked before LDAP binding, an attacker may probe the LDAP backend indirectly through the authenticated endpoint, turning an otherwise protected route into a vector for injection.

The risk is compounded when the Actix service uses simple string concatenation instead of parameterized LDAP queries. For example, constructing a filter by appending the key-validated username directly into the search filter can allow crafted input to change the query semantics. A filter like (&(objectClass=person)(cn={input})) becomes dangerous when input includes wildcard characters or substrings that expand the result set. In such configurations, the Api Key does not mitigate injection; it only confirms that the caller is known, not that the subsequent LDAP operations are safe.

middleBrick detects this risk under the BOLA/IDOR and Input Validation checks by correlating unauthenticated LDAP-related behavior with the presence of static credentials like Api Keys. The scanner highlights cases where user input flows into directory queries after successful key validation, emphasizing that keys manage access but do not sanitize data. A typical finding would note that an endpoint accepting Api Keys passes raw input into an LDAP filter, enabling potential data exposure or unauthorized enumeration. This aligns with the broader OWASP API Top 10 category of Broken Object Level Authorization and underscores the need to treat validated credentials as insufficient for query safety.

Api Keys-Specific Remediation in Actix — concrete code fixes

To secure Actix endpoints that use Api Keys and interact with LDAP, avoid string concatenation entirely. Use parameterized LDAP queries or an LDAP library that supports placeholders, ensuring that user input is treated strictly as data, not executable query syntax. Combine strict input validation—allowing only safe characters for identifiers—with consistent key validation middleware that runs before any directory operation.

Below is a minimal, realistic example of safe handling in Actix with Api Keys. The code validates the key via middleware, extracts a username, and then uses a parameterized approach to search LDAP without embedding raw input into the filter string.

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use ldap3::{LdapConnAsync, Scope, SearchEntry};
use serde::{Deserialize};

#[derive(Deserialize)]
struct UserQuery {
    username: String,
}

async fn search_user(
    query: web::Query,
    // Assume Api Key validated by prior middleware; request extensions used for identity
) -> impl Responder {
    let username = &query.username;
    // Basic allowlist: alphanumeric and limited symbols
    if !username.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
        return HttpResponse::BadRequest().body("Invalid username format");
    }

    // Connect and bind with a service account (Api Key context can inform which account to use)
    let (conn, mut ldap) = LdapConnAsync::new("ldap://ldap.example.com").await.unwrap();
    ldap.simple_bind("cn=service,dc=example,dc=com", "password").await.unwrap().success().unwrap();

    // Parameterized filter using username as a literal value, not concatenated into the filter
    let filter = format!("(uid={})", ldap.escape(username));
    let search = ldap.search(
        "dc=example,dc=com",
        Scope::Subtree,
        &filter,
        vec!["cn", "mail"],
    );
    let res = search.await.unwrap();
    let entries = res.success().unwrap().unwrap_or_default();
    let users: Vec<_> = entries.into_iter().map(|e| SearchEntry::construct(e).unwrap()).collect();

    HttpResponse::Ok().json(users)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            // Api Key validation middleware would be inserted here
            .route("/users", web::get().to(search_user))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

In this example, the username is validated against an allowlist before being passed to the LDAP library, and the library’s escape method is used to ensure special characters are treated literally. The Api Key validation layer (not shown) confirms caller identity but does not influence how the username is incorporated into the query. This separation of authentication and input sanitization reduces the likelihood of injection while preserving the intended access control.

middleBrick can help verify that such precautions are in place by scanning the unauthenticated attack surface and mapping findings to compliance frameworks such as OWASP API Top 10 and SOC2. On the Pro plan, continuous monitoring can alert you if new endpoints introduce concatenated LDAP filters, and the GitHub Action can fail builds when risk scores exceed your chosen threshold.

Frequently Asked Questions

Does using Api Keys prevent Ldap Injection in Actix?
No. Api Keys control who can reach the endpoint but do not sanitize user input. If the endpoint builds LDAP queries by concatenating validated usernames or other input, injection remains possible. Always validate and escape input separately from authentication.
How can middleBrick help detect Ldap Injection risks with Api Keys?
middleBrick tests unauthenticated attack surfaces and correlates findings with authentication mechanisms like Api Keys. It flags endpoints where user input flows into directory queries after key validation, highlighting improper query construction and lack of input validation under BOLA/IDOR and Input Validation checks.