HIGH dns cache poisoningchijwt tokens

Dns Cache Poisoning in Chi with Jwt Tokens

Dns Cache Poisoning in Chi with Jwt Tokens — how this specific combination creates or exposes the vulnerability

In the Chi web framework, DNS cache poisoning and JWT token handling intersect when an application uses dynamically resolved hostnames for authentication or redirection. If a Chi application resolves a hostname (e.g., auth.example.com) once and caches the DNS result, an attacker who can poison the cache may redirect the application to a malicious server. When the application then uses that hostname to validate or verify a JWT token — for example, by fetching a JSON Web Key Set (JWKS) from a discovery endpoint — it may unwittingly communicate with the attacker-controlled server.

This becomes critical when the JWT verification flow relies on network calls to retrieve keys or validate issuer metadata. A poisoned DNS entry can point to a server that presents a valid-looking JWT signing key, enabling signature validation to succeed against a malicious token. Because Chi typically does not re-resolve hostnames aggressively in production environments, the poisoned entry may persist across requests, extending the window of exposure. The vulnerability is not in JWT itself, but in the trust chain that depends on network resolution as part of the verification process.

Additionally, if the Chi application uses HTTP client configurations that do not enforce strict hostname verification or certificate pinning, an attacker who controls the poisoned DNS response may also present certificates that match the manipulated hostname, further bypassing TLS-level defenses. This can lead to JWT tokens being accepted even though they originate from an untrusted source. The combination of cached DNS data and JWT key discovery creates a path where token validation is subverted without triggering obvious errors in the application logic.

Such issues are relevant to the broader OWASP API Top 10 category of Security Misconfiguration and can intersect with SSRF or insecure consumption risks if the Chi application does not constrain outbound connections. middleBrick scans detect scenarios where JWT discovery endpoints are reachable through dynamically resolved hosts and highlight the risk of unauthenticated endpoints being influenced by network-level attacks.

Jwt Tokens-Specific Remediation in Chi — concrete code fixes

To mitigate DNS cache poisoning risks in Chi when working with JWT tokens, hardcode trusted endpoints and avoid runtime DNS-based resolution for security-critical hosts. Instead of relying on dynamic DNS lookups to locate JWKS endpoints, embed the HTTPS URL directly in configuration. This eliminates the cache poisoning vector by removing variability in the target hostname resolution.

Example: Hardcoded JWKS URL in Chi configuration

Use a fixed URL for JWT key retrieval and disable any automatic discovery that depends on dynamic hostnames. Below is a Chi route that validates a JWT using a hardcoded JWKS endpoint:

// app.psi
import "core:fmt"
import "chi"
import "jwt"

get_jwks :: proc() -> jwt.Keys {
    // Use a fixed, trusted HTTPS endpoint
    url := "https://auth.example.com/.well-known/jwks.json"
    keys := jwt.fetch_keys_from_url(url) or_else {
        fmt.eprintfln("failed to fetch keys: %v", err)
        return nil
    }
    return keys
}

verify_token :: proc(token: string) -> (bool, string) {
    keys := get_jwks()
    if keys == nil {
        return false, "unable to load keys"
    }
    verified, claims := jwt.verify_hs256(token, keys)
    if !verified {
        return false, "invalid signature"
    }
    return true, claims
}

app := chi.NewRouter()
app.get("/protected", func(w http.ResponseWriter, r *http.Request) {
    auth := r.header.get("Authorization")
    if auth == "" {
        http.error(w, "missing authorization header", 401)
        return
    }
    token := string(auth[7:])
    valid, msg := verify_token(token)
    if !valid {
        http.error(w, msg, 401)
        return
    }
    fmt.Fprintf(w, "access granted: %s", msg)
})

Enforce HTTPS and Pin Expected Hostname

When making HTTP requests for JWT material, enforce HTTPS and validate the server hostname programmatically. Chi does not provide built-in DNS pinning, so perform an explicit check on the resolved IP or certificate hostnames before proceeding with JWT operations:

https_client := http.Client(
    timeout = 5 * time.Second,
    // Ensure the client does not follow redirects to unexpected hosts
    check_redirect = proc(req: ^http.Request, via: []http.Request) -> bool {
        return false
    },
)

// Manually verify hostname after connection
conn, err := tls.dial("tcp", "auth.example.com:443", nil)
if err != nil {
    // handle error
}
defer conn.close()

cert := conn.connection_state().peer_certificates[0]
if cert.issuer.string() != "CN=Expected CA, O=Example" {
    // reject certificate
}

Use Environment Configuration for Flexibility Without Risk

For deployment variability, inject trusted hostnames via environment variables at startup, before any JWT verification logic runs. Validate the value against an allowlist to prevent runtime changes:

allowed_hosts := {"auth.example.com", "backup.auth.example.com"}
raw_host := os.get_env("AUTH_HOST")
if raw_host == "" || !util.contains(allowed_hosts, raw_host) {
    log.panic("invalid AUTH_HOST")
}
jwks_url := fmt.appendf("https://%s/.well-known/jwks.json", raw_host)

These steps ensure that JWT token validation in Chi does not rely on mutable DNS caches. By combining static endpoints, strict transport checks, and controlled configuration, the application reduces the attack surface related to DNS cache poisoning while maintaining compatibility with standard JWT workflows.

middleBrick can validate that your Chi application’s authentication endpoints are not exposed to unauthenticated discovery or resolution risks by scanning the API surface. The tool identifies patterns where JWT verification depends on dynamic host resolution and provides prioritized findings with remediation guidance.

Frequently Asked Questions

Can DNS cache poisoning affect JWT validation even when HTTPS is used?
Yes. If the hostname in a HTTPS URL is resolved via poisoned DNS, the TLS handshake may still succeed if the attacker presents a valid certificate for that hostname, allowing a malicious server to supply fake JWT keys.
Does middleBrick test for DNS-related JWT risks?
middleBrick identifies scenarios where JWT discovery depends on unauthenticated endpoints or dynamic host resolution and flags them with severity and remediation steps, but it does not fix the underlying configuration.