logo

Database

Python Starlette Uncontrolled Format String

Description

Detects uncontrolled format string vulnerabilities in Python Starlette web applications where user input is directly used in HTML responses. This can lead to XSS (Cross-Site Scripting) attacks if user-controlled data is interpolated into HTML content without proper escaping.

Weakness:

089 - Lack of data validation - Trust boundary violation

Category: Unexpected Injection

Detection Strategy

    Check if the Starlette framework is imported in the Python codebase

    Identify HTMLResponse objects that use string formatting operations

    Look for format strings that incorporate user-controlled data from Starlette request objects

    Report a vulnerability when user input is used in format strings within HTML responses without proper sanitization

Vulnerable code example

from starlette.requests import Request
from starlette.responses import HTMLResponse

async def vulnerable_endpoint(request: Request):
    # VULNERABLE: User input used directly as format string template
    user_template = request.query_params.get("msg")
    return HTMLResponse(user_template.format(request))  # Allows object introspection via {0.__init__.__globals__}

✅ Secure code example

from starlette.requests import Request
from starlette.responses import HTMLResponse
from string import Template  # For safe string templating

async def secure_endpoint(request: Request):
    # SAFE: Use Template class which doesn't support attribute access
    user_message = request.query_params.get("msg", "Hello")
    safe_template = Template("Message: $message")  # Fixed template structure...