flawopen.com/Cross-Site Scripting/Python

Cross-Site Scripting in Python

Alta CWE-79 Draft — pending review
Language: English Português (Brasil) Español Français Deutsch Русский 简体中文 日本語 हिन्दी 한국어 Bahasa Indonesia
Explicación simple

Imagine a guestbook where a visitor writes a note containing hidden script tags that execute in the browser of the next person who opens the page.

Términos clave en esta página
output encoding
Converting special markup characters into safe entities so browsers display them as text rather than script.

Qué está pasando

Cross-Site Scripting in Python occurs when untrusted input is formatted directly into HTML strings instead of using template auto-escaping.

Impacto en el mundo real

In 2005, the Samy XSS worm infected over 1 million user profiles on MySpace in under 20 hours, forcing the platform offline.

Documented historical AppSec case study.

Vulnerable vs. corregido

VULNERABLE
# username inserted with no escaping
@app.route("/welcome")
def welcome():
  name = request.args.get("name")
  return f"
Welcome, {name}
"
FIXED
# Jinja2 template auto-escapes by default
@app.route("/welcome")
def welcome():
  name = request.args.get("name")
  return render_template("welcome.html", name=name)

Por qué funciona la solución

Template engines like Jinja2 and Django auto-escape HTML entities by default, rendering markup inert.

Puntos críticos específicos

Django mark_safe() and Jinja2 | safe

Marking untrusted data as safe disables all escaping, reopening stored and reflected XSS.

f-strings bypass templates

Python f-strings execute before template rendering, bypassing auto-escaping entirely.

Conceptos errneos comunes

"f-strings are safe inside templates"

f-strings evaluate before template escaping happens, leaving user input completely raw.

Cómo comprobar si está afectado

grep -rn "render_template_string(.*f\"" --include="*.py" . grep -rn "mark_safe(" --include="*.py" .
Run Bandit with rule B701 (jinja2_autoescape_false) in CI to catch unescaped templates automatically.

Lista de comprobación de prevención

Preguntas frecuentes

Does Flask escape by default?

Yes, for .html, .htm, and .xml template extensions rendered with render_template().

Referencias

Ver también: SQL Injection Command InjectionPath Traversal