HIGH broken authenticationaxumbasic auth

Broken Authentication in Axum with Basic Auth

Broken Authentication in Axum with Basic Auth — how this specific combination creates or exposes the vulnerability

Basic Authentication over unencrypted channels is a common source of broken authentication in Axum-based services. When HTTP Basic Auth is used without TLS, credentials are base64-encoded and sent in plaintext on the wire, making interception trivial. middleBrick flags this as a high-severity data exposure finding because base64 is not encryption and offers no confidentiality.

Even when TLS is used, implementation issues can weaken authentication. Common missteps include failing to validate the Authorization header correctly, accepting credentials via query parameters or logs, and not enforcing secure cookie attributes when sessions are derived from Basic Auth. MiddleBrick’s authentication checks verify that credentials are only transmitted over encrypted connections and that no credentials are exposed in URLs or server logs.

Another Axum-specific risk is improper integration with middleware. For example, wrapping routes with a Basic Auth extractor but not enforcing it across all sub-routers can leave some endpoints unauthenticated. This inconsistent enforcement can lead to IDOR-related access issues, where authenticated users can manipulate resource IDs to access other users’ data. middleBrick tests for BOLA/IDOR alongside authentication to detect cases where authentication is present but authorization is insufficient.

Credential management also matters. Hardcoding usernames and passwords in source code—common in small Axum projects—creates a security risk if repositories are exposed. middleBrick’s inventory management checks look for indicators like plaintext credentials in common config file patterns and flags them as unsafe consumption issues.

Finally, without rate limiting, Basic Auth endpoints are vulnerable to credential brute-forcing. Axum developers must combine authentication with rate limiting middleware to mitigate automated attacks. middleBrick’s rate limiting checks confirm that authentication endpoints are protected by sufficient request throttling and backoff mechanisms.

Basic Auth-Specific Remediation in Axum — concrete code fixes

To fix broken authentication in Axum with Basic Auth, always enforce TLS, use secure extractors, and avoid storing credentials in code. Below are concrete Axum examples that align with middleBrick’s recommended remediation guidance.

1. Enforce HTTPS and validate credentials securely:

use axum::{
    async_trait,
    extract::{FromRequest, Request},
    response::IntoResponse,
    routing::get,
    Router,
};
use std::convert::Infallable;
use headers::authorization::{Authorization, Basic};
use hyper::StatusCode;

#[async_trait]
impl FromRequest<S> for AuthenticatedUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request(req: Request, _state: &S) -> Result {
        let auth = req.headers().typed_get::<Authorization<Basic>>()
            .ok_or((StatusCode::UNAUTHORIZED, "Missing authorization header"))?;
        let user = auth.user_id();
        let pass = auth.password().unwrap_or("");
        // Validate credentials against a secure store (e.g., database with hashed passwords)
        if valid_credentials(user, pass) {
            Ok(AuthenticatedUser { user: user.to_string() })
        } else {
            Err((StatusCode::UNAUTHORIZED, "Invalid credentials"))
        }
    }
}

async fn valid_credentials(user: &str, pass: &str) -> bool {
    // In production, use constant-time comparison and hashed passwords
    user == "appuser" && pass == "StrongPassw0rd!"
}

async fn handler() -> &'static str {
    "Authenticated"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/secure", get(handler).layer(axum::middleware::from_extractor_with_extractor::<AuthenticatedUser>()));

    // Listen on HTTPS in production
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8443").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

This example shows a typed extractor that requires a valid Authorization header. It avoids logging credentials and uses constant-time checks in a real implementation (placeholder valid_credentials). middleBrick would verify that this extractor is applied to all sensitive routes and that TLS is enforced.

2. Use middleware for rate limiting and avoid query parameters:

use axum::middleware;
use tower_http::limit::RateLimitLayer;
use std::time::Duration;

let app = Router::new()
    .route("/secure", get(handler).layer(axum::middleware::from_extractor::<AuthenticatedUser>()))
    .layer(
        RateLimitLayer::new(10, Duration::from_secs(1)) // 10 requests per second
    );

The rate limiting layer protects the authentication endpoint from brute force attacks. middleBrick’s rate limiting checks ensure such a layer is present and correctly configured.

3. Never embed credentials in source code or config files that are checked into version control. Use environment variables or a secrets manager, and validate them at runtime.

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

Can Basic Auth be used securely in Axum without TLS?
No. Basic Auth encodes credentials but does not encrypt them. Without TLS, credentials are exposed in transit. middleBrick flags unencrypted Basic Auth as high-severity data exposure.
How does middleBrick detect authentication issues in Axum APIs?
middleBrick performs black-box checks against the running endpoint, verifying whether authentication is required for sensitive routes, whether credentials leak in URLs or logs, and whether rate limiting is applied to authentication paths.