HIGH symlink attackfastapihmac signatures

Symlink Attack in Fastapi with Hmac Signatures

Symlink Attack in Fastapi with Hmac Signatures — how this specific combination creates or exposes the vulnerability

A symlink attack in a FastAPI service that uses HMAC signatures can occur when file upload or file retrieval endpoints resolve user-controlled paths without canonicalization. If an endpoint accepts a filename or path parameter, constructs a filesystem path, and then verifies an HMAC over that path or file contents, an attacker can create a symbolic link that points outside the intended directory. Because HMACs are typically computed on the data or on a path string, the signature may still validate while the actual resolved location diverges from what the application expects.

Consider a FastAPI endpoint that allows downloading user documents. The client sends a filename and an HMAC computed over the filename plus a shared secret. The server recomputes the HMAC; if it matches, the server opens the file. An attacker can register a malicious symlink on the server (or in a location the server follows) that points to a sensitive file such as /etc/passwd. When the server joins the user-supplied filename with the upload directory, the symlink causes the open call to resolve to the sensitive file. Because the HMAC was computed over the attacker-controlled path string, the verification passes, leading to unauthorized file disclosure via path traversal through symlink resolution.

This combination is dangerous because HMACs protect integrity of the data or path as provided, but they do not prevent the server from interpreting that path in a different location once filesystem operations occur. If the application does not canonicalize paths (e.g., using os.path.realpath) and ensure the resolved path remains within an allowed directory, the symlink redirects access. The vulnerability maps to OWASP API Top 10 security misconfiguration and broken object-level authorization patterns, and it can be discovered by scanners that test path traversal and symlink-based privilege escalation without requiring authentication.

Hmac Signatures-Specific Remediation in Fastapi — concrete code fixes

To remediate symlink risks while preserving HMAC-based integrity checks, resolve and validate paths before any signature verification and filesystem operation. Use canonical paths, enforce strict allowlists, and avoid using user input directly in filesystem APIs.

import os
from fastapi import FastAPI, Query, HTTPException
import hmac
import hashlib

app = FastAPI()
SECRET = b'super-secret-key'
BASE_DIR = os.path.realpath('uploads')

def verify_hmac(value: str, signature: str) -> bool:
    mac = hmac.new(SECRET, value.encode('utf-8'), hashlib.sha256)
    return hmac.compare_digest(mac.hexdigest(), signature)

@app.get('/download')
async def download_file(filename: str = Query(...), signature: str = Query(...)):
    if not verify_hmac(filename, signature):
        raise HTTPException(status_code=403, detail='invalid signature')
    # canonicalize and ensure path remains under BASE_DIR
    candidate = os.path.realpath(os.path.join(BASE_DIR, filename))
    if not candidate.startswith(BASE_DIR):
        raise HTTPException(status_code=403, detail='path traversal detected')
    if not os.path.isfile(candidate):
        raise HTTPException(status_code=404, detail='not found')
    # safe to open candidate
    with open(candidate, 'rb') as f:
        data = f.read()
    return {'size': len(data)}

Key practices illustrated:

  • Compute HMAC over a canonical, normalized representation of the path or data, not raw user input that could be ambiguous.
  • Use os.path.realpath after joining with the base directory to resolve any symlinks the attacker may have placed.
  • Enforce a strict prefix check against the real base directory to guarantee the resolved path cannot escape.
  • Perform filesystem checks (isfile) after path validation to avoid leaking information via timing differences.

If you use an OpenAPI/Swagger spec with middleBrick, you can align documentation with these secure patterns and let the scanner map runtime behavior against spec definitions, including $ref resolution across components.

Frequently Asked Questions

Can HMAC signatures alone prevent symlink attacks in FastAPI?
No. HMAC signatures ensure integrity of the data or path string but do not prevent the server from resolving symlinks. You must canonicalize paths and enforce directory allowlists before using the path in filesystem operations.
What additional checks should be included in an OpenAPI spec to reduce symlink risk?
Describe path parameters with explicit patterns that disallow path separators, use examples that show canonicalized paths, and document server-side validation steps such as realpath resolution and prefix checks. Tools like middleBrick can cross-reference spec definitions with runtime findings to highlight mismatches.