Symlink Attack in Fastapi with Dynamodb
Symlink Attack in Fastapi with Dynamodb — how this specific combination creates or exposes the vulnerability
A symlink attack in a Fastapi service that uses DynamoDB typically occurs when user-influenced paths or keys are used to locate files or to derive item keys, and an attacker can control part of that path to traverse directories or overwrite arbitrary files. Although DynamoDB itself does not have a filesystem, the vulnerability surfaces when your application writes files locally (for example, user uploads, exported reports, or cache files) and constructs file paths using data that may come from or be influenced by DynamoDB item attributes.
Consider a Fastapi endpoint that retrieves a user profile from DynamoDB and uses an attribute such as sub or a provided file_key to build a local path for reading or writing files:
import os
from fastapi import FastAPI, HTTPException
import boto3
app = FastAPI()
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("UserProfiles")
@app.get("/export/{user_id}")
def export_user(user_id: str):
# Assume user_id is used both in DynamoDB and in a local filename
safe_name = user_id.strip()
file_path = os.path.join("/tmp/exports", f"{safe_name}.csv")
# Potential symlink race: file_path can be manipulated to point outside intended directory
with open(file_path, "w") as f:
f.write("mock export")
return {"path": file_path}
If an attacker provides a user_id like ../../../etc/passwd after stripping, and the application does not fully sanitize or isolate the path, the resolved file path can escape the intended directory. Even if DynamoDB stores only the canonical user_id, the attacker may supply a crafted value at the API layer, and the symlink can be created on the host filesystem before the file is written. This can lead to unauthorized file overwrites, information disclosure, or privilege escalation on the host.
Another scenario involves symbolic links in storage mounted alongside DynamoDB workflows (for example, backups or artifact storage). If your application trusts item metadata from DynamoDB to reconstruct paths for archival operations, an attacker who can inject a crafted attribute (e.g., through a compromised admin interface or a malicious item put by another vector) can cause the application to follow a symlink that points to a sensitive location. DynamoDB does not store symlinks, but your application’s use of item attributes to guide filesystem operations is where the cross-domain risk arises.
Additionally, unauthenticated endpoints or weak authorization checks (BOLA/IDOR) can allow an attacker to read or write DynamoDB items that contain path-influencing attributes. Combined with filesystem operations that resolve symlinks, this can turn a DynamoDB item read into a path traversal or overwrite via a malicious symlink present on the filesystem. The 12 checks run by middleBrick—such as Input Validation, Authentication, BOLA/IDOR, and Property Authorization—would highlight whether user-controlled data directly influences local file paths and whether symlink resolution is safely constrained.
Dynamodb-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on isolating DynamoDB item attributes from filesystem paths and strictly validating any path construction. Avoid using user-controlled values to build filesystem paths. If you must store a file reference, store a random, server-generated identifier in DynamoDB and keep the mapping server-side.
Use a strict allowlist for filenames and normalize paths to ensure symlinks cannot escape the intended directory. Prefer os.path.realpath to detect symlinks and reject paths that resolve outside the target base directory. Below is a hardened Fastapi pattern that uses DynamoDB with safe path handling:
import os from fastapi import FastAPI, HTTPException, Depends import boto3 from pydantic import BaseModel app = FastAPI() dynamodb = boto3.resource("dynamodb", region_name="us-east-1") table = dynamodb.Table("UserProfiles") EXPORT_BASE = os.path.abspath("/tmp/exports") class ExportRequest(BaseModel): user_id: str def safe_path(base: str, user_id: str) -> str: # Normalize and restrict to base directory candidate = os.path.normpath(os.path.join(base, f"{user_id}.csv")) if not candidate.startswith(base): raise HTTPException(status_code=400, detail="Invalid user_id") # Ensure the final path does not resolve through symlinks outside base real_base = os.path.realpath(base) real_candidate = os.path.realpath(candidate) if not real_candidate.startswith(real_base): raise HTTPException(status_code=400, detail="Path traversal detected") return real_candidate @app.post("/export") def export_user(req: ExportRequest): # Validate user_id format strictly (alphanumeric + safe chars) if not req.user_id.replace("-", "").replace("_", "").isalnum(): raise HTTPException(status_code=400, detail="Invalid user_id format") file_path = safe_path(EXPORT_BASE, req.user_id) # Optionally verify item exists in DynamoDB before writing resp = table.get_item(Key={"user_id": req.user_id}) if "Item" not in resp: raise HTTPException(status_code=404, detail="User not found") with open(file_path, "w") as f: f.write("mock export") return {"path": file_path}Key practices:
- Never concatenate user input into filesystem paths without strict validation and normalization.
- Use server-generated filenames or tokens stored in DynamoDB instead of exposing filesystem paths via API responses.
- Resolve real paths with
os.path.realpathand enforce that resolved paths remain within the intended directory tree. - Apply the same validation principles to any artifact storage, log paths, or temporary file operations triggered by DynamoDB item attributes.
middleBrick scans would flag the initial pattern as risky under Input Validation, BOLA/IDOR, and Property Authorization, and the remediation aligns with the findings and guidance provided in the scan report.
Frequently Asked Questions
How does middleBrick detect risks related to symlinks and DynamoDB in Fastapi APIs?
Can the middleBrick CLI generate a report that includes specific remediation for symlink risks with DynamoDB?
middlebrick scan <url> to get a JSON or text report that includes severity, category, and remediation guidance for findings such as unsafe path construction involving DynamoDB-derived attributes and symlink risks.