Skip to content

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

:lock: Restrict dynamic icon template functions and source https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52

Daniel5ef7c5d06264
diff --git a/kernel/api/icon.go b/kernel/api/icon.go
index b402e7cfdf..a6dd1dc6a8 100644
--- a/kernel/api/icon.go
+++ b/kernel/api/icon.go
@@ -162,7 +162,10 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Con
content := c.Query("content")
id := c.Query("id")
if strings.Contains(content, ".action{") {
- // 模板内容会按 id 读取工作区数据,只读角色必须通过发布访问控制后才能执行 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838
+ // 模板内容会按 id 读取工作区数据,只读角色必须通过发布访问控制后才能执行
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838
+ // 只读角色的模板源码由内核从块已保存的图标属性中取得,不使用请求中的 content
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
if !dynamicIconContentAccessable(c, id) {
// 空内容保持与 id 不存在时一致的响应结构,避免泄露文档的可访问状态
svg = generateTypeEightSVG(color, "")
diff --git a/kernel/api/icon_publish_access_test.go b/kernel/api/icon_publish_access_test.go
index 3a9de0414c..fce23c0e3e 100644
--- a/kernel/api/icon_publish_access_test.go
+++ b/kernel/api/icon_publish_access_test.go
@@ -91,9 +91,12 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
treenode.InitBlockTree(true)
- addDoc := func(id, title string) {
+ addDoc := func(id, title, icon string) {
tree := treenode.NewTree(boxID, "/"+id+".sy", "/"+title, title)
tree.Root.FirstChild.Unlink()
+ if "" != icon {
+ tree.Root.SetIALAttr("icon", icon)
+ }
node := &ast.Node{Type: ast.NodeParagraph, ID: id[:21] + "c"}
node.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("body")})
tree.Root.AppendChild(node)
@@ -102,10 +105,14 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
t.Fatal(err)
}
}
- addDoc(publicID, "Public Doc")
- addDoc(hiddenID, "Hidden Doc")
- addDoc(disabledID, "Disabled Doc")
- addDoc(passwordID, "Password Doc")
+ // 文档图标保存为动态图标模板,只读角色渲染时必须使用这份已保存的源码
+ storedIcon := func(id string) string {
+ return "api/icon/getDynamicIcon?type=8&color=%23d23f31&content=.action%7B.title%7D&id=" + id
+ }
+ addDoc(publicID, "Public Doc", storedIcon(publicID))
+ addDoc(hiddenID, "Hidden Doc", "")
+ addDoc(disabledID, "Disabled Doc", "")
+ addDoc(passwordID, "Password Doc", storedIcon(passwordID))
if err := model.SetPublishAccess(model.PublishAccess{
{ID: hiddenID, Visible: false},
@@ -147,6 +154,17 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
t.Fatalf("administrator cannot render a template icon: %s", svg)
}
+ // 只读角色不能自带模板源码:请求中的 content 被忽略,渲染的是文档已保存的图标模板
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
+ submittedContent := ".action%7BgetHPathByID%20%22" + disabledID + "%22%7D"
+ if svg := requestIcon(model.RoleReader, publicID, submittedContent); !strings.Contains(svg, "Public Doc") || strings.Contains(svg, "Disabled Doc") {
+ t.Fatalf("publish reader replaced the saved template icon: %s", svg)
+ }
+ // 文档没有已保存的动态图标模板时,请求中的模板不参与渲染
+ if svg := requestIcon(model.RoleReader, hiddenID, titleContent); strings.Contains(svg, "Hidden Doc") {
+ t.Fatalf("publish reader rendered an unsaved template: %s", svg)
+ }
+
// 隐藏(不列出)与禁止发布、密码保护不同:发布访问控制按设计仍允许按 ID 读取隐藏文档,
// 仅禁止其被枚举,因此这里只断言禁止与密码保护两类
for _, id := range []string{disabledID, passwordID} {
@@ -164,11 +182,10 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
t.Fatalf("authenticated publish reader cannot render the template icon: %s", svg)
}
- hPathContent := ".action%7BgetHPathByID%20%22" + disabledID + "%22%7D"
statContent := ".action%7BstatBlock%20%22" + disabledID + "%22%7D"
// 通用模板函数不得成为绕过发布访问控制的第二条通路
- if svg := requestIcon(model.RoleReader, publicID, hPathContent); strings.Contains(svg, "Disabled Doc") {
+ if svg := requestIcon(model.RoleReader, publicID, submittedContent); strings.Contains(svg, "Disabled Doc") {
t.Fatalf("publish reader read a protected doc path through getHPathByID: %s", svg)
}
// statBlock 返回结构体,模板渲染为 {runeCount wordCount linkCount imageCount refCount blockCount}
@@ -177,7 +194,7 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
}
// 可写角色不受影响
- if svg := requestIcon(model.RoleAdministrator, publicID, hPathContent); !strings.Contains(svg, "Disabled Doc") {
+ if svg := requestIcon(model.RoleAdministrator, publicID, submittedContent); !strings.Contains(svg, "Disabled Doc") {
t.Fatalf("administrator cannot use getHPathByID in a template icon: %s", svg)
}
if svg := requestIcon(model.RoleAdministrator, publicID, statContent); !strings.Contains(svg, "{4 1 0 0 0 1}") {
@@ -185,7 +202,7 @@ func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {
}
// 模板解析失败时不应回显模板原文
- if svg := requestIcon(model.RoleReader, publicID, ".action%7B%7B.title%7D%7D"); strings.Contains(svg, ".title") {
+ if svg := requestIcon(model.RoleAdministrator, publicID, ".action%7B%7B.title%7D%7D"); strings.Contains(svg, ".title") {
t.Fatalf("dynamic icon echoed the raw template content: %s", svg)
}
}
diff --git a/kernel/model/template.go b/kernel/model/template.go
index ebaf361a65..19c774d9c3 100644
--- a/kernel/model/template.go
+++ b/kernel/model/template.go
@@ -21,6 +21,7 @@ import (
"errors"
"fmt"
"io/fs"
+ "net/url"
"os"
"path"
"path/filepath"
@@ -483,8 +484,16 @@ func markTemplateAttributeViewModes(root *ast.Node, databaseMode TemplateDatabas
})
}
+// 动态图标模板的源码与渲染输出上限。图标文本的实际需要远小于这两个值,
+// 上限用于阻断调用方用少量输入换取大量分配的模板写法。
+const (
+ maxDynamicIconTemplateSourceSize = 8 * 1024
+ maxDynamicIconTemplateOutputSize = 8 * 1024
+)
+
// RenderDynamicIconContentTemplate 渲染动态图标中的模板内容。
-// 调用方必须自行完成授权:只读角色会失去按块 ID 读取工作区数据的模板函数,避免绕过发布访问控制。
+// 调用方必须自行完成授权:只读角色会失去按块 ID 读取工作区数据的模板函数,
+// 并且模板源码只能取自工作区中已保存的图标属性,避免绕过发布访问控制。
func RenderDynamicIconContentTemplate(c *gin.Context, content, id string) (ret string) {
tree, err := LoadTreeByBlockID(id)
if err != nil {
@@ -495,6 +504,20 @@ func RenderDynamicIconContentTemplate(c *gin.Context, content, id string) (ret s
if nil == node {
return
}
+
+ if IsReadOnlyRoleContext(c) {
+ // 只读调用方不能自带模板源码,源码只能来自工作区中已保存的图标属性,
+ // 否则任意发布读者都能提交自选模板,借模板函数把少量请求放大成大量分配
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
+ if content = savedDynamicIconContent(node); "" == content {
+ return
+ }
+ }
+ if maxDynamicIconTemplateSourceSize < len(content) {
+ logging.LogWarnf("dynamic icon template source exceeds %d bytes, id [%s]", maxDynamicIconTemplateSourceSize, id)
+ return
+ }
+
block := sql.BuildBlockFromNode(node, tree)
if nil == block {
return
@@ -513,28 +536,107 @@ func RenderDynamicIconContentTemplate(c *gin.Context, content, id string) (ret s
goTpl := template.New("").Delims(".action{", "}")
tplFuncMap := dynamicIconTemplateFuncs(c)
goTpl = goTpl.Funcs(tplFuncMap)
- tpl, err := goTpl.Funcs(tplFuncMap).Parse(content)
+ tpl, err := goTpl.Parse(content)
if err != nil {
err = fmt.Errorf(Conf.Language(44), err.Error())
return
}
- buf := &bytes.Buffer{}
- buf.Grow(4096)
+ buf := newLimitedBuffer(maxDynamicIconTemplateOutputSize)
if err = tpl.Execute(buf, dataModel); err != nil {
err = fmt.Errorf(Conf.Language(44), err.Error())
return
}
+ if buf.Truncated() {
+ // 输出超过上限说明模板把输入放大成了不合理的文本,按不可渲染处理
+ logging.LogWarnf("dynamic icon template output exceeds %d bytes, id [%s]", maxDynamicIconTemplateOutputSize, id)
+ return
+ }
ret = buf.String()
return
}
+// savedDynamicIconContent 从块已保存的图标属性中取出动态图标的 content 参数。
+// 只读调用方的模板源码只能来自这里,请求中的 content 不参与模板渲染。
+func savedDynamicIconContent(node *ast.Node) (ret string) {
+ icon := strings.TrimSpace(util.UnescapeHTML(node.IALAttr("icon")))
+ if !strings.HasPrefix(icon, "api/icon/getDynamicIcon") {
+ return
+ }
+ u, err := url.Parse(icon)
+ if nil != err {
+ return
+ }
+ return u.Query().Get("content")
+}
+
+// limitedBuffer 在累计写入超过 limit 后丢弃后续内容并标记截断,避免模板输出无上限增长。
+// Write 对超出部分返回成功,使模板继续渲染而不是报错,由调用方按截断处理。
+type limitedBuffer struct {
+ buf bytes.Buffer
+ limit int
+ truncated bool
+}
+
+func newLimitedBuffer(limit int) (ret *limitedBuffer) {
+ ret = &limitedBuffer{limit: limit}
+ ret.buf.Grow(4096)
+ return
+}
+
+func (b *limitedBuffer) Write(p []byte) (n int, err error) {
+ if remaining := b.limit - b.buf.Len(); len(p) > remaining {
+ if 0 < remaining {
+ b.buf.Write(p[:remaining])
+ }
+ b.truncated = true
+ return len(p), nil
+ }
+ return b.buf.Write(p)
+}
+
+func (b *limitedBuffer) Truncated() bool { return b.truncated }
+
+func (b *limitedBuffer) String() string { return b.buf.String() }
+
+// dynamicIconTemplateFuncNames 是动态图标模板允许使用的函数白名单。
+// 这里用白名单而不是从通用模板函数中逐个删除:图标模板只需要字符串、日期与数值格式化,
+// 不需要 until、repeat、randBytes 等能把少量输入放大成大量分配的函数,
+// 也不需要 bcrypt、htpasswd、derivePassword 等慢速 KDF;
+// 删除清单无法覆盖 sprig 后续版本新增的函数,白名单对新增函数默认拒绝。
+// 白名单内不放任何构造列表的函数(list、tuple、splitList 等),
+// 这样模板里的 range 只能遍历 4 项数据模型,无法把 printf 这类内建函数放大成循环。
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
+var dynamicIconTemplateFuncNames = []string{
+ // 字符串处理
+ "trim", "trimAll", "trimSuffix", "trimPrefix", "upper", "lower", "title", "untitle",
+ "substr", "trunc", "abbrev", "abbrevboth", "initials", "nospace", "swapcase", "snakecase",
+ "camelcase", "kebabcase", "contains", "hasPrefix", "hasSuffix", "quote", "squote", "cat",
+ "replace", "plural", "toString",
+ // 日期时间
+ "now", "date", "dateInZone", "dateModify", "duration", "durationRound", "unixEpoch", "toDate",
+ "Weekday", "WeekdayCN", "WeekdayCN2", "ISOWeek", "ISOYear", "ISOMonth", "ISOWeekDate", "parseTime",
+ // 数值
+ "add", "add1", "sub", "mul", "div", "mod", "max", "min", "floor", "ceil", "round",
+ "addf", "subf", "mulf", "divf", "maxf", "minf", "FormatFloat", "pow", "powf", "log", "logf",
+ // 取值与转换
+ "default", "empty", "coalesce", "ternary", "atoi", "int", "int64", "float64",
+ // 工作区数据,按角色另行放行
+ "getHPathByID", "statBlock", "runeCount", "wordCount", "countif", "markdown2text", "markdown2content",
+}
+
// dynamicIconTemplateFuncs 返回动态图标模板可用的函数表。
-// 通用模板函数会按块 ID 直接读取工作区数据,与动态图标模板自身的授权无关,
+// 模板按块 ID 直接读取工作区数据,与动态图标模板自身的授权无关,
// 因此只读角色(发布读者与匿名访问者)必须剔除这些函数,防止其绕过发布访问控制读取被禁用、
// 受密码保护或加密笔记本中的文档元数据与块统计。
func dynamicIconTemplateFuncs(c *gin.Context) (ret template.FuncMap) {
- ret = filesys.BuiltInTemplateFuncs()
+ all := filesys.BuiltInTemplateFuncs()
+ ret = make(template.FuncMap, len(dynamicIconTemplateFuncNames))
+ for _, name := range dynamicIconTemplateFuncNames {
+ if fn, ok := all[name]; ok {
+ ret[name] = fn
+ }
+ }
if IsReadOnlyRoleContext(c) {
delete(ret, "getHPathByID")
delete(ret, "statBlock")
diff --git a/kernel/model/template_security_test.go b/kernel/model/template_security_test.go
index 3af310a18e..78a8a8a65d 100644
--- a/kernel/model/template_security_test.go
+++ b/kernel/model/template_security_test.go
@@ -17,9 +17,12 @@
package model
import (
+ "bytes"
"net/http/httptest"
"testing"
+ "text/template"
+ "github.com/88250/lute/ast"
"github.com/gin-gonic/gin"
)
@@ -29,42 +32,167 @@ func testRoleContext(role Role) *gin.Context {
return context
}
-func TestDynamicIconTemplateFuncsExcludeSQL(t *testing.T) {
- funcs := dynamicIconTemplateFuncs(nil)
- for _, name := range []string{"queryBlocks", "querySpans", "querySQL", "getBlock"} {
- if _, ok := funcs[name]; ok {
- t.Fatalf("动态图标模板不应包含 SQL 函数 [%s]", name)
+// TestDynamicIconTemplateFuncsAllowList 校验动态图标模板函数表等于白名单,只读角色只失去按块 ID 读取数据的函数。
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
+func TestDynamicIconTemplateFuncsAllowList(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ writable := dynamicIconTemplateFuncs(testRoleContext(RoleAdministrator))
+ if len(dynamicIconTemplateFuncNames) != len(writable) {
+ var missing []string
+ for _, name := range dynamicIconTemplateFuncNames {
+ if _, ok := writable[name]; !ok {
+ missing = append(missing, name)
+ }
}
+ t.Fatalf("动态图标模板函数表与白名单不一致,白名单 %d 项、函数表 %d 项,缺失 %v",
+ len(dynamicIconTemplateFuncNames), len(writable), missing)
}
- if _, ok := funcs["date"]; !ok {
- t.Fatal("动态图标模板应保留内置模板函数")
- }
-}
-// TestDynamicIconTemplateFuncsDenyWorkspaceReadsForReadOnlyRole 防止只读角色通过模板函数绕过发布访问控制。
-// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838
-func TestDynamicIconTemplateFuncsDenyWorkspaceReadsForReadOnlyRole(t *testing.T) {
- gin.SetMode(gin.TestMode)
+ // 只读角色只失去按块 ID 读取工作区数据的函数 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838
for _, role := range []Role{RoleReader, RoleVisitor} {
funcs := dynamicIconTemplateFuncs(testRoleContext(role))
- for _, name := range []string{"getHPathByID", "statBlock"} {
+ if len(writable)-2 != len(funcs) {
+ t.Fatalf("只读角色 [%d] 的函数表应为 %d 项,实际 %d 项", role, len(writable)-2, len(funcs))
+ }
+ for name := range writable {
if _, ok := funcs[name]; ok {
- t.Fatalf("只读角色 [%d] 的动态图标模板不应包含按块 ID 读取数据的函数 [%s]", role, name)
+ continue
+ }
+ if "getHPathByID" != name && "statBlock" != name {
+ t.Fatalf("只读角色 [%d] 不应失去函数 [%s]", role, name)
}
}
- for _, name := range []string{"date", "now"} {
- if _, ok := funcs[name]; !ok {
- t.Fatalf("只读角色 [%d] 的动态图标模板应保留 [%s]", role, name)
+ for _, name := range []string{"getHPathByID", "statBlock"} {
+ if _, ok := funcs[name]; ok {
+ t.Fatalf("只读角色 [%d] 不应包含按块 ID 读取数据的函数 [%s]", role, name)
}
}
}
- for _, role := range []Role{RoleAdministrator, RoleEditor} {
+ // 图标模板只需要字符串、日期与数值格式化,放大分配、慢速 KDF、环境网络与工作区读写函数必须缺席
+ for _, name := range []string{
+ "until", "untilStep", "repeat",
+ "randBytes", "randAlphaNum", "randAlpha", "randAscii", "randNumeric",
+ "bcrypt", "htpasswd", "derivePassword", "genPrivateKey",
+ "env", "expandenv", "getHostByName",
+ "indent", "nindent", "wrap", "wrapWith",
+ "toJson", "toPrettyJson", "mustToJson", "fromJson", "fail",
+ "querySQL", "queryBlocks", "querySpans", "getBlock", "readFile", "tpl",
+ } {
+ if _, ok := writable[name]; ok {
+ t.Fatalf("动态图标模板不应包含函数 [%s]", name)
+ }
+ }
+
+ for _, role := range []Role{RoleAdministrator, RoleReader, RoleVisitor} {
funcs := dynamicIconTemplateFuncs(testRoleContext(role))
- for _, name := range []string{"getHPathByID", "statBlock"} {
+ for _, name := range []string{"now", "date", "upper", "add", "default"} {
if _, ok := funcs[name]; !ok {
- t.Fatalf("可写角色 [%d] 的动态图标模板应保留 [%s]", role, name)
+ t.Fatalf("角色 [%d] 的动态图标模板应保留函数 [%s]", role, name)
}
}
}
}
+
+// TestDynamicIconTemplateFuncsRejectAmplification 校验白名单外的放大写法无法解析。
+func TestDynamicIconTemplateFuncsRejectAmplification(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ funcs := dynamicIconTemplateFuncs(testRoleContext(RoleAdministrator))
+
+ for _, source := range []string{
+ `.action{len (until 400000000)}`,
+ `.action{untilStep 0 400000000 1}`,
+ `.action{repeat 400000000 "A"}`,
+ `.action{randBytes 400000000}`,
+ `.action{randAlphaNum 400000000}`,
+ `.action{bcrypt "x"}`,
+ `.action{htpasswd "u" "p"}`,
+ `.action{derivePassword 1 "long" "p" "u" "s"}`,
+ `.action{querySQL "select 1"}`,
+ } {
+ if _, err := template.New("").Delims(".action{", "}").Funcs(funcs).Parse(source); nil == err {
+ t.Fatalf("动态图标模板不应能解析 [%s]", source)
+ }
+ }
+
+ // 白名单不放任何构造列表的函数,模板里的 range 只能遍历 4 项数据模型,
+ // 无法把 printf 这类无法移除的内建函数放大成循环
+ for _, name := range []string{"list", "tuple", "dict", "splitList", "seq", "until"} {
+ if _, ok := funcs[name]; ok {
+ t.Fatalf("动态图标模板不应包含构造列表的函数 [%s]", name)
+ }
+ }
+
+ // printf 是 text/template 内建函数,无法通过函数表移除。fmt 自身的宽度解析上限为 1e7,
+ // 超过上限时退化成很短的错误标记而不是按调用方给的宽度分配
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-cxwr-r7cq-xw52
+ tpl, err := template.New("").Delims(".action{", "}").Funcs(funcs).Parse(`.action{printf "%40000000d" 1}`)
+ if nil != err {
+ t.Fatalf("parse failed: %s", err)
+ }
+ buf := &bytes.Buffer{}
+ if err = tpl.Execute(buf, map[string]string{}); nil != err {
+ t.Fatalf("render failed: %s", err)
+ }
+ if 64 < buf.Len() {
+ t.Fatalf("超限的 printf 宽度未被 fmt 拒绝,输出 %d 字节", buf.Len())
+ }
+}
+
+// TestSavedDynamicIconContent 校验只读角色的模板源码取自块已保存的图标属性。
+func TestSavedDynamicIconContent(t *testing.T) {
+ node := &ast.Node{Type: ast.NodeDocument}
+
+ node.SetIALAttr("icon", "api/icon/getDynamicIcon?type=8&color=%23d23f31&content=.action%7B.title%7D&id=20260101000000-abcdefg")
+ if content := savedDynamicIconContent(node); ".action{.title}" != content {
+ t.Fatalf("unexpected content [%s]", content)
+ }
+
+ // 图标属性可能以 HTML 转义形式保存
+ node.SetIALAttr("icon", "api/icon/getDynamicIcon?type=8&amp;content=SiYuan")
+ if content := savedDynamicIconContent(node); "SiYuan" != content {
+ t.Fatalf("unexpected escaped content [%s]", content)
+ }
+
+ node.SetIALAttr("icon", "api/icon/getDynamicIcon?type=1")
+ if content := savedDynamicIconContent(node); "" != content {
+ t.Fatalf("unexpected content without template [%s]", content)
+ }
+
+ node.SetIALAttr("icon", "1f4ca")
+ if content := savedDynamicIconContent(node); "" != content {
+ t.Fatalf("unexpected content for non dynamic icon [%s]", content)
+ }
+
+ node.RemoveIALAttr("icon")
+ if content := savedDynamicIconContent(node); "" != content {
+ t.Fatalf("unexpected content for missing icon [%s]", content)
+ }
+}
+
+// TestLimitedBufferTruncates 校验渲染缓冲在超过上限后标记截断且不再增长。
+func TestLimitedBufferTruncates(t *testing.T) {
+ buf := newLimitedBuffer(16)
+ if _, err := buf.Write([]byte("0123456789")); nil != err {
+ t.Fatal(err)
+ }
+ if buf.Truncated() {
+ t.Fatal("buffer should not be truncated yet")
+ }
+ if _, err := buf.Write([]byte("abcdefghij")); nil != err {
+ t.Fatal(err)
+ }
+ if !buf.Truncated() {
+ t.Fatal("buffer should be truncated")
+ }
+ if "0123456789abcdef" != buf.String() {
+ t.Fatalf("unexpected content [%s]", buf.String())
+ }
+ if _, err := buf.Write([]byte("more")); nil != err {
+ t.Fatal(err)
+ }
+ if "0123456789abcdef" != buf.String() {
+ t.Fatalf("truncated buffer grew to [%s]", buf.String())
+ }
+}