HIGH padding oracleaxumjwt tokens

Padding Oracle in Axum with Jwt Tokens

Padding Oracle in Axum with Jwt Tokens — how this specific combination creates or exposes the vulnerability

A padding oracle in the context of Axum applications that validate JWT tokens typically arises when an API exposes different behavior for invalid padding versus other decryption or signature verification failures. Axum is a Rust web framework, and when combined with JWT token handling, developers often rely on libraries such as jsonwebtoken to parse and verify tokens. If error handling around token validation is not uniform, an attacker can infer whether a malformed ciphertext has valid padding by observing whether the system returns a distinct error for padding failures versus other errors. This distinction can allow adaptive chosen-ciphertext attacks that gradually reveal the plaintext without needing to directly decrypt the JWT.

In practice, a JWT consists of three base64url-encoded parts: header, payload, and signature (or an encrypted compact serialization in the case of JWE). When using an authenticated encryption algorithm such as AES-GCM or RSA-OAEP, incorrect padding or decryption errors must be handled so that they do not leak which part of the token caused the failure. In Axum, middleware or extractor implementations that process JWT tokens may inadvertently return different HTTP status codes or response messages for padding errors compared to signature verification failures. For example, a padding error might trigger a 400 Bad Request with a message about malformed tokens, while a signature mismatch might produce a 401 Unauthorized. These behavioral differences create an oracle that a remote attacker can exploit by sending modified JWTs and observing responses.

Even when Axum routes use typed extractors that return standardized error responses, the underlying JWT library may propagate low-level cryptographic errors that vary in timing or message content. An attacker can send specially crafted JWTs where the ciphertext bytes are modified systematically and measure whether the validation path reaches the padding check. Although the total scan time for middleBrick is 5–15 seconds, its unauthenticated black-box checks can detect inconsistent error handling patterns that suggest an oracle condition. Findings from such scans often map to OWASP API Top 10 categories such as Broken Object Level Authorization and Security Misconfiguration, because the issue stems from inconsistent validation logic rather than a dedicated padding oracle module.

Real-world scenarios involve JWT tokens protected with algorithms that are susceptible to padding manipulation, such as RSAES-PKCS1-v1_5 in combination with certain server-side implementations. If the Axum service uses such algorithms and does not apply constant-time verification or swallow low-level errors into a generic failure, the service may be vulnerable. middleBrick’s checks for input validation and error handling consistency can surface these risks by probing endpoints that accept JWTs and analyzing whether error messages or timing differ based on token structure. Remediation requires aligning error handling so that all token validation failures, including padding errors, produce the same generic response and status code, thereby removing the oracle.

Jwt Tokens-Specific Remediation in Axum — concrete code fixes

To remediate padding oracle risks when handling JWT tokens in Axum, ensure that token validation errors are caught and normalized before they reach the HTTP layer. Use a JWT library that supports constant-time verification where applicable and avoid branching logic based on specific cryptographic failure types. In Axum, this is typically done within extractor implementations or middleware that calls the JWT verification routine. All validation failures—including invalid signatures, expired tokens, and decryption or padding errors—should result in the same response type and HTTP status code, such as 401 Unauthorized with a generic message like {"error":"invalid_token"}.

Below is an example of a robust JWT extractor in Axum that wraps verification and normalizes errors. It uses the jsonwebtoken crate and treats any validation failure as a uniform unauthorized response, preventing distinct error paths for padding issues.

use axum::extract::FromRequest;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::Deserialize;
use std::convert::Infallible;

#[derive(Debug, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
}

struct Jwt(String);

#[axum::async_trait]
impl FromRequest<S> for Jwt
where
    S: Send + Sync,
{
    type Rejection = impl IntoResponse;

    async fn from_request(req: axum::http::Request<S>) -> Result<Self, Self::Rejection> {
        let auth_header = req.headers()
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .ok_or((StatusCode::UNAUTHORIZED, "{"error":"invalid_token"}"))?;

        let token = auth_header
            .strip_prefix("Bearer ")
            .ok_or((StatusCode::UNAUTHORIZED, "{"error":"invalid_token"}"))?;

        // Use a constant-time decoding approach and map all errors to the same response
        let decoding_key = DecodingKey::from_rsa_pem(include_bytes!("private_key.pem"))
            .map_err(|_| (StatusCode::UNAUTHORIZED, "{"error":"invalid_token"}"))?;
        let validation = Validation::new(Algorithm::RS256);

        decode::

In this example, decode errors—including those arising from padding issues during RSA decryption—are caught by the generic error handler and mapped to the same rejection type. This ensures that an attacker cannot distinguish padding failures from other invalid token conditions. For symmetric algorithms like HS256, the same principle applies: avoid exposing algorithm-specific errors and rely on a uniform error path.

Additionally, prefer algorithms that do not use PKCS#1 v1.5 padding where feasible, such as ES256 or EdDSA, because they avoid padding oracle primitives entirely. If RSA with PKCS#1 v1.5 is required, ensure the cryptographic library is configured to use constant-time operations and that error messages are suppressed at the application layer. middleBrick’s JWT-specific checks can validate that your Axum endpoints do not leak distinct error signatures for malformed tokens, supporting compliance mappings to frameworks such as OWASP API Top 10 and SOC2.

Frequently Asked Questions

How can I test my Axum JWT endpoints for padding oracle behavior using middleBrick?
Run an unauthenticated scan with middleBrick against your API endpoint that accepts JWT tokens. middleBrick’s black-box checks probe error handling patterns and can indicate whether distinct responses suggest a padding oracle. Use the CLI: middlebrick scan <url>, or add the GitHub Action to fail builds if risk scores indicate insecure error handling.
Does fixing the extractor guarantee protection against all token-related oracle attacks?
Normalizing error responses is essential, but you should also verify that the underlying JWT library does not leak timing or error details. Ensure constant-time decoding where supported, avoid branching on specific failure types, and consider algorithms that do not rely on padding. Continuous monitoring with the Pro plan can help detect regressions.