An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Harden SVG sanitization https://github.com/siyuan-note/siyuan/security/advisories/GHSA-99rq-75j6-5j9f
Danielf08dee71ba8e
diff --git a/kernel/api/icon.go b/kernel/api/icon.goindex dcfafeed11..81b825a0c8 100644--- a/kernel/api/icon.go+++ b/kernel/api/icon.go@@ -18,6 +18,7 @@ package apiimport ("fmt"+ "html""math""net/http""regexp"@@ -166,10 +167,17 @@ func getDynamicIcon(c *gin.Context) {}if !model.Conf.Editor.AllowSVGScript {- svg = util.SanitizeSVG(svg)+ var err error+ svg, err = util.SanitizeSVG(svg)+ if err != nil {+ c.Status(http.StatusInternalServerError)+ return+ }}c.Header("Content-Type", "image/svg+xml")+ c.Header("Content-Security-Policy", "script-src 'none'; object-src 'none'; base-uri 'none'")+ c.Header("X-Content-Type-Options", "nosniff")c.Header("Cache-Control", "no-cache")c.Header("Pragma", "no-cache")c.String(http.StatusOK, svg)@@ -577,10 +585,11 @@ func generateTypeEightSVG(color, content, id string) string {}}+ escapedContent := html.EscapeString(content)return fmt.Sprintf(`<svg id="dynamic_icon_type8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M39,0h434c20.97,0,38,17.03,38,38v412c0,33.11-26.89,60-60,60H60c-32.56,0-59-26.44-59-59V38C1,17.03,18.03,0,39,0Z" style="fill: %s;"/><text x="50%%" y="55%%" dy="%s" style="font-size: %.2fpx; fill: #fff; text-anchor: middle; dominant-baseline:middle;font-family: -apple-system, BlinkMacSystemFont, 'Noto Sans', 'Noto Sans CJK SC', 'Microsoft YaHei'; ">%s</text></svg>- `, colorScheme.Primary, dy, fontSize, content)+ `, colorScheme.Primary, dy, fontSize, escapedContent)}diff --git a/kernel/api/icon_test.go b/kernel/api/icon_test.gonew file mode 100644index 0000000000..8e649d6f65--- /dev/null+++ b/kernel/api/icon_test.go@@ -0,0 +1,66 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package api++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestGenerateTypeEightSVGEscapesContent(t *testing.T) {+ content := `</text><desc><style><script>alert(1)</script></style></desc><text>`+ output := generateTypeEightSVG("red", content, "")+ if strings.Contains(output, `<script>`) || strings.Contains(output, `</text><desc>`) {+ t.Fatalf("dynamic icon contains injected SVG markup: %s", output)+ }+ if !strings.Contains(output, `</text>`) {+ t.Fatalf("dynamic icon content was not escaped: %s", output)+ }+}++func TestGenerateTypeEightSVGCalculatesFontSizeBeforeEscaping(t *testing.T) {+ output := generateTypeEightSVG("red", "<", "")+ if !strings.Contains(output, `font-size: 480.00px`) || !strings.Contains(output, `<`) {+ t.Fatalf("escaped content changed the dynamic icon font size: %s", output)+ }+}++func TestGetDynamicIconSetsSecurityHeaders(t *testing.T) {+ oldConf := model.Conf+ model.Conf = model.NewAppConf()+ model.Conf.Editor = conf.NewEditor()+ t.Cleanup(func() {+ model.Conf = oldConf+ })++ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ request := httptest.NewRequest(http.MethodGet, "/api/icon/getDynamicIcon?type=8&content=%3Cscript%3Ealert(1)%3C%2Fscript%3E", nil)+ context.Request = request+ getDynamicIcon(context)++ if recorder.Code != http.StatusOK {+ t.Fatalf("unexpected status code %d", recorder.Code)+ }+ if strings.Contains(recorder.Body.String(), `<script>`) {+ t.Fatalf("dynamic icon response contains injected script: %s", recorder.Body.String())+ }+ if recorder.Header().Get("Content-Security-Policy") != "script-src 'none'; object-src 'none'; base-uri 'none'" {+ t.Fatalf("unexpected CSP header %q", recorder.Header().Get("Content-Security-Policy"))+ }+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {+ t.Fatalf("unexpected X-Content-Type-Options header %q", recorder.Header().Get("X-Content-Type-Options"))+ }+}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 811fed30bf..a719897431 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -790,9 +790,17 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {}if !model.Conf.Editor.AllowSVGScript {- data = []byte(util.SanitizeSVG(string(data)))+ sanitized, sanitizeErr := util.SanitizeSVG(string(data))+ if sanitizeErr != nil {+ logging.LogWarnf("sanitize svg file failed [%s]: %s", assetAbsPath, sanitizeErr)+ context.Status(http.StatusUnprocessableEntity)+ return true+ }+ data = []byte(sanitized)+ context.Header("Content-Security-Policy", "script-src 'none'; object-src 'none'; base-uri 'none'")}+ context.Header("X-Content-Type-Options", "nosniff")setAssetsAttachmentDisposition(context, assetAbsPath)context.Data(200, "image/svg+xml", data)return truediff --git a/kernel/server/serve_svg_test.go b/kernel/server/serve_svg_test.gonew file mode 100644index 0000000000..fb3a77558e--- /dev/null+++ b/kernel/server/serve_svg_test.go@@ -0,0 +1,90 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package server++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestServeSVGSanitizesAndSetsSecurityHeaders(t *testing.T) {+ oldConf := model.Conf+ model.Conf = model.NewAppConf()+ model.Conf.Editor = conf.NewEditor()+ t.Cleanup(func() {+ model.Conf = oldConf+ })++ assetPath := filepath.Join(t.TempDir(), "test.svg")+ input := `<svg xmlns="http://www.w3.org/2000/svg"><desc><style><script>alert(1)</script></style></desc></svg>`+ if err := os.WriteFile(assetPath, []byte(input), 0644); err != nil {+ t.Fatalf("write test SVG failed: %v", err)+ }++ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/test.svg", nil)+ if !serveSVG(context, assetPath) {+ t.Fatal("SVG asset was not handled")+ }++ if recorder.Code != http.StatusOK {+ t.Fatalf("unexpected status code %d", recorder.Code)+ }+ if strings.Contains(recorder.Body.String(), `<script>`) {+ t.Fatalf("SVG response contains injected script: %s", recorder.Body.String())+ }+ if recorder.Header().Get("Content-Security-Policy") != "script-src 'none'; object-src 'none'; base-uri 'none'" {+ t.Fatalf("unexpected CSP header %q", recorder.Header().Get("Content-Security-Policy"))+ }+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {+ t.Fatalf("unexpected X-Content-Type-Options header %q", recorder.Header().Get("X-Content-Type-Options"))+ }+}++func TestServeSVGPreservesAllowSVGScriptBehavior(t *testing.T) {+ oldConf := model.Conf+ model.Conf = model.NewAppConf()+ model.Conf.Editor = conf.NewEditor()+ model.Conf.Editor.AllowSVGScript = true+ t.Cleanup(func() {+ model.Conf = oldConf+ })++ assetPath := filepath.Join(t.TempDir(), "test.svg")+ input := `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`+ if err := os.WriteFile(assetPath, []byte(input), 0644); err != nil {+ t.Fatalf("write test SVG failed: %v", err)+ }++ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.Request = httptest.NewRequest(http.MethodGet, "/assets/test.svg", nil)+ if !serveSVG(context, assetPath) {+ t.Fatal("SVG asset was not handled")+ }++ if !strings.Contains(recorder.Body.String(), `<script>`) {+ t.Fatalf("enabled SVG script was unexpectedly removed: %s", recorder.Body.String())+ }+ if recorder.Header().Get("Content-Security-Policy") != "" {+ t.Fatalf("enabled SVG script received an unexpected CSP header %q", recorder.Header().Get("Content-Security-Policy"))+ }+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {+ t.Fatalf("unexpected X-Content-Type-Options header %q", recorder.Header().Get("X-Content-Type-Options"))+ }+}diff --git a/kernel/util/misc.go b/kernel/util/misc.goindex 9eac389490..fc3b479dd6 100644--- a/kernel/util/misc.go+++ b/kernel/util/misc.go@@ -19,7 +19,9 @@ package utilimport ("bytes""encoding/json"+ "encoding/xml""fmt"+ "io""math/rand""reflect""regexp"@@ -29,7 +31,6 @@ import ("github.com/88250/lute/html""github.com/microcosm-cc/bluemonday"- "github.com/siyuan-note/logging")// Optional is a generic type that represents an optional value, which can be in one of three states:@@ -316,121 +317,189 @@ func SanitizeHTML(h string) string {return p.Sanitize(h)}-func SanitizeSVG(svgInput string) string {- // 1. 将字符串解析为节点树- doc, err := html.Parse(strings.NewReader(svgInput))- if err != nil {- logging.LogWarnf("parse svg failed: %v", err)- return svgInput- }+const (+ maxSVGDepth = 256+ maxSVGTokens = 1_000_000+)- // 2. 定义递归移除逻辑- var walk func(*html.Node)- walk = func(n *html.Node) {- // 倒序遍历子节点,确保删除操作不影响后续迭代- for c := n.FirstChild; c != nil; {- next := c.NextSibling- if c.Type == html.ElementNode {- tag := strings.ToLower(c.Data)- if i := strings.LastIndex(tag, ":"); i >= 0 {- tag = tag[i+1:]- }- if tag == "script" || tag == "iframe" || tag == "object" || tag == "embed" || tag == "foreignobject" || "animate" == tag ||- "animatetransform" == tag || "animatecolor" == tag || "animatemotion" == tag || "set" == tag {- n.RemoveChild(c)- c = next- continue- }+var unsafeSVGElements = map[string]struct{}{+ "script": {},+ "iframe": {},+ "object": {},+ "embed": {},+ "foreignobject": {},+ "animate": {},+ "animatetransform": {},+ "animatecolor": {},+ "animatemotion": {},+ "set": {},+}++// SanitizeSVG 使用 XML 语义过滤 SVG,避免 HTML 与 XML 解析规则差异导致活动内容绕过过滤。+func SanitizeSVG(svgInput string) (string, error) {+ decoder := xml.NewDecoder(strings.NewReader(svgInput))+ decoder.Strict = true- // 清理不安全属性- if len(c.Attr) > 0 {- // 过滤属性:删除以 on 开头的属性(事件处理),href/xlink:href 指向 javascript: 或不安全 data:,以及危险的 style 表达式- filtered := c.Attr[:0]- for _, a := range c.Attr {- key := strings.ToLower(a.Key)- val := strings.TrimSpace(strings.ToLower(a.Val))- val = strings.Map(func(r rune) rune {- if r == '\t' || r == '\n' || r == '\r' {- return -1 // Remove character- }- return r- }, val)-- // 删除事件处理器属性(onload, onerror 等)- if strings.HasPrefix(key, "on") {- continue- }-- if key == "values" || key == "from" || key == "to" {- // 删除 animate* 元素的 values、from、to 属性以防止恶意动画- if strings.Contains(val, "javascript:") {- continue- }- }-- // 删除 href 或 xlink:href 指向 javascript: 或某些不安全的 data: URI- if key == "href" || key == "xlink:href" || key == "xlinkhref" {- if strings.HasPrefix(val, "javascript:") {- continue- }- // 对 data: 做保守处理,只允许常见安全的图片格式(png/jpeg/gif/webp)- if strings.HasPrefix(val, "data:") {- safe := strings.HasPrefix(val, "data:image/png") ||- strings.HasPrefix(val, "data:image/jpeg") ||- strings.HasPrefix(val, "data:image/gif") ||- strings.HasPrefix(val, "data:image/webp")- if !safe {- continue- }- }- }-- // 清理 style 中的危险表达式,如 expression() 或 url(javascript:...)- if key == "style" {- low := val- if strings.Contains(low, "expression(") || strings.Contains(low, "url(javascript:") || strings.Contains(low, "javascript:") {- // 丢弃整个 style 属性以保证安全- continue- }- }-- // 其它属性保留- filtered = append(filtered, a)- }- c.Attr = filtered+ var buf bytes.Buffer+ encoder := xml.NewEncoder(&buf)+ rootSeen := false+ rootClosed := false+ depth := 0+ skipDepth := 0+ tokenCount := 0+ var elementStack []xml.Name++ for {+ token, err := decoder.RawToken()+ if err == io.EOF {+ break+ }+ if err != nil {+ return "", fmt.Errorf("parse svg failed: %w", err)+ }+ tokenCount+++ if tokenCount > maxSVGTokens {+ return "", fmt.Errorf("svg contains too many tokens")+ }++ switch typed := token.(type) {+ case xml.StartElement:+ elementStack = append(elementStack, typed.Name)+ depth+++ if depth > maxSVGDepth {+ return "", fmt.Errorf("svg nesting depth exceeds %d", maxSVGDepth)+ }+ if rootClosed {+ return "", fmt.Errorf("svg contains multiple root elements")+ }+ if !rootSeen {+ if !strings.EqualFold(typed.Name.Local, "svg") {+ return "", fmt.Errorf("root element is not svg")}+ rootSeen = true}- // 递归处理子节点(如果节点尚未被删除)- if c.Parent != nil {- walk(c)+ if skipDepth > 0 {+ skipDepth+++ continue+ }+ if _, unsafe := unsafeSVGElements[strings.ToLower(typed.Name.Local)]; unsafe {+ skipDepth = 1+ continue}- c = next+ typed.Name = preserveXMLName(typed.Name)+ typed.Attr = sanitizeSVGAttributes(typed.Attr)+ if err = encoder.EncodeToken(typed); err != nil {+ return "", fmt.Errorf("render svg failed: %w", err)+ }+ case xml.EndElement:+ if depth <= 0 || len(elementStack) == 0 {+ return "", fmt.Errorf("svg contains an unexpected closing element")+ }+ startName := elementStack[len(elementStack)-1]+ if startName != typed.Name {+ return "", fmt.Errorf("svg closing element %q does not match %q", typed.Name.Local, startName.Local)+ }+ elementStack = elementStack[:len(elementStack)-1]+ if skipDepth > 0 {+ skipDepth--+ depth--+ if depth == 0 {+ rootClosed = true+ }+ continue+ }+ typed.Name = preserveXMLName(typed.Name)+ if err = encoder.EncodeToken(typed); err != nil {+ return "", fmt.Errorf("render svg failed: %w", err)+ }+ depth--+ if depth == 0 {+ rootClosed = true+ }+ case xml.CharData:+ if skipDepth > 0 {+ continue+ }+ if (!rootSeen || rootClosed) && strings.TrimSpace(string(typed)) != "" {+ return "", fmt.Errorf("svg contains text outside the root element")+ }+ if rootSeen && !rootClosed {+ if err = encoder.EncodeToken(typed); err != nil {+ return "", fmt.Errorf("render svg failed: %w", err)+ }+ }+ case xml.Comment:+ if skipDepth == 0 && rootSeen && !rootClosed {+ if err = encoder.EncodeToken(typed); err != nil {+ return "", fmt.Errorf("render svg failed: %w", err)+ }+ }+ case xml.Directive:+ return "", fmt.Errorf("svg directives are not allowed")+ case xml.ProcInst:+ // XML 声明和处理指令不影响 SVG 图像内容,输出时统一省略。}}- // 3. 执行移除- walk(doc)-- // 4. 将处理后的树重新渲染回字符串- var buf bytes.Buffer- if err = html.Render(&buf, doc); err != nil {- logging.LogWarnf("render svg failed: %v", err)- return svgInput+ if !rootSeen || !rootClosed || depth != 0 || skipDepth != 0 || len(elementStack) != 0 {+ return "", fmt.Errorf("svg root element is incomplete")+ }+ if err := encoder.Close(); err != nil {+ return "", fmt.Errorf("render svg failed: %w", err)}+ return buf.String(), nil+}- // 5. 提取 SVG 部分 (html.Render 会自动加上 <html><body> 标签)- return extractSVG(buf.String())+func preserveXMLName(name xml.Name) xml.Name {+ if name.Space != "" {+ name.Local = name.Space + ":" + name.Local+ name.Space = ""+ }+ return name}-func extractSVG(fullHTML string) string {- start := strings.Index(fullHTML, "<svg")- end := strings.LastIndex(fullHTML, "</svg>")- if start == -1 || end == -1 {- return fullHTML+func sanitizeSVGAttributes(attrs []xml.Attr) []xml.Attr {+ filtered := make([]xml.Attr, 0, len(attrs))+ for _, attr := range attrs {+ key := strings.ToLower(attr.Name.Local)+ value := normalizeSVGAttributeValue(attr.Value)+ if strings.HasPrefix(key, "on") {+ continue+ }+ if key == "href" {+ if strings.HasPrefix(value, "javascript:") || strings.HasPrefix(value, "vbscript:") {+ continue+ }+ if strings.HasPrefix(value, "data:") && !isSafeSVGDataImage(value) {+ continue+ }+ }+ if key == "style" && (strings.Contains(value, "expression(") || strings.Contains(value, "javascript:") ||+ strings.Contains(value, "vbscript:")) {+ continue+ }+ attr.Name = preserveXMLName(attr.Name)+ filtered = append(filtered, attr)}- return fullHTML[start : end+6]+ return filtered+}++func normalizeSVGAttributeValue(value string) string {+ return strings.ToLower(strings.Map(func(r rune) rune {+ if unicode.IsSpace(r) || unicode.IsControl(r) {+ return -1+ }+ return r+ }, strings.TrimSpace(value)))+}++func isSafeSVGDataImage(value string) bool {+ return strings.HasPrefix(value, "data:image/png") ||+ strings.HasPrefix(value, "data:image/jpeg") ||+ strings.HasPrefix(value, "data:image/gif") ||+ strings.HasPrefix(value, "data:image/webp")}var nonAlphanumericRegexp = regexp.MustCompile(`[^0-9a-zA-Z]`)diff --git a/kernel/util/sanitize_svg_test.go b/kernel/util/sanitize_svg_test.gonew file mode 100644index 0000000000..88b435b63a--- /dev/null+++ b/kernel/util/sanitize_svg_test.go@@ -0,0 +1,95 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package util++import (+ "strings"+ "testing"+)++func TestSanitizeSVGRemovesActiveContent(t *testing.T) {+ tests := []struct {+ name string+ input string+ }{+ {"script", `<svg><script>alert(1)</script></svg>`},+ {"style parser difference", `<svg><desc><style><script>alert(1)</script></style></desc></svg>`},+ {"xmp parser difference", `<svg><title><xmp><script>alert(1)</script></xmp></title></svg>`},+ {"noscript parser difference", `<svg><desc><noscript><script>alert(1)</script></noscript></desc></svg>`},+ {"prefixed script", `<svg xmlns:s="urn:test"><s:script>alert(1)</s:script></svg>`},+ {"foreign object", `<svg><foreignObject><div><script>alert(1)</script></div></foreignObject></svg>`},+ {"animation", `<svg><animate attributeName="href" values="javascript:alert(1)"></animate></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)+ }+ lower := strings.ToLower(output)+ for _, unsafe := range []string{"<script", ":script", "<foreignobject", "<animate", "javascript:"} {+ if strings.Contains(lower, unsafe) {+ t.Fatalf("unsafe content %q remains in %q", unsafe, output)+ }+ }+ })+ }+}++func TestSanitizeSVGFiltersUnsafeAttributes(t *testing.T) {+ input := `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="alert(1)">` ++ `<a href="java
script:alert(1)" xlink:href="vbscript:alert(1)" style="background:url(javascript:alert(1))">` ++ `<image href="data:image/png;base64,AA=="></image></a></svg>`+ output, err := SanitizeSVG(input)+ if err != nil {+ t.Fatalf("sanitize failed: %v", err)+ }+ lower := strings.ToLower(output)+ for _, unsafe := range []string{"onload=", "javascript:", "vbscript:"} {+ if strings.Contains(lower, unsafe) {+ t.Fatalf("unsafe attribute %q remains in %q", unsafe, output)+ }+ }+ if !strings.Contains(output, `href="data:image/png;base64,AA=="`) {+ t.Fatalf("safe bitmap data URL was removed from %q", output)+ }+}++func TestSanitizeSVGPreservesStaticSVG(t *testing.T) {+ input := `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10">` ++ `<defs><linearGradient id="g"><stop offset="0%" stop-color="#fff"></stop></linearGradient></defs>` ++ `<path d="M0 0h10v10z" fill="url(#g)"></path><use xlink:href="#shape"></use></svg>`+ output, err := SanitizeSVG(input)+ if err != nil {+ t.Fatalf("sanitize failed: %v", err)+ }+ for _, expected := range []string{`xmlns="http://www.w3.org/2000/svg"`, `xmlns:xlink="http://www.w3.org/1999/xlink"`,+ `<linearGradient`, `<path`, `xlink:href="#shape"`} {+ if !strings.Contains(output, expected) {+ t.Fatalf("static SVG content %q is missing from %q", expected, 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>`,+ }+ for _, input := range tests {+ if output, err := SanitizeSVG(input); err == nil {+ t.Fatalf("invalid input %q produced %q", input, output)+ }+ }+}