HIGH crlf injectionactixbasic auth

Crlf Injection in Actix with Basic Auth

Crlf Injection in Actix with Basic Auth — how this specific combination creates or exposes the vulnerability

Crlf Injection occurs when user-controlled data is reflected in HTTP headers without sanitization, allowing an attacker to inject additional header lines using carriage return (CR, \r) and line feed (LF, \n) sequences. In Actix web applications, this becomes particularly concerning when Basic Authentication is used because the Authorization header value is often parsed and echoed back in error messages, logs, or custom headers. An attacker can supply a crafted username or password containing \r\n sequences, which Actix may forward into downstream logging, redirection, or custom response headers, thereby splitting headers and injecting new ones such as Content-Security-Policy or Set-Cookie.

Basic Auth transmits credentials as a base64-encoded string in the Authorization header (e.g., Authorization: Basic base64(username:password)). If the server decodes this value and includes it in output that is later interpreted as headers, CRLF Injection is feasible. For example, a username like admin\r\nX-Injected: true results in a decoded credential string that contains a newline, enabling header manipulation. Actix middleware or handlers that concatenate user input into headers or logs without validation create a path for response splitting, which can lead to HTTP response smuggling, cache poisoning, or unauthorized cookie setting.

In the context of unauthenticated black-box scanning, middleBrick tests for CRLF Injection by submitting inputs with \r\n sequences in authentication fields and examining whether these sequences appear verbatim in response headers or body content. When combined with Basic Auth, the risk is amplified because the Authorization header is often logged or reflected. A scan may detect missing input validation on the decoded user credentials and flag the endpoint as allowing header injection. This can expose the application to OWASP API Top 10 #1: Improper Asset Management and related injection-based weaknesses, especially if the endpoint also handles sensitive operations or exposes verbose error messages.

Real-world attack patterns include injecting Set-Cookie headers to establish malicious sessions, or smuggling requests between chained proxies. For compliance mappings, findings related to CRLF Injection align with controls in OWASP API Security Top 10 and can be surfaced in middlewareBrick reports with severity ratings and remediation guidance. Note that middleBrick detects and reports these issues but does not perform automatic fixes; developers must validate and sanitize all inputs that may influence HTTP headers.

Basic Auth-Specific Remediation in Actix — concrete code fixes

Remediation focuses on strict validation and encoding of user-supplied credentials before they are used in header construction or logging. Do not directly concatenate decoded Basic Auth values into response headers or logs. Instead, treat the decoded username and password as opaque strings, and sanitize any downstream usage. Use Actix's extractor patterns to separate authentication parsing from business logic, and apply output encoding when values must be reflected.

Below are concrete Actix code examples demonstrating secure handling of Basic Auth credentials.

Example 1: Validating credentials without echoing raw input

use actix_web::{web, HttpResponse, Result};
use base64::Engine;

async fn login_basic(
    auth_header: Option>,
) -> Result {
    if let Some(auth) = auth_header {
        let credentials = auth.user_id(); // username
        let password = auth.password();   // password

        // Validate: allow only alphanumeric and a few safe symbols
        if !credentials.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
            return Ok(HttpResponse::BadRequest().body("Invalid username"));
        }
        if password.chars().all(|c| c.is_alphanumeric() || c == '!' || c == '#') {
            // Proceed with authentication logic
            return Ok(HttpResponse::Ok().body("Authenticated"));
        }
    }
    Ok(HttpResponse::Unauthorized()
        .header("WWW-Authenticate", "Basic realm=\"secure\"")
        .body("Unauthorized"))
}

Example 2: Using middleware to reject dangerous characters

use actix_web::{dev::ServiceRequest, Error};
use actix_web_httpauth::extractors::basic::BasicAuth;

pub fn validate_no_crlf(req: &ServiceRequest, credentials: &BasicAuth) -> Result<(), Error> {
    let username = credentials.user_id();
    let password = credentials.password();

    if username.contains('\r') || username.contains('\n') {
        return Err(actix_web::error::ErrorBadRequest("Invalid username"));
    }
    if password.contains('\r') || password.contains('\n') {
        return Err(actix_web::error::ErrorBadRequest("Invalid password"));
    }
    Ok(())
}

Example 3: Safe logging and header usage

use log::info;

fn safe_log_auth(auth: Option) {
    if let Some(auth) = auth {
        // Do not log raw Authorization header; log only sanitized identifiers
        let username = auth.user_id();
        // Ensure username is sanitized before logging
        let safe_username = username.replace(|c: char| !c.is_alphanumeric(), "_");
        info!(user = %safe_username, "Auth attempt");
    }
}

For automated verification, the CLI tool (middlebrick) can be used to scan endpoints that use Basic Auth and surface CRLF Injection findings. To integrate checks into your workflow, run middlebrick scan <url> from the terminal or add the GitHub Action to fail builds if a risk score drops below your chosen threshold. Teams using the Pro plan gain continuous monitoring and can configure scans on a schedule, while the MCP Server allows AI coding assistants to trigger scans directly from the IDE.

Frequently Asked Questions

How can I test my Actix Basic Auth endpoint for CRLF Injection without a scanner?
Send a request with \r\n sequences in the username or password (e.g., username: admin\r\nX-Injected: true) and inspect response headers and logs to ensure these sequences are not reflected. Do not rely on client-side filtering alone; validate and encode on the server.
Does middleBrick fix CRLF Injection findings automatically?
No. middleBrick detects and reports findings with remediation guidance. Developers must implement input validation and safe handling of credentials as shown in the code examples.