HIGH crlf injectionrockethmac signatures

Crlf Injection in Rocket with Hmac Signatures

Crlf Injection in Rocket with Hmac Signatures — how this specific combination creates or exposes the vulnerability

Crlf Injection occurs when an attacker can inject carriage return (CR, \r) and line feed (\n) characters into an HTTP header or response body, causing header injection or response splitting. In the Rocket web framework for Rust, this risk can intersect with Hmac Signatures when signature validation does not strictly validate or sanitize input that influences the canonical string signed by the Hmac key. For example, if a request path, query parameter, or header value containing \r\n is included in the data that is signed and later reflected in a redirect or a downstream request, an attacker can inject additional headers or even forge a valid Hmac signature for a malicious payload.

Consider a Rocket endpoint that constructs a redirect URL using a user-supplied parameter and signs the target URL with an Hmac key. If the parameter includes CRLF sequences, an attacker can inject headers such as Content-Type or Location, leading to response splitting or open redirects. Because the Hmac signature is computed over the tainted input, the server may treat the forged request as valid, especially when the signature is verified on a normalized but still CRLF-tainted string. This combination effectively bypasses integrity checks and allows the attacker to control response headers or trick clients into following malicious URLs.

In the context of middleBrick’s scanning methodology, this interaction is flagged under Input Validation and Data Exposure checks. The scanner tests whether user-controlled data that participates in Hmac computation or header construction is sanitized and canonicalized before being used for signing or redirection. The presence of CRLF-sensitive logic in Rocket handlers without strict input validation increases the likelihood that an attacker can exploit this class of weaknesses.

Hmac Signatures-Specific Remediation in Rocket — concrete code fixes

To mitigate Crlf Injection when using Hmac Signatures in Rocket, ensure that any data included in the signed string is normalized by stripping or rejecting CR and LF characters, and that outputs are encoded appropriately. Below are concrete Rocket examples using the hmac and sha2 crates.

Example 1: Signing a canonical request without CRLF

Normalize user input by removing \r and \n before constructing the message and computing the Hmac. This prevents injected control characters from affecting the signed payload or being reflected unchecked.

use hmac::{Hmac, Mac};
use sha2::Sha256;
use rocket::http::Status;
use rocket::response::content;

// Canonicalize by stripping CR/LF from the input before signing.
fn canonicalize(input: &str) -> String {
    input.chars().filter(|&c| c != '\r' && c != '\n').collect()
}

fn compute_hmac(key: &[u8], data: &str) -> Vec<u8> {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("Hmac key is valid");
    mac.update(data.as_bytes());
    mac.finalize().into_bytes().to_vec()
}

#[rocket::get("/redirect<target>")]
pub fn redirect(target: String) -> Result<rocket::response::Redirect, content::Html<String>> {
    let cleaned = canonicalize(&target);
    let message = format!("redirect_to:{}", cleaned);
    let signature = compute_hmac(b"my-secret-key", &message);
    // In a real app, you would include the signature in a header or query param.
    // Use the cleaned URL for the redirect to avoid CRLF injection.
    rocket::http::Redirect::permanent(&cleaned).map_ok(|_| ())
        .or_else(|_| Err(content::Html(format!("Invalid target: {}", cleaned))))
}

Example 2: Verifying Hmac with strict header and input validation

When verifying an Hmac signature, ensure the data being verified does not contain CRLF and that any headers derived from it are set safely using Rocket’s header API, which does not allow raw \r\n injection.

use hmac::{Hmac, Mac};
use rocket::request::{Request, FromRequest, Outcome};
use rocket::http::Header;

struct SecureHmacValidator([u8; 32]);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for SecureHmacValidator {
    type Error = ();

    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        // Example: extract and validate a signature header.
        if let Some(sig_header) = request.headers().get_one("X-API-Signature") {
            // Ensure the header value does not contain CRLF before further use.
            if sig_header.contains('\r') || sig_header.contains('\n') {
                return Outcome::Error((Status::BadRequest, ()));
            }
            // Proceed with signature verification logic using the validated header.
            // For demonstration, we accept a placeholder validator.
            return Outcome::Success(SecureHmacValidator([0u8; 32]));
        }
        Outcome::Forward(())

}

fn verify_hmac(key: &[u8], data: &str, received_sig: &str) -> bool {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("Hmac key is valid");
    mac.update(data.as_bytes());
    // Use constant-time comparison in production.
    let computed_sig = hex::encode(mac.finalize().into_bytes());
    computed_sig == received_sig
}

#[rocket::get("/data<id>")]
pub fn get_data(id: u64, validator: SecureHmacValidator) -> String {
    // Construct canonical data without CRLF.
    let data = format!("resource:{},v1", id);
    let cleaned_data = data.replace(['\r', '\n'], "");
    // Use cleaned_data for verification or further processing.
    cleaned_data
}

Frequently Asked Questions

Why does removing CR/LF matter when signing Hmac payloads in Rocket?
Removing CR/LF prevents attackers from injecting extra headers or breaking the structure of the signed payload. If \r\n characters are present in data that is included in the Hmac string, they can be used to split headers or bypass canonicalization checks, leading to response splitting or signature forgery.
Can middleBrick detect CRLF Injection combined with Hmac misuse in Rocket APIs?
Yes. middleBrick tests for Input Validation and Data Exposure across authenticated and unauthenticated attack surfaces. It identifies whether user-controlled data that influences Hmac signing or header construction is properly sanitized, helping you find CRLF Injection paths that could undermine signature integrity.