MEDIUM log injectionchijwt tokens

Log Injection in Chi with Jwt Tokens

Log Injection in Chi with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Log injection occurs when untrusted input is written directly into application or system logs without proper sanitization. In a Chi application that uses JWT tokens for authentication, this typically happens when values from the token—such as claims, the token string itself, or derived user identifiers—are inserted into log messages without validation or encoding. Because JWT tokens often carry user identity, roles, or session metadata, they become a prime source of attacker-controlled data once token parsing or verification is bypassed or when tokens are accepted from untrusted sources.

Chi routes and handlers process requests and produce logs at multiple layers: middleware, route handlers, and any custom logging you add. If a handler logs the raw token or a claim like sub or name directly, an attacker who can influence the token (for example, via a forged but structurally valid token, a token with a modified payload in a weak verification setup, or a token obtained through phishing) can inject newline characters or structured delimiters. Newline injection enables log forging, where additional fake entries are appended, potentially obscuring real events or triggering log-based alerts and parsers to misinterpret the sequence of events. Worse, if logs are aggregated into SIEMs or monitoring systems that treat each line as a separate event, injected newlines can split one malicious action into multiple log entries or fabricate context such as fake user IDs or statuses.

Chi applications that rely on JWTs for authorization may also log details from token validation outcomes. Without care, log entries can reflect low-level errors from the JWT library (e.g., malformed token, expired, invalid signature) including the exact token fragment that caused the failure. This not only risks exposing sensitive parts of the token but also provides clues useful for token replay or brute-force attempts. In a microservice context where tokens are passed across services, each service may independently log token-related information. If one service logs attacker-controlled claims without sanitization, the injected content can propagate through the distributed log stream, amplifying the impact across the system.

Because Chi is a functional, composable router for Clojure, developers often use concise middleware and handlers. A common pattern is to extract a claim and log it inline, for example to trace request context. This convenience can inadvertently introduce injection if the claim value contains carriage returns or line feeds. Additionally, structured logging formats like JSON are popular; if a claim is placed into a JSON log without proper string escaping, an injected newline can break the JSON structure, leading to mangled records and complicating automated analysis. The key risk in the Chi + JWT combination is thus uncontrolled propagation of token-derived data into logs, where newline or delimiter injection can distort audit trails and obscure real attacks.

Jwt Tokens-Specific Remediation in Chi — concrete code fixes

Remediation focuses on preventing untrusted token data from corrupting logs. Treat any data derived from a JWT as untrusted input: validate, sanitize, and safely encode before logging. Below are concrete patterns for Chi handlers and middleware.

1) Sanitize claims before logging

Do not log raw claims. Normalize and escape them. For structured JSON logging, ensure strings are properly escaped so newlines and control characters cannot break log format integrity.

(ns myapp.handler
  (:require [cheshire.core :as json]
            [clojure.string :as str]))

(defn sanitize-for-log [s]
  ;; Replace newlines and carriage returns; keep a readable representation
  (if (string? s)
    (-> s
        (str/replace #"[\r\n]" " ")
        (str/replace "\"" "\\\""))
    s))

(defn user-handler [request]
  (let [token (some-> request :headers (get "authorization") (re-find #"Bearer\s+(.+)") second)
        claims (some-> token my.jwt/decode-verify)] ; your JWT library here
    (when claims
      (info (str "request-id=" (:request-id request)
                 " user_id=\"" (sanitize-for-log (:sub claims))
                 " name=\"" (sanitize-for-log (:name claims)) "\"")))
    ...))

2) Use structured logging with safe encoders

When logging as JSON, use a library that escapes control characters automatically, or explicitly encode strings. This prevents newline injection from corrupting JSON log lines.

(ns myapp.logger
  (:require [cheshire.core :as json]))

(defn log-event [event-map]
  ;; Ensure string values are sanitized
  (let [clean-map (update-vals event-map (fn [v] (if (string? v) (sanitize-for-log v) v)))]
    (println (json/generate-string clean-map)))) ; prints a single-line, safe JSON log

3) Validate and constrain JWT usage in middleware

Validate tokens early and log only safe, normalized metadata. Avoid logging the raw token.

(ns myapp.middleware
  (:require [ring.util.http-response :as r]))

(defn jwt-auth-middleware [handler]
  (fn [request]
    (let [auth-header (get-in request [:headers "authorization"])
          token (when auth-header (re-find #"Bearer\s+(.+)" auth-header))
          token (second token)]
      (if (and token (valid-jwt? token)) ; your verification logic
        (let [claims (decode-valid-jwt token)
              user-id (sanitize-for-log (:sub claims))]
          (info (str "auth-success user_id=\"" user-id "\""))
          (handler request))
        (do
          (warn (str "auth-failed token=\"" (sanitize-for-log (str token)) "\""))
          (r/unauthorized {:error "invalid_token"}))))))

4) General practices

  • Never log raw JWT tokens in full.
  • Treat all external inputs—including tokens—as untrusted; apply consistent sanitization for logs.
  • Ensure your JSON logger escapes control characters; test with newline-injected claims to confirm log integrity.
  • Correlate requests with safe identifiers (e.g., a sanitized user ID or a server-generated request ID) rather than relying on token content alone.

These steps reduce the risk that JWT-derived data can manipulate log structure, while preserving useful audit information in Chi applications.

Frequently Asked Questions

Can log injection via JWT tokens affect compliance reporting?
Yes. Injected newlines or fabricated entries can distort audit trails, making it harder to reconstruct events accurately and potentially failing compliance checks that rely on log integrity.
Does middleBrick detect log injection risks in API logs?
middleBrick scans API endpoints and reports security findings such as input validation and data exposure issues. It does not inspect application logs, but its findings can highlight related risks that may lead to unsafe logging of JWT-derived data.