HIGH crlf injectionrocketrust

Crlf Injection in Rocket (Rust)

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

Crlf Injection occurs when an attacker can inject CRLF sequences (\r\n) into HTTP headers or the response body, causing header splitting or response splitting. In Rocket with Rust, this typically arises when user-controlled input is reflected into headers, Set-Cookie values, or the response body without proper validation or encoding. Rocket’s routing and request guards do not automatically sanitize inputs used to construct headers, so it is the developer’s responsibility to treat any user data as untrusted.

For example, if a route extracts a query parameter and uses it directly in a header via rocket::response::Response::raw() or custom header construction, an input like foo\r\nSet-Cookie: injected=1 can split the response and inject additional headers. The unauthenticated attack surface checked by middleBrick includes input validation and data exposure; Crlf Injection falls under input validation and can lead to data exposure or security bypass. Because Rocket applications are often built with type-safe request guards, developers may assume safety while inadvertently passing tainted data into headers or cookies, which the scanner’s checks for Data Exposure and Input Validation are designed to surface.

When scanning a Rocket endpoint with middleBrick, the tool tests whether inputs can manipulate response headers by injecting CRLF sequences across response lines and header fields. This tests the unauthenticated attack surface and does not require credentials. Rocket’s compile-time guarantees and strong typing reduce some classes of bugs, but they do not prevent logic-level flaws where concatenated strings form headers. The scanner’s checks include response splitting risks and reports findings with severity and remediation guidance mapped to OWASP API Top 10 and other compliance frameworks.

Rust-Specific Remediation in Rocket — concrete code fixes

To prevent Crlf Injection in Rocket with Rust, validate and sanitize any user-controlled data before using it in headers or the response body. Avoid concatenating raw input into header values; instead, use Rocket’s built-in facilities and strict allowlists. Below are concrete, safe patterns and examples.

  • Safe header setting with validation: Use a strict allowlist and do not embed newlines. Prefer rocket::http::Header over raw strings.
use rocket::response::Response;
use rocket::http::Header;
use rocket::serde::json::Json;
use rocket::{get, State};

#[get("/user<id>")]
fn get_user(id: u64, accept_language: rocket::request::Header<'_, &str>) -> Response {
    // Validate header value: allow only alphanumeric and basic punctuation
    let value = accept_language.value();
    if !value.chars().all(|c| c.is_ascii_alphanumeric() || c == ' ' || c == '-' || c == '_') {
        return Response::build()
            .status(rocket::http::Status::BadRequest)
            .header(rocket::http::ContentType::JSON)
            .sized_body(format!(r#"{{"error":"invalid header value"}}"#).into_bytes())
            .finalize();
    }
    Response::build()
        .header(Header::new("X-Locale", value.to_string()))
        .ok()
        .unwrap_or_else(|| Response::build().status(rocket::http::Status::InternalServerError).finalize())
}
  • Safe cookie setting: Use Rocket’s CookieJar for setting cookies instead of constructing Set-Cookie headers manually with user input.
use rocket::http::Cookie;
use rocket::request::FlashMessage;
use rocket::response::Redirect;

#[get("/login")]
fn login(jar: &rocket::http::CookieJar) -> Redirect {
    // Use CookieJar to set cookies safely; it handles encoding and prevents injection
    jar.add_private(Cookie::new("session_id", "abc123"));
    Redirect::to(uri!(dashboard))
}
  • Response body: When reflecting user input in the body, ensure newline characters are encoded or replaced. For JSON responses, use a serializer that escapes control characters.
use rocket::serde::json::json;

#[get("/echo")]
fn echo(name: String) -> rocket::serde::json::Json<serde_json::Value> {
    // Sanitize by removing or replacing newlines/carriage returns
    let sanitized = name.replace(|c| c == '\r' || c == '\n', "_");
    rocket::serde::json::Json(json!({ "echo": sanitized }))
}

These patterns ensure that CRLF sequences cannot split responses or headers. When using middleBrick’s CLI (middlebrick scan <url>) or adding the GitHub Action to your CI/CD pipeline, you can validate that such mitigations are present and that the endpoint receives a secure risk score. For continuous monitoring, the Pro plan provides scheduled scans and alerts for regressions, and the MCP Server allows you to run checks directly from your IDE while developing Rocket routes.

Frequently Asked Questions

Can Crlf Injection affect Rocket APIs that use OpenAPI specs?
Yes. If the OpenAPI spec permits user input in headers or cookies without constraints, middleBrick’s spec-aware checks will flag the endpoint during scanning. Validate and encode all user data regardless of spec documentation.
Does middleBrick fix Crlf Injection findings automatically?
No. middleBrick detects and reports findings with remediation guidance. Developers must apply Rust-specific fixes in Rocket, such as input validation and using CookieJar, and re-scan to confirm resolution.