HIGH ldap injectionchiapi keys

Ldap Injection in Chi with Api Keys

Ldap Injection in Chi with Api Keys — how this specific combination creates or exposes the vulnerability

Ldap Injection occurs when user input is concatenated into an LDAP query without proper sanitization or parameterization. In the Chi web framework for Clojure, this risk arises when API keys or other user-controlled values are used to build LDAP filter strings. Because Chi does not provide built-in LDAP escaping, concatenating an API key directly into a filter enables attackers to terminate a filter clause or inject additional conditions using special characters such as (, ), *, and \00.

Consider an endpoint that authenticates a user by searching an LDAP directory using an API key passed as a query parameter. A vulnerable Chi handler might look like this:

(defn vulnerable-ldap-search [request]
  (let [api-key (get-in request [:query-params :api-key])
        filter (<code>(str "(&(objectClass=person)(apiKey=" api-key "))"))]
    (ldap/search connection filter)))

If an attacker supplies api-key=*)(adminRole:1.2.840.113556.1.4.803:=true, the resulting filter becomes (&(objectClass=person)(apiKey=*)(adminRole:1.2.840.113556.1.4.803:=true)), which can bypass authentication or escalate privileges. Even when API keys are expected to be opaque tokens, injection can expose directory information or enable unauthorized binds. The combination of Chi’s routing flexibility and direct string usage for LDAP filters creates a clear injection surface.

middleBrick scans this attack surface by testing unauthenticated endpoints and flagging inputs that reach LDAP-related operations without validation. It checks for missing input sanitization, improper filter construction, and unsafe consumption patterns that could lead to data exposure or authentication bypass. These findings map to the OWASP API Top 10 and relevant compliance frameworks, providing prioritized remediation guidance rather than attempting to fix the code.

Api Keys-Specific Remediation in Chi — concrete code fixes

To prevent Ldap Injection when using API keys in Chi, avoid concatenating user input into LDAP filters. Use parameterized search APIs or strict allow-listing, and treat API keys as opaque values that are never interpreted as LDAP control characters.

1. Use parameterized LDAP libraries

Instead of building filters with string concatenation, use a library that supports parameterized filters or pre-escaped components. For example, with clj-ldap, prefer structured input and avoid embedding raw keys in filter templates:

(defn safe-ldap-search [request]
  (let [api-key (get-in request [:query-params :api-key])
        ;; Validate format strictly before use
        safe-key (when (re-matches #"[A-Za-z0-9_-]{20,40}" api-key)
                   api-key)]
    (when safe-key
      (let [filter (ldap/filter:and
                     (ldap/filter:equality "objectClass" "person")
                     (ldap/filter:equality "apiKey" safe-key))]
        (ldap/search connection filter)))))

2. Strict allow-listing and validation

Enforce strict allow-listing for API key format and length. Reject any input containing LDAP metacharacters before it reaches the directory query:

(def invalid-chars #{\space \; \: \( \) \* \+ \? \< \> \=})
(defn valid-api-key? [key]
  (and (some? key)
       (not-any? #(contains? invalid-chars %) key)
       (re-matches #"^[A-Za-z0-9_-]{16,64}$" key)))

(defn validated-search [request]
  (let [api-key (get-in request [:query-params :api-key])]
    (if (valid-api-key? api-key)
      (let [filter (str "(&(objectClass=person)(apiKey=" api-key "))")]
        (ldap/search connection filter))
      {:status 400 :body "Invalid API key format"})))

3. Use environment-bound keys and avoid user-supplied keys in LDAP

Where possible, use server-side API keys stored as environment variables or secrets, and map them via hashed identifiers rather than raw values. This removes the need to embed potentially dangerous strings in LDAP filters entirely.

(defn mapped-search [request]
  (let [client-id (get-in request [:query-params :client-id])
        api-key (get-session-key-from-db client-id)] ; server-side lookup
    (ldap/search connection (<code>(str "(&(objectClass=person)(clientId=" client-id "))")))))

These patterns reduce injection risk by ensuring API keys are treated as data, not executable query components. middleBrick’s LLM/AI Security checks can further validate that endpoints do not leak sensitive logic or keys in error messages, complementing these coding practices.

Frequently Asked Questions

Can Ldap Injection occur even when API keys are treated as opaque tokens?
Yes. If an API key is concatenated into an LDAP filter string without validation, special characters in the token can alter the filter logic regardless of whether the token is meaningful. Always validate and escape.
Does middleBrick fix Ldap Injection vulnerabilities automatically?
No. middleBrick detects and reports Ldap Injection findings with remediation guidance. It does not modify code, block requests, or patch systems.