mikexxz
All posts

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

  1. When converting Markdown to HTML, drop raw HTML so that it never makes it into the output
  2. 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, and mailto in 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

Delete this comment?

Its content will be removed. This can’t be undone.