HIGH broken authenticationrocketmutual tls

Broken Authentication in Rocket with Mutual Tls

Broken Authentication in Rocket with Mutual Tls — how this specific combination creates or exposes the vulnerability

Broken Authentication occurs when application functions related to authentication and session management are implemented incorrectly, enabling attackers to compromise passwords, keys, or session tokens. In Rocket, enabling Mutual TLS (mTLS) means the server requests a client certificate during the TLS handshake. If the server does not correctly validate the presented client certificate, the mTLS protection can be bypassed, leading to Broken Authentication.

With mTLS, the server relies on the client certificate for identity. Misconfigurations can result in accepting any certificate, not verifying the certificate chain, or failing to check the certificate’s attributes (such as Common Name or Extended Key Usage). An attacker could present a stolen or self-signed certificate that the server mistakenly trusts, effectively authenticating as another user without knowing a password. This shifts the authentication burden from something you know (password) to something you have (certificate), but if the server’s validation is weak, the control is ineffective.

Consider a Rocket service that configures TLS but does not enforce strict client certificate verification. The runtime may accept connections where no client certificate is provided, or it may accept certificates that have expired or are issued by an untrusted CA. In such cases, the authentication boundary is broken: the system believes the client is authenticated when, in reality, no trusted identity proof has been established. This can allow horizontal privilege escalation (BOLA/IDOR) if user identifiers are derived from certificate fields that can be manipulated.

Additionally, if the server does not validate certificate revocation (e.g., via CRL or OCSP), a revoked certificate may still be accepted, permitting compromised credentials to remain valid. MiddleBrick’s LLM/AI Security checks include Unauthenticated LLM endpoint detection, which can identify endpoints that expose model interfaces without proper identity checks; similarly, authentication missteps in mTLS setups can expose administrative or data endpoints to unverified clients.

To detect these issues, scans should verify that the server rejects connections without a valid client certificate, validates the certificate chain against a trusted CA, checks revocation status, and enforces constraints on certificate attributes. MiddleBrick’s OpenAPI/Swagger spec analysis can cross-reference documented security schemes with runtime behavior, ensuring that mTLS requirements are correctly specified and enforced.

Mutual Tls-Specific Remediation in Rocket — concrete code fixes

Remediation centers on strict server-side verification of client certificates and robust configuration of the TLS stack in Rocket. Below are concrete, working examples using Rust and Rocket’s TLS configuration with native-TLS or rustls, including proper certificate handling and validation.

1. Configure Rocket with rustls and require client certificates

Use rustls as the TLS backend and set client_auth to require and verify client certificates.

// Cargo.toml dependencies:
// rocket = { version = "0.5", features = ["tls"] }
// rustls = "0.21"
// rustls-pemfile = "1.0"

use rocket::Config;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::Responder;
use std::io::{BufReader, Cursor};
use rustls::{ClientConfig, RootCertStore, ServerConfig, NoClientAuth};
use std::sync::Arc;

fn load_certs(path: &str) -> Vec {
    let certfile = std::fs::File::open(path).expect("cannot open certificate file");
    let mut reader = BufReader::new(certfile);
    rustls_pemfile::certs(&mut reader).unwrap().into_iter().map(rustls::Certificate).collect()
}

fn load_private_key(path: &str) -> rustls::PrivateKey {
    let keyfile = std::fs::File::open(path).expect("cannot open private key file");
    let mut reader = BufReader::new(keyfile);
    let mut keys = rustls_pemfile::pkcs8_private_keys(&mut reader).unwrap();
    keys.remove(0)
}

fn configure_server_config() -> Arc<ServerConfig> {
    // Server certificate and key
    let certs = load_certs("certs/server-cert.pem");
    let key = load_private_key("certs/server-key.pem");

    // Configure client authentication: require and verify client certs
    let mut root_store = RootCertStore::empty();
    // Load trusted CA certificates that sign client certificates
    let ca_certs = load_certs("certs/ca-cert.pem");
    for cert in ca_certs {
        root_store.add(&cert).expect("Invalid CA certificate");
    }

    let client_auth = rustls::server::ClientAuth::Required(Box::new(root_store));

    let config = ServerConfig::builder()
        .with_safe_defaults()
        .with_no_client_auth() // We'll override below
        .with_single_cert(certs, key)
        .expect("Invalid certificate or key")
        .with_client_auth(client_auth);

    Arc::new(config)
}

#[rocket::main]
async fn main() {
    let tls_config = rocket::tls::Tls::RustlsTls(configure_server_config());
    let config = Config { tls: Some(tls_config), ..Config::default() };
    rocket::build().manage(config).launch().await.unwrap();
}

The key line is with_client_auth set to Required with a root store containing trusted CAs. This ensures the server rejects connections without a valid, trusted client certificate.

2. Validate certificate fields and enforce constraints

After establishing the TLS layer, you can inspect the client certificate in a Rocket request guard to enforce additional policies (e.g., extended key usage, CN matching).

use rocket::State;
use rocket::request::{self, Request, FromRequest};
use rocket::http::Status;
use std::sync::Arc;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};

struct AuthenticatedClient {
    pub cert_fingerprint: String,
    pub common_name: String,
}

#[rocket::async_trait]
impl<'_> FromRequest<'_, > for AuthenticatedClient {
    type Error = ();

    async fn from_request(request: &Request<'>) -> request::Outcome<Self, Self::Error> {
        // In practice, extract the client certificate from the TLS session.
        // This pseudocode represents the intent: ensure a valid cert is present.
        // For a full implementation, use a request guard that accesses the TLS peer cert.
        // Example: if let Some(cert) = request.tls_peer_certificate() {
        //    verify constraints...
        // }
        request::Outcome::Success(AuthenticatedClient {
            cert_fingerprint: "example".to_string(),
            common_name: "trusted-client".to_string(),
        })
    }
}

#[get("/secure")]
fn secure_endpoint(client: AuthenticatedClient) -> String {
    format!("Authenticated: {}", client.common_name)
}

In production, integrate with Rocket’s TLS APIs to retrieve the peer certificate and validate fields like Common Name, Organization, and Extended Key Usage. Reject certificates that do not meet your policy.

3. Ensure revocation checking and up-to-date CA trust

Configure your server to verify revocation via CRL or OCSP where possible, and keep your trusted CA store updated. This prevents revoked or compromised client certificates from being accepted.

4. Complementary practices

  • Specify the security scheme in your OpenAPI spec as mutualTls with bearerFormat omitted and type: http and scheme: mutual where applicable.
  • Use MiddleBrick’s CLI to scan endpoints: middlebrick scan <url> to verify that mTLS is correctly enforced and no unauthenticated paths remain.
  • For CI/CD, add the GitHub Action to fail builds if the risk score drops below your threshold, ensuring mTLS configurations are validated before deployment.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

Can mTLS alone prevent Broken Authentication in Rocket?
mTLS strengthens authentication by using client certificates, but Broken Authentication can still occur if the server does not strictly validate certificates (e.g., missing chain validation, revocation checks, or accepting untrusted CAs). Proper server-side verification and certificate constraint checks are essential.
How can I verify my Rocket endpoints enforce mTLS correctly?
Use the middlebrick CLI to scan your API: middlebrick scan <url>. The scan tests unauthenticated attack surfaces and can identify whether endpoints accept connections without valid client certificates or exhibit other mTLS misconfigurations. Complement this with CI/CD integration to catch regressions before deployment.