HIGH crlf injectionactixhmac signatures

Crlf Injection in Actix with Hmac Signatures

Crlf Injection in Actix with Hmac Signatures

Crlf Injection occurs when an attacker can inject carriage return (CR, \r) and line feed (\n) characters into HTTP headers or header-derived values. In Actix, this risk is amplified when Hmac Signatures are used to authenticate requests because an injected newline can allow an attacker to append additional signature-value pairs or duplicate existing signed headers without invalidating the Hmac verification. The signature is typically computed over a canonical set of headers and a payload; if a header value contains injected \r\n sequences, the server may parse the resulting header lines as multiple distinct headers. This can cause the application to treat appended data as a separate, unsigned header or as a second instance of a signed header, leading to request smuggling, response splitting, or unauthorized privilege escalation.

Consider an Actix middleware that builds an Authorization header using Hmac Signatures like: Authorization: HMAC id="alice",headers="date request-target",signature=.... If the request-target or any header value under the signed headers list is controllable and not sanitized, an attacker-supplied \r\n can inject a new line such as request-target: /api/resource\r\nX-Additional: injected. Depending on how the server parses headers and reconstructs the canonical string for verification, the Hmac may be computed over only the original headers while the injected line is processed as a new, unsigned header. This mismatch between the runtime header view and the signed canonical string can bypass intended integrity checks and enable smuggling or response manipulation.

Real-world impact includes response splitting, header-based attacks, and bypass of access controls that rely on the integrity of signed headers. For example, an attacker could inject a new header like X-User-Role: admin after the signature block if the server processes headers sequentially and does not reject \r\n in values. Because middleBrick tests input validation and header handling as part of its 12 security checks, it can identify whether an endpoint reflects or processes injected newline characters in headers that influence Hmac canonicalization.

Hmac Signatures-Specific Remediation in Actix

Remediation focuses on disallowing CR and LF characters in any header value that participates in Hmac signing and ensuring strict parsing of headers before canonicalization. In Actix, you should validate and sanitize header values before they are included in the signed string, and enforce a canonical form that excludes \r and \n. Below are concrete code examples demonstrating secure handling of Hmac Signatures in Actix HTTP request handling.

use actix_web::{web, App, HttpServer, HttpRequest, HttpResponse, Error};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::collections::BTreeMap;

// Type alias for HMAC-SHA256
type HmacSha256 = Hmac;

/// Validate and sanitize header values to prevent CRLF injection.
/// Reject or escape CR/LF in any header that influences the canonical string.
fn sanitize_header_value(value: &str) -> Result {
    if value.contains('\r') || value.contains('\n') {
        return Err("Invalid header value: contains CR or LF");
    }
    Ok(value.to_string())
}

/// Build canonical string for Hmac signing from selected headers.
/// Headers must be lowercased and sorted for deterministic ordering.
fn build_canonical(headers: &BTreeMap) -> String {
    headers.iter()
        .map(|(k, v)| format!("{}:{}", k.to_lowercase(), v))
        .collect::>()
        .join("\n")
}

/// Example Actix extractor that validates headers before signing.
async fn handle_signed_request(req: HttpRequest, body: web::Bytes) -> Result {
    // Example: headers that must be included in Hmac
    let header_names = ["date", "request-target"];
    let mut canonical_headers = BTreeMap::new();

    for &name in &header_names {
        if let Some(val) = req.headers().get(name) {
            let val_str = val.to_str().map_err(|_| actix_web::error::ErrorBadRequest("Invalid header"))?;
            // Critical: sanitize before inclusion in canonical string
            let safe_val = sanitize_header_value(val_str)?;
            canonical_headers.insert(name.to_string(), safe_val);
        } else {
            return Err(actix_web::error::ErrorBadRequest("Missing required header"));
        }
    }

    let canonical = build_canonical(&canonical_headers);
    let secret = b"super-secret-key"; // In practice, load securely
    let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC can take key of any size");
    mac.update(canonical.as_bytes());
    let result = mac.finalize();
    let signature = result.into_bytes();

    // Construct Authorization header safely without embedded newlines
    let auth_value = format!("HMAC id=\"alice\",headers=\"date request-target\",signature=\"{}\"",
        hex::encode(signature));

    // Ensure the constructed header is also safe
    sanitize_header_value(&auth_value)?;

    Ok(HttpResponse::Ok()
        .insert_header(("Authorization", auth_value))
        .body("Signed request processed"))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/api/secure", web::post().to(handle_signed_request))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Key points in the remediation:

  • Validate and reject CR/LF in any header that participates in the Hmac canonical string.
  • Use a deterministic, sorted header representation (e.g., BTreeMap) to ensure reproducible canonicalization.
  • Do not include user-controlled header names in the signed list; if you must, sanitize them strictly.
  • Ensure the Authorization header you emit also avoids CR/LF to prevent response splitting when the header is reflected.

By combining input validation and canonical-form discipline, you prevent CRLF Injection from undermining Hmac Signatures in Actix. middleBrick’s checks for input validation and header handling help surface endpoints where newlines are not rejected, supporting secure implementation of Hmac-based authentication.

Frequently Asked Questions

How can I test my Actix endpoint for CRLF Injection with Hmac Signatures?
Send requests with \r\n in header values that are included in the Hmac canonical string and observe whether the server parses them as additional headers or accepts them as part of the signature. middleBrick’s unauthenticated scan can detect whether endpoints reflect or process injected newline characters in signed headers.
Does middleBrick detect CRLF Injection in authenticated scans?
middleBrick tests the unauthenticated attack surface and includes checks for input validation and header handling; it can identify endpoints vulnerable to CRLF Injection in header processing regardless of authentication.