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.
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>"...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.