HIGH nosql injectionchimutual tls

Nosql Injection in Chi with Mutual Tls

Nosql Injection in Chi with Mutual Tls

Chi is a functional web framework for Clojure that encourages composable middleware and explicit route handling. When TLS is configured for client certificate verification (mutual TLS), developers may assume the transport is fully authenticated and therefore reduce validation on data that originates from the authenticated identity. This assumption can interact poorly with Nosql injection when application logic builds NoSQL queries using values derived from the client certificate without additional sanitization.

Mutual TLS in Chi does not automatically sanitize inputs that come from authenticated principals. For example, if a route extracts a subject field from the client certificate and uses it directly in a MongoDB query without type checks or allow-listing, an attacker who can present a valid certificate may still inject query operators. A typical vulnerable pattern in Chi might look like reading the certificate subject and using it as a key in a query map:

(defroutes app-routes
  (GET "/users/*" req
    (let [client-cert (some-> req :ssl-client-cert :subject)
          username (get-in client-cert ["CN"])
          user-doc (mongo/find-one :users {:username username}))]
      (response/json user-doc))))

If the certificate subject is not constrained, an attacker could supply a CN value such as {"$ne": "admin"} and cause the query to match unintended documents. This is a classic NoSQL injection where the attacker manipulates the query structure through controlled input.

Chi middleware can also introduce risks if developers compose routes dynamically based on certificate metadata. For instance, using the certificate common name to select a tenant or database without strict validation may allow an attacker to traverse logical boundaries by injecting operators or malformed keys. The NoSQL injection occurs at the point where data derived from the mutual TLS identity is combined with untrusted request parameters. Even with mutual TLS providing identity assurance, the application must treat all data used in query construction as untrusted and apply validation and encoding appropriate for the NoSQL engine.

Another scenario involves logging or audit trails where certificate fields are interpolated into query strings for storage or analysis. If these values are later used to construct NoSQL queries without parameterization, injection can occur at that secondary stage. The key takeaway is that mutual TLS handles authentication, not authorization logic, and developers must still apply secure coding practices for NoSQL interactions in Chi, including schema design constraints, allow-listing of fields, and avoiding string concatenation to build queries.

Mutual Tls-Specific Remediation in Chi

Remediation focuses on strict validation and separation of identity from query construction. Do not use certificate fields as direct query keys or values. Instead, map certificate attributes to internal identifiers and use parameterized queries or safe access patterns.

A safer approach in Chi is to treat the certificate as an authentication source and map it to a known user record via a stable internal ID. For example:

(defn extract-username [cert]
  (when cert
    (some-> cert :subject (get-in ["CN"]))))

(defn user-by-username-safe [username]
  ;; Use a parameterized query or an ORM that avoids injection
  (mongo/find-one :users {:username username}))

(defroutes app-routes
  (GET "/profile" req
    (let [cert (:ssl-client-cert req)
          username (extract-username cert)]
      (if username
        (response/json (user-by-username-safe username))
        {:status 401 :body "Invalid certificate"}})))

Enforce allow-listing for any field derived from the certificate. If only specific common names or organizational units are valid, check them explicitly:

(def allowed-cns #{"alice" "bob" "service-account-1"})

(defn cert-allowed? [cert]
  (contains? allowed-cns (get-in cert ["CN"])))

(defn authenticated-handler [handler]
  (fn [req]
    (if (cert-allowed? (:ssl-client-cert req))
      (handler req)
      {:status 403 :body "Certificate not authorized"})))

For multi-tenant applications, avoid using certificate fields to select databases or collections directly. Use a predefined mapping:

(def tenant-map {"alice" "tenant-a"
                 "bob" "tenant-b"})

(defn resolve-tenant [cert]
  (get tenant-map (get-in cert ["CN"])))

When constructing queries that involve user-provided input alongside certificate data, always treat the union as untrusted. Use functions that prevent injection by design, such as MongoDB's official driver parameterization or an abstraction layer that validates field names and values.

In Chi, you can also leverage middleware to normalize request parameters before they reach handlers, ensuring that certificate-derived values are only used in contexts where they cannot alter query semantics. Combine this with continuous scanning using tools like middleBrick to detect NoSQL injection patterns across your endpoints, including those protected by mutual TLS.

Frequently Asked Questions

Does mutual TLS prevent NoSQL injection?
No. Mutual TLS authenticates the client but does not sanitize data used in query construction. Developers must still validate and parameterize inputs used in NoSQL queries.
Can middleBrick detect NoSQL injection in endpoints protected by mutual TLS?
Yes. middleBrick tests the unauthenticated attack surface and can identify NoSQL injection patterns regardless of TLS configuration, provided the endpoints are reachable and exhibit the vulnerable behavior.