HIGH container escapeactixjwt tokens

Container Escape in Actix with Jwt Tokens

Container Escape in Actix with Jwt Tokens — how this specific combination creates or exposes the vulnerability

A container escape in Actix when JWT tokens are handled improperly typically arises from server-side request forgery (SSRF) or insecure deserialization combined with trust in token metadata. In this scenario, an API built with Actix-web validates JWTs for access control but then uses claims from the token (such as user roles or tenant IDs) to make runtime routing or containerization decisions. If the endpoint that processes these claims also accepts attacker-supplied URLs or host parameters, an unauthenticated or low-privilege attacker can pivot from the API host into the container host filesystem or network namespace.

For example, consider an Actix endpoint that reads a sub or a custom claim to decide which internal service container to invoke. If the endpoint does not validate the claim against an allowlist and also performs an SSRF-prone HTTP request to a service URL derived from the claim, an attacker can supply a malicious hostname that resolves to 127.0.0.1 or a Docker internal DNS name. Through this path, the attacker can reach the Docker socket mounted inside a container (e.g., /var/run/docker.sock) if the API container runs with elevated capabilities or has a volume mount into the host’s Docker runtime. This can lead to container escape by creating new containers with host-level privileges, mounting sensitive host paths, or interacting with the container runtime API.

Another angle involves JWT tokens issued with weak signing keys or none algorithms. If an Actix service trusts the JWT header’s alg field without enforcing a strong algorithm, an attacker can replace the token’s signature method with none or a public key as an HMAC secret. When the service decodes the token without strict validation, attacker-controlled claims can be injected, including paths or container identifiers that the backend uses to spawn processes or schedule workloads. These injected claims may direct the backend to execute binaries on the host, bypassing intended container boundaries.

Additionally, logging or error responses that include the JWT payload without sanitization can aid an attacker in refining SSRF or path traversal vectors. The combination of Actix’s routing flexibility and JWT-based authorization logic increases the blast radius if token validation is inconsistent. Security checks that focus only on authentication (valid signature) without verifying authorization context (claim integrity and safe usage) leave a gap that can be leveraged for container escape.

Jwt Tokens-Specific Remediation in Actix — concrete code fixes

Remediation centers on strict JWT validation, claim sanitization, and avoiding direct use of token claims for host or path resolution. Below are concrete patterns for Actix-web in Rust that reduce the risk of container escape.

1. Enforce algorithm and validate issuer/audience

Always specify the expected algorithm and validate standard claims. Do not trust the JWT header’s alg field.

use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation, TokenData, Header};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    role: String,
    tenant: String,
    exp: usize,
    iss: String,
    aud: String,
}

fn validate_token(token: &str) -> Result<TokenData<Claims>, jsonwebtoken::errors::Error> {
    let mut validation = Validation::new(Algorithm::HS256);
    validation.validate_exp = true;
    validation.validate_iss = true;
    validation.validate_aud = true;
    validation.iss = Some("my-secure-issuer".to_string());
    validation.set_audience(&["my-api"]);

    let key = DecodingKey::from_secret(&b"super-secret-key-32-bytes-long-xxxx"[..]);
    decode::<Claims>(token, &key, &validation)
}

2. Sanitize claims before using them in routing or container selection

Never directly use claims to construct file paths, container names, or hostnames. Map claims to a controlled allowlist.

fn safe_tenant_endpoint(claims: &Claims) -> Result<String, &'static str> {
    let allowed_tenants = ["tenant-a", "tenant-b"];
    if allowed_tenants.contains(&claims.tenant.as_str()) {
        // Map to an internal service name, not a raw claim value
        Ok(format!("service-{}.internal", claims.tenant)) // internal DNS, not user-controlled
    } else {
        Err("unauthorized tenant")
    }
}

3. Avoid SSRF when invoking backend services derived from JWT claims

Do not perform HTTP requests to URLs built from token claims. If you must call downstream services, use a fixed allowlist of endpoints and pass only safe identifiers as parameters.

async fn call_service_for_tenant(tenant: &str) -> Result<reqwest::Response, reqwest::Error> {
    // Fixed mapping; tenant is validated against an allowlist first
    let base = match tenant {
        "tenant-a" => "http://internal-service-a",
        "tenant-b" => "http://internal-service-b",
        _ => return Err(reqwest::Error::new(reqwest::StatusCode::FORBIDDEN)),
    };
    reqwest::get(base).await
}

4. Drop dangerous headers and avoid logging raw JWTs

Strip or ignore the kid header and never log the full token. If you must log for debugging, redact sensitive parts.

// In an Actix guard or middleware, reject tokens with unexpected headers
fn validate_header(header: &Header) -> bool {
    // Reject tokens with 'none' algorithm or unexpected 'kid' usage
    header.alg != Algorithm::HS256 || header.kid.is_none()
}

Frequently Asked Questions

Can a JWT with a none algorithm lead to container escape in Actix?
Yes. If an Actix service does not enforce a specific algorithm and accepts a JWT signed with none, attacker-controlled claims can be injected and used to influence container selection or SSRF targets, enabling container escape.
Does middleBrick detect JWT validation weaknesses related to container escape?
middleBrick’s LLM/AI Security and Input Validation checks can surface insecure token handling and SSRF patterns that may contribute to container escape; findings include remediation guidance to enforce strict JWT validation and safe claim usage.