HIGH man in the middleactixbasic auth

Man In The Middle in Actix with Basic Auth

Man In The Middle in Actix with Basic Auth — how this specific combination creates or exposes the vulnerability

When Basic Authentication is used in an Actix web service without transport-layer protection, credentials are encoded but not encrypted. An attacker who can observe or modify traffic between the client and server can perform a Man In The Middle (MitM) interception. Because Base64 is easily reversible, intercepted Authorization headers can be decoded to recover usernames and passwords in cleartext.

In an Actix application, if an endpoint relies solely on Basic Auth over HTTP, a network adversary on the same LAN, Wi‑Fi, or through a compromised router can capture requests and replay or modify them. This exposes the application to credential theft, session hijacking, and unauthorized access to protected resources. Even when TLS is available, misconfigurations—such as missing HTTPS enforcement or accepting insecure ciphers—can leave the channel vulnerable to downgrade attacks that strip encryption and expose Basic credentials.

Because middleBrick scans the unauthenticated attack surface, it can detect whether an API endpoint accepts requests over HTTP, whether the login surface is reachable without TLS, and whether authentication is performed in a way that relies on obscurity rather than cryptographic protection. The scanner also checks whether input validation and transport protections are consistent with the declared security design, highlighting gaps such as missing HSTS or lack of secure cookie attributes that compound MitR risks.

Basic Auth-Specific Remediation in Actix — concrete code fixes

To mitigate MitM risks with Basic Auth in Actix, enforce HTTPS for all endpoints and avoid sending credentials over unencrypted channels. Combine transport security with strict validation and secure defaults. Below are concrete Actix examples demonstrating a secure setup.

Enforce HTTPS and secure Basic Auth in Actix

Always redirect HTTP to HTTPS and configure TLS with strong ciphers. Use middleware to require secure connections and avoid conditional acceptance of cleartext HTTP.

use actix_web::{web, App, HttpResponse, HttpServer, middleware::Logger};
use actix_web::http::header::HeaderValue;
use actix_web::dev::ServiceRequest;
use actix_web::error::ErrorUnauthorized;
use std::future::{ready, Ready};

async fn basic_auth_middleware(
    req: ServiceRequest,
    credentials: (&'static str, &'static str),
) -> Result {
    let (valid_user, valid_pass) = credentials;
    match req.headers().get("Authorization") {
        Some(header_value) => {
            let header_str = header_value.to_str().unwrap_or("");
            if header_str.starts_with("Basic ") {
                let encoded = &header_str[6..];
                // decode base64
                if let Ok(decoded) = base64::decode(encoded) {
                    if let Ok(credentials) = String::from_utf8(decoded) {
                        let parts: Vec<&str> = credentials.splitn(2, ':').collect();
                        if parts.len() == 2 && parts[0] == valid_user && parts[1] == valid_pass {
                            return Ok(req);
                        }
                    }
                }
            }
        }
        None => (),
    }
    Err((ErrorUnauthorized("Unauthorized"), req))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .wrap_fn(|req, srv| {
                let credentials = ("admin", "s3cur3P@ssw0rd");
                basic_auth_middleware(req, credentials).map_err(|(e, req)| e.into())
            })
            .route("/secure", web::get().to(|| async { HttpResponse::Ok().body("Authenticated access granted") }))
    })
    .bind_rustls(
        "0.0.0.0:8443",
        rustls::ServerConfig::builder()
            .with_safe_defaults()
            .with_no_client_auth()
            .with_single_cert(
                vec![rustls_pemfile::certs(&mut std::io::BufReader::new(std::fs::File::open("cert.pem").unwrap())).unwrap().into_iter().collect()],
                rustls_pemfile::pkcs8_private_keys(&mut std::io::BufReader::new(std::fs::File::open("key.pem").unwrap())).unwrap().remove(0),
            )
            .unwrap(),
    )?.
    run()
    .await
}

The example above demonstrates TLS termination using rustls with a certificate and private key, ensuring that all communication is encrypted in transit. The middleware extracts and validates the Basic Auth header, rejecting requests that do not present valid credentials. By requiring HTTPS, the attack surface for MitM is significantly reduced because intercepted traffic cannot be decoded without the private key.

Complementary mitigations

  • Use short-lived credentials and rotate them regularly to limit exposure if leaked.
  • Add strict CORS policies and prevent credential transmission over insecure origins.
  • Set the Secure and HttpOnly flags on any cookies used in conjunction with authentication.
  • Enable HTTP Strict Transport Security (HSTS) to prevent protocol downgrade attacks.

These practices align with the checks performed by middleBrick, which evaluates whether endpoints use encryption, whether authentication is properly enforced, and whether the API surface adheres to security best practices such as those found in the OWASP API Security Top 10.

Frequently Asked Questions

Can Basic Auth be used safely in Actix if HTTPS is enforced?
Yes, when HTTPS is enforced with strong TLS settings, Basic Auth can be used safely because the credentials are protected in transit. Always redirect HTTP to HTTPS and use a middleware that validates the Authorization header, as shown in the code examples.
What does middleBrick check related to MitM and Basic Auth in Actix APIs?
middleBrick checks whether endpoints accept unencrypted HTTP, whether authentication is transport-dependent, and whether security headers like HSTS are present. It also cross-references spec definitions with runtime behavior to highlight weak authentication exposure that could facilitate MitM attacks.