Hallucination Attacks in Django with Hmac Signatures
Hallucination Attacks in Django with Hmac Signatures — how this specific combination creates or exposes the vulnerability
A hallucination attack in the context of Django with HMAC signatures occurs when an attacker provides manipulated input that causes a server-side verification process to produce incorrect or fabricated outcomes, such as accepting a tampered payload or inferring information about the signing key. This can happen when HMAC verification logic is incomplete, overly permissive, or incorrectly integrated into Django request handling.
One common scenario involves Django endpoints that use HMAC signatures to verify the integrity of incoming JSON or form data but do not enforce strict canonicalization. If the server recomputes the HMAC using a subset of the transmitted parameters while the client signs a different set or order, an attacker can supply additional or reordered fields without invalidating the signature. This mismatch allows the attacker to hallucinate new behavior by adding or modifying parameters that the server mistakenly trusts after verification passes.
Django applications that compute HMAC on raw POST data must ensure consistent byte-for-byte representations. Variations in encoding, such as differences in JSON key ordering, whitespace, or the presence of optional fields, can lead to divergent signatures. If the server normalizes input differently than the client, a valid signature on one side can become invalid on the other, and conversely, an attacker might exploit lenient verification to treat unsigned or partially signed requests as valid, effectively hallucinating a trusted origin.
Another vector arises when HMAC verification is applied only to selected endpoints or only to certain HTTP methods. An attacker may probe for endpoints where signature checks are absent and replay or modify requests, with the server hallucinating authorization based on session cookies or other contextual state rather than the HMAC. This is especially risky when developers assume that HMAC coverage is universal while implementation is partial.
The LLM/AI Security checks in middleBrick specifically probe for system prompt leakage and prompt injection techniques. Although these tests focus on language model endpoints, they highlight a broader principle: untrusted input must not influence the logic that determines whether a signature is trusted. In Django, hallucination attacks exploit similar trust boundaries when signature validation is inconsistent, allowing injected data to change control flow or data interpretation after verification appears to succeed.
Consider a payment confirmation flow where the client sends amount, currency, and a HMAC over these fields. If the server verifies the HMAC but then uses values from the request body directly instead of the signed ones, an attacker can modify the amount post-verification. The server may hallucinate a legitimate high-value transaction because it failed to bind the verified signed data to the processing logic, illustrating how implementation gaps turn HMAC into a false sense of security.
Hmac Signatures-Specific Remediation in Django — concrete code fixes
To remediate hallucination attacks in Django when using HMAC signatures, enforce strict canonicalization, verify all relevant fields, and bind the HMAC check directly to the business logic. Use constant-time comparison to avoid timing attacks and ensure that the same data representation is used for signing and verification.
Below is a concrete example of a Django view that computes and verifies HMAC-SHA256 over a canonical JSON payload. The client and server agree on a shared secret key. The client creates a canonical JSON string by sorting keys, strips whitespace, and computes HMAC. The server performs the same canonicalization and compares signatures using hmac.compare_digest.
import json
import hmac
import hashlib
from django.http import JsonResponse, HttpResponseBadRequest
from django.views import View
# Shared secret; in production, load from a secure vault or environment variable
HMAC_SECRET = b'super-secret-shared-key-2024'
def canonical_json(data):
"""Return a deterministic JSON string with sorted keys and no extra whitespace."""
return json.dumps(data, sort_keys=True, separators=(',', ':')).encode('utf-8')
class PaymentConfirmationView(View):
def post(self, request):
try:
payload = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponseBadRequest('Invalid JSON')
# Require the client to send the signature in a header
received_sig = request.headers.get('X-API-Signature')
if received_sig is None:
return HttpResponseBadRequest('Missing signature')
# Canonicalize the exact data that was signed
canonical = canonical_json(payload)
# Recompute HMAC on the server using the same canonical form
expected_sig = hmac.new(HMAC_SECRET, canonical, hashlib.sha256).hexdigest()
# Constant-time comparison to prevent timing attacks
if not hmac.compare_digest(expected_sig, received_sig):
return HttpResponseBadRequest('Invalid signature')
# Use the values from the canonical payload, not raw request data
amount = payload['amount']
currency = payload['currency']
# Proceed with payment logic using amount and currency bound to the verified signature
return JsonResponse({'status': 'ok', 'amount': amount, 'currency': currency})
For forms or query parameters, apply the same canonicalization strategy. Serialize the relevant parameters in a stable order, include all fields that must be integrity-protected, and reject requests where the HMAC does not match exactly. Avoid adding or omitting fields between client and server; if optional fields are allowed, include them with null values in the canonical form rather than omitting them.
In Django, you can encapsulate this logic into a decorator or middleware to ensure consistent enforcement across endpoints. Store the HMAC secret securely, rotate keys according to policy, and audit that every trusted operation validates the signature immediately before use. Do not treat HMAC as a substitute for authentication; combine it with proper session or token management when user context is required.
The Pro plan of middleBrick supports continuous monitoring and can integrate into your CI/CD pipeline via the GitHub Action. This helps detect regressions in signature handling as code evolves, ensuring that canonicalization logic and verification remain aligned across deployments.
Related CWEs: llmSecurity
| CWE ID | Name | Severity |
|---|---|---|
| CWE-754 | Improper Check for Unusual or Exceptional Conditions | MEDIUM |