logo

Database

Python Starlette Html Injection

Description

This detector identifies HTML injection vulnerabilities in Python applications using the Starlette web framework. It finds locations where user-controlled data is directly embedded into HTML responses without proper sanitization, which can lead to Cross-Site Scripting (XSS) attacks where malicious scripts execute in users' browsers.

Weakness:

045 - HTML code injection

Category: Unexpected Injection

Detection Strategy

    • The application must import the Starlette web framework (import statements containing 'starlette')

    • Code must use Starlette's HTML response classes (like HTMLResponse) or general response classes (like Response) configured for HTML content

    • The HTML response must contain user-controlled or tainted data that flows directly into the response without sanitization

    • The data flow analysis confirms that untrusted input reaches the HTML response construction

Vulnerable code example

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

async def vulnerable_endpoint(request: Request):
    # VULNERABLE: User input directly rendered as HTML without escaping
    name = request.query_params.get("name", "World")
    html = f"<h1>Hello, {name}!</h1>"
    return HTMLResponse(html)  # XSS vulnerability

✅ Secure code example

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

async def secure_endpoint(request: Request):
    # SAFE: escape() encodes <>&"' preventing script injection
    name = escape(request.query_params.get("name", "World"))
    html = f"<h1>Hello, {name}!</h1>"...