HIGH cross site request forgerychimutual tls

Cross Site Request Forgery in Chi with Mutual Tls

Cross Site Request Forgery in Chi with Mutual Tls

Cross Site Request Forgery (CSRF) in the context of Chi with Mutual TLS (mTLS) involves a subtle interplay between transport-layer client authentication and application-layer request validation. mTLS ensures that only clients possessing a valid certificate signed by a trusted Certificate Authority can establish a TLS connection to the server. In Chi, this means the server can rely on the presence of a client certificate to assert identity at the transport layer. However, this does not automatically protect endpoints that perform state-changing operations if the application does not continue to validate the intent of the request.

Consider a Chi application that exposes an HTTP endpoint for changing a user’s email. If the route relies solely on mTLS to identify the client—by inspecting the certificate presented during the TLS handshake—there is no additional check that the authenticated user intended this specific action. A browser-based CSRF attack becomes relevant when an authenticated user visits a malicious site that triggers a request to this Chi endpoint. Since the browser includes the client certificate automatically as part of the TLS handshake (assuming the certificate is installed in the user’s keystore), the server may accept the request as legitimate, even though the request was not initiated intentionally by the user.

This creates a mismatch: mTLS solves authentication of the client to the server, but does not solve the problem of unauthorized commands being issued from a user’s browser. In Chi, this often manifests when developers assume mTLS replaces application-level anti-CSRF measures such as synchronizer tokens or SameSite cookies. Attack vectors like img or form tags can still cause the browser to make authenticated requests if the client certificate is present and the server does not implement additional checks. The server must therefore treat mTLS as a strong identity signal, but not as a complete CSRF defense.

To understand this in practice, consider a Chi handler that uses client certificate information from the connection state without enforcing a per-request token or origin check. An attacker can craft a web page that causes a victim’s browser to submit a POST to the endpoint. Because the browser presents the victim’s certificate, the Chi application may interpret this as a valid, authenticated request. The vulnerability is not in mTLS itself, but in the assumption that authenticated transport equals authorized intent. This is especially important when endpoints perform sensitive operations such as changing permissions or initiating financial transactions.

Real-world parallels can be drawn to misconfigured setups where developers integrate mTLS but neglect OWASP API Top 10 protections around broken object-level authorization. Tools like middleBrick can detect such gaps by scanning the unauthenticated attack surface and identifying endpoints that lack CSRF-relevant controls even when mTLS is in use. The scanner tests assumptions by probing routes without client certificates and then with certificates to observe whether additional validation is enforced. This helps teams understand whether their Chi application correctly treats mTLS as one layer rather than a complete security boundary.

Mutual Tls-Specific Remediation in Chi

Remediation for CSRF in Chi with mTLS centers on adding application-layer checks that complement the transport-layer identity provided by client certificates. The key principle is to never rely solely on mTLS for protection against CSRF. Instead, combine mTLS with anti-CSRF tokens, strict origin validation, or custom request identifiers that cannot be forged by a malicious site.

One concrete approach in Chi is to require a custom header, such as x-request-id or a CSRF token, in addition to a valid client certificate. The server can verify the presence and correctness of this header before processing state-changing operations. Below is an example of a Chi route that requires both a client certificate and a valid CSRF token in a header:

open import Http
open import Data.String

csrfToken : String
csrfToken = "expected-csrf-token-from-session"

changeEmailHandler : ServerT Api IO (Either ServerError Unit)
changeEmailHandler = getRoute <!> header "x-csrf-token" <**> certAuthHandler
  where
    certAuthHandler :: Maybe ClientCertificate -> Handler (Either ServerError Unit)
    certAuthHandler Nothing = throwError err403 {reason = "Client certificate required"}
    certAuthHandler (Just _) = do
      token <- askHeader "x-csrf-token"
      if token == Just csrfToken
        then ok (unit :: Unit)
        else throwError err403 {reason = "Invalid CSRF token"}

In this example, certAuthHandler ensures that a client certificate is present, while the route also validates a CSRF token provided in the x-csrf-token header. This dual-check pattern ensures that even if a browser automatically presents a certificate, the request must still include a token that a malicious site cannot read or forge due to same-origin policy restrictions.

For APIs consumed by single-page applications, another strategy is to use the SameSite attribute on cookies and require anti-CSRF tokens in headers. If your Chi application uses cookies for session state alongside mTLS, set SameSite=Strict or Lax and validate the Origin header for sensitive endpoints. Below is an example of setting a secure cookie and validating origin in Chi:

import Network.HTTP.Server
import Network.TLS

-- Assume client certificate verification is configured at the TLS level
-- Set SameSite cookie and validate origin
setSecureCookieAndValidateOrigin :: Request -> Handler ()
setSecureCookieAndValidateOrigin req = do
  let origin = lookupHeader "origin" req
  let secureCookie = "session=abc123; Path=/; Secure; SameSite=Strict"
  -- Validate origin for sensitive operations
  case origin of
    Just o | not ("https://trusted-app.com" `isPrefixOf` o) -> throwError err403 {reason = "Invalid origin"}
    _ -> addHeader "Set-Cookie" secureCookie >> ok (unit :: Unit)

These patterns ensure that mTLS provides strong client authentication while the application layer continues to enforce CSRF protections aligned with OWASP recommendations. Combining transport and application controls significantly reduces the risk of successful CSRF attacks in Chi-based services.

Frequently Asked Questions

Does mTLS alone prevent CSRF in Chi applications?
No. mTLS authenticates the client to the server but does not prevent a browser from automatically presenting a certificate and making unauthorized requests. You must add application-layer CSRF protections such as anti-CSRF tokens or strict origin validation.
How can middleBrick help detect CSRF issues when mTLS is used?
middleBrick scans endpoints both without and with client certificates to verify that CSRF-relevant controls are enforced. It checks whether routes require additional tokens or origin checks beyond mTLS, producing findings mapped to OWASP API Top 10 and compliance frameworks.