HIGH container escapefastapidynamodb

Container Escape in Fastapi with Dynamodb

Container Escape in Fastapi with Dynamodb — how this specific combination creates or exposes the vulnerability

A container escape in a Fastapi service that uses DynamoDB typically arises when an attacker can manipulate how the application constructs and executes shell commands or subprocesses that reference DynamoDB resources. If Fastapi endpoints build shell commands using user-controlled input—such as table names, key condition expressions, or AWS CLI flags—and pass them to os.system, subprocess.run, or similar execution functions, the attacker can escape the container’s intended execution context. Running within a container limits process access, but command injection combined with DynamoDB operations can provide the foothold needed to reach the host runtime or other containers.

For example, suppose a Fastapi endpoint accepts a table name and uses it to run an AWS CLI query. If the input is not strictly validated or sanitized, an attacker can supply a table name like mytable; id=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/). When the command is executed, the injected segment runs in the container’s process space, potentially exposing instance metadata that can lead to further host compromise. This pattern is especially risky when the container runs with elevated capabilities or when the runtime uses bind mounts that expose sensitive host paths. Even without host filesystem access, an insecure Fastapi endpoint that forwards user input to DynamoDB operations via shell commands can become a pivot point for lateral movement or privilege escalation.

The interaction between Fastapi’s request handling, DynamoDB’s API surface, and container isolation boundaries amplifies the impact of insecure coding practices. A common misconfiguration is permissive CORS or overly broad IAM policies attached to the container task role, which allow any injected command context to query or modify a wide range of DynamoDB tables. If the container’s entrypoint or orchestration scripts rely on environment variables to construct AWS CLI calls, environment variable injection can further expand the attack surface. Because DynamoDB operations often appear benign—read and write calls—developers may overlook how command construction paths can bypass container restrictions. The scanner’s checks for OS command injection and SSRF, combined with runtime behavior around unauthenticated endpoints, help highlight these risky patterns before they are exploited in production.

Dynamodb-Specific Remediation in Fastapi — concrete code fixes

Remediation centers on strict input validation, avoiding shell command construction, and using the AWS SDK directly with parameterized inputs. Never concatenate user input into CLI commands or shell strings. Instead, use the boto3 client with explicit parameter structures and enforce allowlists on identifiers such as table names.

Below is a secure Fastapi example that validates the table name against an allowlist, uses boto3 to query DynamoDB, and returns items safely without shell involvement:

from fastapi import Fastapi, HTTPException, Query
import boto3
from pydantic import BaseModel

app = Fastapi()
# Allowlist for table names — do not rely on user input to select tables
ALLOWED_TABLES = {"users", "orders", "products"}

class Item(BaseModel):
    pk: str
    sk: str
    data: dict

def get_table(table_name: str):
    if table_name not in ALLOWED_TABLES:
        raise ValueError("Table not allowed")
    dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
    return dynamodb.Table(table_name)

@app.get("/items/{table_name}", response_model=list[Item])
def read_items(
    table_name: str,
    limit: int = Query(10, ge=1, le=50)
):
    try:
        table = get_table(table_name)
        response = table.scan(Limit=limit)
        items = response.get("Items", [])
        # Ensure consistent pagination handling in production
        return items
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal error")

If you must use the AWS CLI for operational workflows, construct commands programmatically without user-controlled segments in the command path. For example, use subprocess with a list of arguments and pass the table name as a variable that is validated against an allowlist, rather than interpolating it into a shell string:

import subprocess
import shlex

# Safe approach: use a list and avoid shell=True
def aws_query_table(table_name: str, key_condition: str):
    if table_name not in {"users", "orders"}:
        raise ValueError("Invalid table")
    # key_condition should also be constrained; this is illustrative
    cmd = ["aws", "dynamodb", "query", "--table-name", table_name, "--key-condition-expression", key_condition]
    result = subprocess.run(cmd, capture_output=True, text=True, check=False)
    if result.returncode != 0:
        raise RuntimeError(f"AWS CLI error: {result.stderr}")
    return result.stdout

Additionally, enforce least-privilege IAM roles for the container so that even if an injection occurs, the scope of accessible DynamoDB resources is limited. Combine this with network policies that restrict egress to known AWS endpoints, reducing the impact of SSRF or metadata service exposure. Regularly rotate credentials and prefer IAM roles attached to the container runtime rather than static keys stored in environment variables.

Frequently Asked Questions

Can a container escape via DynamoDB alone without command injection?
DynamoDB by itself does not execute code, so an escape requires a command or code execution path in the Fastapi service. Without shell or process execution, DynamoDB access remains constrained to the permissions of the IAM role.
Does scanning with middleBrick detect container escape risks tied to DynamoDB endpoints?
middleBrick runs checks for OS command injection and SSRF that can surface risky patterns when user input influences DynamoDB interactions. Findings include remediation guidance to harden Fastapi endpoints and reduce container escape risk.