Django Markdown Rendering XSS Fix – nh3 Sanitization

Django AppSec

Goal

Make the render_markdown template filter in the creolecorner Django app safe to apply to user-supplied text, while keeping fenced code blocks and Pygments syntax highlighting working.

Setup

render_markdown (apps/common/templatetags/markdown_filters.py) converted Markdown and returned it through mark_safe() with no sanitization:

@register.filter
@stringfilter
def render_markdown(value):
    md = markdown.Markdown(extensions=["fenced_code", "codehilite"])
    return mark_safe(md.convert(value))

Any <script>, onerror= handler or javascript: link in the input reached the page as executable code (see Rendering Untrusted Markdown with mark_safe Causes XSS). The realistic target was a Contact message rendered for staff in the CRM, which would let a script read customer PII and tokens with a staff session.

Steps and findings

1. Added nh3

Added nh3 to pyproject.toml (and uv.lock). It wraps the Rust sanitizer ammonia, which parses HTML with html5ever and keeps only allowlisted tags, attributes and URL schemes. bleach was not an option: it has been deprecated since January 2023.

2. Sanitized before mark_safe()

ALLOWED_ATTRIBUTES = deepcopy(nh3.ALLOWED_ATTRIBUTES)
for _tag in ("div", "pre", "code", "span"):
    ALLOWED_ATTRIBUTES.setdefault(_tag, set()).add("class")

# Only keep class names emitted by codehilite/Pygments (e.g. "codehilite", "k", "nf", "s2"),
# so user-supplied raw HTML can't reuse site CSS (e.g. Tailwind) to build overlays.
_ALLOWED_CLASS = re.compile(r"^(codehilite|[a-z]{1,3}\d?)$")


def _attribute_filter(tag, attr, value):
    if attr == "class":
        kept = " ".join(c for c in value.split() if _ALLOWED_CLASS.match(c))
        return kept or None
    return value


@register.filter
@stringfilter
def render_markdown(value):
    md = markdown.Markdown(extensions=["fenced_code", "codehilite"])
    html = md.convert(value)
    sanitized_html = nh3.clean(
        html, attributes=ALLOWED_ATTRIBUTES, attribute_filter=_attribute_filter
    )
    return mark_safe(sanitized_html)
  1. md.convert() produces HTML, including Pygments markup for fenced code.
  2. nh3.clean() keeps safe formatting tags, removes <script>/<style> with their content, drops other unknown tags but keeps their text, removes on* and style attributes, removes href/src attributes with schemes like javascript: or data:, and adds rel="noopener noreferrer" to links. Details: Sanitizing Markdown Output with an HTML Allowlist.
  3. class is allowed on div, pre, code and span for highlighting, but _attribute_filter keeps only names matching codehilite or short Pygments token names, so <div class="fixed inset-0 z-50 bg-white"> loses its classes (see Scriptless UI Redressing via Allowed class Attributes).
  4. Only then is the result passed to mark_safe().

Controls verified

RenderMarkdownFilterTests in apps/common/tests.py:

  1. test_renders_safe_markdown_and_code_blocks: headings, bold, https:// links and a fenced Python block render as a SafeString with codehilite classes.
  2. test_strips_script_tags_and_event_handlers: <script>alert("xss")</script>, <img src="x" onerror="alert(1)"> and [Click me](javascript:alert(1)) lose the script, the onerror attribute and the javascript: href.
  3. test_strips_non_highlighting_classes: <div class="fixed inset-0 z-50 bg-white"> keeps its text but loses every class.
  4. test_keeps_pygments_token_classes: a fenced Python block still carries class="codehilite" and token classes like class="k".

Remaining limitations

  • <img> with any https: source is still allowed, so a message can embed a tracking pixel that reveals when, and from which IP, staff open it.
  • A relative src makes the staff browser send a same-origin GET with its cookies; harmless as long as no endpoint changes state on GET.
  • Without Pygments installed, codehilite emits class="language-…", which the filter strips (no security impact).

Dropping img from the allowed tags, or proxying images, closes the first two.

References