Why Markdown Rendering Must Be Sanitized

Markdown allows embedded HTML, which means "rendering user-submitted Markdown" is essentially the same as "rendering user-submitted HTML."
A Minimal Example
If the following Markdown is converted to HTML as-is and inserted into a page, it will execute a script:
看起来是一条普通评论。
<img src="x" onerror="alert(document.cookie)">
[点我](javascript:alert(1))
Two Layers of Defense
- When converting Markdown to HTML, drop raw HTML so that it never makes it into the output
- After the HTML is generated, sanitize it against an allowlist: keep only known-safe tags and attributes, and allow only protocols such as
http,https, andmailtoin links
The second layer is the safety net: even if someone later changes the configuration of the first layer, dangerous content still can't reach the browser.
Don't use a blocklist. You can never enumerate everything that is dangerous, but you can enumerate everything you need.
Comments