HIGH missing tlsfastapihmac signatures

Missing Tls in Fastapi with Hmac Signatures

Missing Tls in Fastapi with Hmac Signatures — how this specific combination creates or exposes the vulnerability

Transport Layer Security (TLS) is the baseline network protection that ensures confidentiality and integrity for HTTP traffic. When a FastAPI service that uses Hmac Signatures does not enforce TLS, the signature and the payload travel in plaintext. An on-path attacker can observe the raw HTTP request, extract the signature header, and replay the request to the same endpoint while the signature remains valid. This replay bypasses application-level integrity checks because the signature was computed over the exact request body and headers, and the server will accept it if it arrives unmodified over an insecure channel. MiddleBrick scans this attack surface and flags Missing Tls as a high-severity finding because the security properties of Hmac Signatures are only as strong as the transport protecting them.

In FastAPI, a common pattern is to compute an Hmac using a shared secret and a canonical representation of the request (method, path, selected headers, and body). Developers may assume that signatures alone prevent tampering, but without TLS they do not prevent interception and replay. For example, if a client sends a POST to http://api.example.com/payments with x-signature: sha256=abcd1234, an attacker can capture that header and body and reissue the request to the same host over HTTP. The server validates the Hmac successfully because the data and signature match, and the request is processed as legitimate. This scenario maps to the OWASP API Security Top 10 controls around Security Schemes and Integrity, and can also intersect with BOLA/IDOR if the signature includes a user identifier that the server trusts without additional context.

Compliance frameworks such as PCI-DSS and SOC2 expect encryption in transit for any system handling sensitive data or authentication material. MiddleBrick’s LLM/AI Security checks do not apply here, but the scan will highlight Missing Tls and provide remediation guidance, including enforcing HTTPS, using HTTP Strict Transport Security (HSTS), and rotating shared secrets if exposure is suspected. The 5–15 second scan tests the unauthenticated attack surface and surfaces this risk so teams can remediate before deploying to production.

Hmac Signatures-Specific Remediation in Fastapi — concrete code fixes

To remediate Missing Tls in FastAPI when using Hmac Signatures, you must enforce HTTPS and ensure that the signature verification logic is robust. Below are concrete, working code examples that demonstrate a secure approach.

First, enforce TLS by configuring FastAPI to accept only secure requests in production and by using middleware that redirects HTTP to HTTPS. In your application startup, load settings that control the expected scheme:

from fastapi import FastAPI, Request, HTTPException, Header
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
import hmac
import hashlib
import os

app = FastAPI()

# Enforce HTTPS in production
app.add_middleware(HTTPSRedirectMiddleware)

# Shared secret stored securely, e.g., from environment variables
SHARED_SECRET = os.getenv("WEBHOOK_SECRET", "change-this-in-production")

def verify_hmac_signature(body: bytes, signature_header: str) -> bool:
    if not signature_header or not signature_header.startswith("sha256="):
        return False
    expected_sig = signature_header.split("=", 1)[1]
    mac = hmac.new(SHARED_SECRET.encode("utf-8"), body, hashlib.sha256)
    return hmac.compare_digest(mac.hexdigest(), expected_sig)

Next, implement an endpoint that validates the Hmac signature using a canonical representation. In this example, we use the raw request body and a fixed set of headers to compute the signature on the client and verify it on the server:

@app.post("/webhook")
async def webhook(
    request: Request,
    x_signature: str = Header(None, alias="X-Signature")
):
    body = await request.body()
    if not verify_hmac_signature(body, x_signature):
        raise HTTPException(status_code=401, detail="Invalid signature")
    # Process the verified payload
    return {"status": "ok"}

For client-side code, generate the Hmac using the same canonical approach. The example below shows a Python client that computes the signature from method, path, selected headers, and body, then sends them to the FastAPI service over HTTPS:

import hmac
import hashlib
import requests

shared_secret = "your-client-and-server-shared-secret"
method = "POST"
path = "/webhook"
headers_to_sign = {"content-type": "application/json"}
body = '{"amount": 100, "currency": "USD"}'

# Canonical string: method\npath\nheader1:value1\nbody
canonical = f"{method}\n{path}\n"
for k, v in headers_to_sign.items():
    canonical += f"{k}:{v}\n"
canonical += body

signature = hmac.new(
    shared_secret.encode("utf-8"),
    canonical.encode("utf-8"),
    hashlib.sha256
).hexdigest()

headers = {
    "Content-Type": "application/json",
    "X-Signature": f"sha256={signature}"
}
# Always use HTTPS in production
response = requests.post("https://api.example.com/webhook", data=body, headers=headers)
print(response.status_code)

These examples assume that TLS is terminated at the server and that the FastAPI app is only accessible via HTTPS. The MiddleBrick CLI can be used to validate that your endpoints enforce TLS and that Hmac verification is correctly implemented. By combining transport security with strong signature validation, you reduce the risk of tampering and replay even if other layers are involved, such as Inventory Management or Unsafe Consumption checks.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

Does using Hmac Signatures remove the need for TLS in FastAPI?
No. Hmac Signatures provide integrity and authenticity at the application layer, but they do not protect against eavesdropping, replay, or man-in-the-middle attacks. TLS is still required to secure the transport and to prevent interception of signatures and payloads.
How can I test that my FastAPI Hmac implementation resists replay attacks?
Use a tool like the MiddleBrick CLI to scan your endpoint over HTTP and verify that requests with captured signatures are rejected when TLS is not enforced. Additionally, include a nonce or timestamp in the signed canonical string and validate freshness on the server to prevent replay.