HIGH man in the middleflaskbasic auth

Man In The Middle in Flask with Basic Auth

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

A Man In The Middle (MitM) attack against a Flask route protected with HTTP Basic Auth occurs when an attacker can intercept or alter traffic between the client and the server. Basic Auth encodes credentials with Base64, which is trivial to decode; if the channel is not authenticated and encrypted, an attacker on the same network can capture the Authorization header and reuse it.

Flask itself does not provide transport-layer security. If you serve a login form or an API endpoint over plain HTTP, credentials and session identifiers can be observed and replayed. Even when Basic Auth is used, without HTTPS an attacker can perform session hijacking by sniffing the header and making authenticated requests to the same endpoint. This is especially dangerous in environments such as shared Wi‑Fi, corporate networks, or when traffic passes through proxies and load balancers that terminate TLS inconsistently.

Another MitM risk specific to Basic Auth in Flask arises from request tampering. Because the credentials are sent with every request, an attacker who can modify in-flight traffic might alter the URL, headers, or parameters. For example, if a Flask route uses user-supplied input to construct redirects or to build URLs for downstream services, an attacker could manipulate the Authorization context to access unintended resources. This intersects with BOLA/IDOR when the attacker’s goal is to act as a different user by capturing and replaying a valid credential pair.

MiddlewareBrick’s scans include checks for Encryption and Authentication to surface these risks. The tool evaluates whether endpoints are served over TLS and whether credentials are exposed in plaintext in transit. It also tests for insecure direct object references that can be leveraged when credentials are intercepted, providing findings mapped to OWASP API Top 10 and PCI-DSS controls.

Basic Auth-Specific Remediation in Flask — concrete code fixes

To mitigate MitM with Basic Auth in Flask, enforce HTTPS and avoid sending credentials on unencrypted channels. Use HTTP Strict Transport Security (HSTS) and ensure your TLS configuration is up to date. Never construct redirects or downstream URLs using untrusted input derived from the Authorization header.

Below are concrete, secure examples for Flask using Basic Auth. The first example shows a minimal protected route with HTTPS enforcement and safe credential verification. The second demonstrates how to integrate the pattern with a small application that avoids common pitfalls such as weak comparison or logging credentials.

Example 1: Basic Auth over HTTPS with constant-time comparison

from flask import Flask, request, abort, jsonify
import hmac
import os

app = Flask(__name__)

# In production, store this in a secure secret manager and rotate regularly.
API_USER = "api-client"
API_PASS = os.environ.get("API_PASS")
if not API_PASS:
    raise RuntimeError("Missing API_PASS environment variable")

def verify_auth(username, password):
    # Use constant-time comparison to avoid timing attacks
    if not username or not password:
        return False
    user_ok = hmac.compare_digest(username, API_USER)
    pass_ok = hmac.compare_digest(password, API_PASS)
    return user_ok and pass_ok

@app.route("/secure-data", methods=["GET"])
def secure_data():
    auth = request.authorization
    if auth is None or not verify_auth(auth.username, auth.password):
        abort(401, description="Authentication required")
    # Safe processing: do not echo user input into URLs or headers
    return jsonify({"status": "ok", "data": "sensitive payload"})

if __name__ == "__main__":
    # In production, serve behind a TLS-terminating reverse proxy (e.g., load balancer).
    # Do not use development server for HTTPS in production.
    app.run(ssl_context=("cert.pem", "key.pem"))

Example 2: MiddleBrick integration and runtime checks

When you add MiddleBrick to your workflow, you can validate that your Flask endpoints are served with encryption and proper authentication. Use the CLI to scan a staging URL and review findings before promotion.

# Scan a Flask endpoint from terminal
# $ middlebrick scan https://staging.example.com/api/secure-data

The scanner checks whether the endpoint requires authentication, whether credentials are transmitted over an encrypted channel, and whether there are signs of BOLA/IDOR that could be chained with intercepted credentials. Findings are reported with severity, remediation guidance, and mapping to compliance frameworks.

Frequently Asked Questions

Is HTTP Basic Auth safe if I use it over HTTPS?
Yes, Basic Auth can be safe over HTTPS because the credentials are encrypted in transit. However, you must still enforce TLS site-wide (e.g., HSTS), use strong secrets, and protect against token leakage and replay. Always prefer token-based mechanisms (e.g., OAuth2 or API keys with short lifetimes) where possible.
How can I prevent credential replay if a MitM captures a Basic Auth header?
To reduce replay risk, serve all traffic over strict HTTPS with strong cipher suites, rotate credentials regularly, and avoid using static credentials for long-lived sessions. Consider adding per-request nonces or timestamps in custom headers and validate them server-side to detect replays. MiddleBrick’s Authentication and Encryption checks can help identify weak configurations.