Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Allow benign DOCTYPE in SVG sanitization https://github.com/siyuan-note/siyuan/issues/18543

Danielf750d62370ec
diff --git a/kernel/util/misc.go b/kernel/util/misc.go
index fc3b479dd6..c83f1d3aa6 100644
--- a/kernel/util/misc.go
+++ b/kernel/util/misc.go
@@ -437,7 +437,10 @@ func SanitizeSVG(svgInput string) (string, error) {
}
}
case xml.Directive:
- return "", fmt.Errorf("svg directives are not allowed")
+ if !isBenignSVGDoctype(string(typed)) {
+ return "", fmt.Errorf("svg directives are not allowed")
+ }
+ // 良性 DOCTYPE 声明不写入输出,与 XML 声明(ProcInst)的处理方式一致,不影响浏览器渲染
case xml.ProcInst:
// XML 声明和处理指令不影响 SVG 图像内容,输出时统一省略。
}
@@ -460,6 +463,23 @@ func preserveXMLName(name xml.Name) xml.Name {
return name
}
+// isBenignSVGDoctype 判断 DOCTYPE 是否仅为 svg 根元素的无内部子集声明。
+// Go 的 xml.Directive 是 <! 与 > 之间的内容;内部子集 [...] 内可声明实体,存在 XXE 风险,一律拒绝。
+func isBenignSVGDoctype(d string) bool {
+ d = strings.TrimSpace(d)
+ if !strings.HasPrefix(strings.ToLower(d), "doctype") {
+ return false
+ }
+ if strings.ContainsAny(d, "[]") {
+ return false
+ }
+ fields := strings.Fields(strings.TrimSpace(d[len("DOCTYPE"):]))
+ if len(fields) == 0 {
+ return false
+ }
+ return strings.EqualFold(fields[0], "svg")
+}
+
func sanitizeSVGAttributes(attrs []xml.Attr) []xml.Attr {
filtered := make([]xml.Attr, 0, len(attrs))
for _, attr := range attrs {
diff --git a/kernel/util/sanitize_svg_test.go b/kernel/util/sanitize_svg_test.go
index 88b435b63a..3721a87b5a 100644
--- a/kernel/util/sanitize_svg_test.go
+++ b/kernel/util/sanitize_svg_test.go
@@ -78,14 +78,40 @@ func TestSanitizeSVGPreservesStaticSVG(t *testing.T) {
}
}
+func TestSanitizeSVGAllowsBenignDoctype(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ }{
+ {"drawio style", `<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">` +
+ `<svg xmlns="http://www.w3.org/2000/svg"></svg>`},
+ {"short", `<!DOCTYPE svg><svg xmlns="http://www.w3.org/2000/svg"></svg>`},
+ {"system id", `<!DOCTYPE svg SYSTEM "svg.dtd"><svg xmlns="http://www.w3.org/2000/svg"></svg>`},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ output, err := SanitizeSVG(test.input)
+ if err != nil {
+ t.Fatalf("sanitize failed: %v", err)
+ }
+ if strings.Contains(strings.ToLower(output), "<!doctype") {
+ t.Fatalf("doctype was not dropped from %q", output)
+ }
+ })
+ }
+}
+
func TestSanitizeSVGRejectsInvalidInput(t *testing.T) {
tests := []string{
`<html></html>`,
`<svg><path></svg>`,
`<svg><script><path></script></path></svg>`,
`<svg></svg><svg></svg>`,
- `<!DOCTYPE svg><svg></svg>`,
`text<svg></svg>`,
+ `<!DOCTYPE svg [ <!ENTITY x "y"> ]><svg></svg>`,
+ `<!ENTITY x "y"><svg></svg>`,
+ `<!DOCTYPE html><svg></svg>`,
}
for _, input := range tests {
if output, err := SanitizeSVG(input); err == nil {