处理嵌入式 SVG 脚本标签中的字符引用

Handling of character references in an embedded SVG's script tags

这是一个 xss 脚本:

<svg><script>&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;</script></svg>

<script> 标签之间的代码将被浏览器翻译成 alert(1) 并执行。

但是如果我不使用 <svg> 标记,代码将不会被翻译成脚本。 谁能告诉我为什么会这样? <svg> 标签如何工作?

根据 HTML 5 规范,HTML 解析器明确禁止在脚本标记中使用 character references

HTML5 有一个 separate script parsing mode 作为许多随上下文变化的标记化模式之一。脚本解析不允许字符引用,其他一些解析模式可以。

SVG 基于 XML,其中规则更简单、更直接。基本上任何地方都允许使用字符引用,因为 aren't different context sensitive parsing modes.

对于 html 中的 SVG,HTML 规范 says

The svg element from the SVG namespace falls into the embedded content, phrasing content, and flow content categories for the purposes of the content models in this specification.

换句话说,将所有SVG文本解析为短语内容。所有 SVG 都是 HTML 5 解析器的单一自定义标记化模式。

由于我对其他答案对这种行为背后原因的引用并不十分满意,因此我将此 'issue' 升级为 WHATWG mailing list, as it does present some possible (albeit small) security loopholes. To quote Ian Hickson (chief editor of the HTML5 standard at W3C) verbatim:

It's not great, but it is intentional. Within <svg> and <math> blocks, we use the "foreign content" parsing mode wherein parsing is much more similar to legacy XML parsing than legacy HTML parsing:

https://html.spec.whatwg.org/#parsing-main-inforeign

Note in particular that the special behaviour for <script> here doesn't include changing the tokeniser mode, like it would in non-foreign content.

因此,虽然罗伯特的回答本质上是关于独立 HTML5 和 SVG 内容的正确引述的集合,但有一个关于 解析 的特定单独部分 'foreign content' 解释这种行为。 Ian 同意这并不是一个真正完美的解决方案,但老实说,我想不出一个同时兼容 "semi-SGML" 和 XML 解析的解决方案。