Replay Attack in Flask with Basic Auth
Replay Attack in Flask with Basic Auth — how this specific combination creates or exposes the vulnerability
A replay attack occurs when an attacker intercepts a valid authentication request and retransmits it to gain unauthorized access. When Flask applications use HTTP Basic Auth without additional protections, this risk is pronounced because credentials are reused across requests. Basic Auth encodes the username and password with Base64, which is easily reversible; therefore, interception of the request reveals the credentials. Without transport security or nonce mechanisms, an attacker who captures an HTTPS-encrypted packet (for example via a compromised proxy or malicious network) can replay the Authorization header to impersonate the user.
Flask itself does not provide built-in replay protection for Basic Auth. If endpoints do not enforce strict rules such as one-time use tokens, timestamps, or cryptographic nonces, the same Authorization header can be accepted multiple times. This is especially dangerous when session management is weak or absent, allowing an intercepted header to retain validity for an extended period. Insecure storage of credentials on the server side (e.g., plaintext or weakly hashed passwords) further compounds the impact, as attackers who obtain a database dump can also replay authentication attempts.
Because middleBrick scans the unauthenticated attack surface, it can detect endpoints that accept static Authorization headers and lack replay defenses. Findings typically highlight the absence of per-request nonces or timestamps, which enables attackers to reuse credentials. The scanner evaluates whether the API’s design permits repeated identical requests and flags the lack of mechanisms such as OAuth2 with rotating tokens or server-side session invalidation as a security risk.
Basic Auth-Specific Remediation in Flask — concrete code fixes
To mitigate replay attacks in Flask with Basic Auth, implement per-request nonces or timestamps and enforce HTTPS for all traffic. Below are concrete code examples showing how to add a timestamp-based replay protection layer to a Flask Basic Auth endpoint. This approach ensures that each request includes a timestamp and a server-side validation window, making captured headers useless after a short period.
from flask import Flask, request, Response
import base64
import time
app = Flask(__name__)
# Simple in-memory store for used nonces/timestamps (use Redis or a DB in production)
used_nonces = {}
def verify_auth(auth_header):
if not auth_header or not auth_header.startswith('Basic '):
return None
encoded = auth_header.split(' ')[1]
try:
decoded = base64.b64decode(encoded).decode('utf-8')
username, password = decoded.split(':', 1)
return username, password
except Exception:
return None
def is_replayed(timestamp):
# Reject requests older than 2 minutes to prevent replay
now = time.time()
if now - timestamp > 120:
return True
# Ensure nonce uniqueness within the window
nonce = f"{timestamp}"
if nonce in used_nonces and used_nonces[nonce]:
return True
used_nonces[nonce] = True
return False
@app.route('/api/protected')
def protected():
auth = request.headers.get('Authorization')
user = verify_auth(auth)
if user is None:
return Response('Could not verify your access level for that URL.', 401, {'WWW-Authenticate': 'Basic'})
username, password = user
# In practice, validate credentials against a secure store
if username != 'admin' or password != 'secret':
return Response('Invalid credentials', 403)
# Replay protection: require a timestamp header
timestamp_header = request.headers.get('X-Request-Timestamp')
if not timestamp_header:
return Response('Missing timestamp', 400)
try:
timestamp = float(timestamp_header)
except ValueError:
return Response('Invalid timestamp', 400)
if is_replayed(timestamp):
return Response('Replay detected', 403)
return Response(f'Hello, {username}')
if __name__ == '__main__':
app.run(ssl_context='adhoc') # Enforce HTTPS in development
For production, pair this with HTTPS enforcement and consider using framework extensions that support secure cookie-based sessions or token rotation. middleBrick’s scans can validate that endpoints reject repeated identical Authorization headers and enforce timestamp or nonce checks, providing prioritized remediation guidance mapped to frameworks such as OWASP API Top 10.