Skip to content

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

:lock: Restrict SQL execution in live templates https://github.com/siyuan-note/siyuan/security/advisories/GHSA-x67c-8pwr-m8g3

Daniel0a176345e02a
diff --git a/kernel/model/template.go b/kernel/model/template.go
index d3a71d7d30..3a58d17b5a 100644
--- a/kernel/model/template.go
+++ b/kernel/model/template.go
@@ -324,8 +324,7 @@ func RenderDynamicIconContentTemplate(content, id string) (ret string) {
dataModel["alias"] = block.Alias
goTpl := template.New("").Delims(".action{", "}")
- tplFuncMap := filesys.BuiltInTemplateFuncs()
- sql.SQLTemplateFuncs(&tplFuncMap)
+ tplFuncMap := dynamicIconTemplateFuncs()
goTpl = goTpl.Funcs(tplFuncMap)
tpl, err := goTpl.Funcs(tplFuncMap).Parse(content)
if err != nil {
@@ -343,6 +342,10 @@ func RenderDynamicIconContentTemplate(content, id string) (ret string) {
return
}
+func dynamicIconTemplateFuncs() template.FuncMap {
+ return filesys.BuiltInTemplateFuncs()
+}
+
func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, err error) {
tree, err = LoadTreeByBlockID(id)
if err != nil {
diff --git a/kernel/model/template_security_test.go b/kernel/model/template_security_test.go
new file mode 100644
index 0000000000..401c09c045
--- /dev/null
+++ b/kernel/model/template_security_test.go
@@ -0,0 +1,31 @@
+// 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.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import "testing"
+
+func TestDynamicIconTemplateFuncsExcludeSQL(t *testing.T) {
+ funcs := dynamicIconTemplateFuncs()
+ for _, name := range []string{"queryBlocks", "querySpans", "querySQL", "getBlock"} {
+ if _, ok := funcs[name]; ok {
+ t.Fatalf("动态图标模板不应包含 SQL 函数 [%s]", name)
+ }
+ }
+ if _, ok := funcs["date"]; !ok {
+ t.Fatal("动态图标模板应保留内置模板函数")
+ }
+}
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 5b81158e43..fdfbdf4b9b 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -1778,10 +1778,25 @@ func closeDatabase() {
}
func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
+ readonlyStmts := &sync.Map{}
+ isReadonlyStmt := func(stmt string) bool {
+ if _, ok := readonlyStmts.Load(stmt); ok {
+ return true
+ }
+ if CheckSingleStatement(stmt) != nil || CheckReadonlyStatement(stmt) != nil {
+ return false
+ }
+ readonlyStmts.Store(stmt, struct{}{})
+ return true
+ }
+
(*templateFuncMap)["queryBlocks"] = func(stmt string, args ...string) (retBlocks []*Block) {
for _, arg := range args {
stmt = strings.Replace(stmt, "?", arg, 1)
}
+ if !isReadonlyStmt(stmt) {
+ return
+ }
retBlocks = SelectBlocksRawStmt(stmt, 1, 512)
return
}
@@ -1800,11 +1815,14 @@ func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {
for _, arg := range args {
stmt = strings.Replace(stmt, "?", arg, 1)
}
+ if !isReadonlyStmt(stmt) {
+ return
+ }
retSpans = SelectSpansRawStmt(stmt, 512)
return
}
(*templateFuncMap)["querySQL"] = func(stmt string) (ret []map[string]any) {
- if err := CheckSingleStatement(stmt); err != nil {
+ if !isReadonlyStmt(stmt) {
return
}
ret, _ = Query(stmt, 1024)
diff --git a/kernel/sql/template_test.go b/kernel/sql/template_test.go
new file mode 100644
index 0000000000..a1bd50c4cf
--- /dev/null
+++ b/kernel/sql/template_test.go
@@ -0,0 +1,77 @@
+// 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.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package sql
+
+import (
+ gosql "database/sql"
+ "testing"
+ "text/template"
+)
+
+func TestSQLTemplateFuncsAllowReadonlyQueriesAndRejectWrites(t *testing.T) {
+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ testDB.SetMaxOpenConns(1)
+ defer testDB.Close()
+ if _, err = testDB.Exec("CREATE TABLE blocks (id TEXT)"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = testDB.Exec("INSERT INTO blocks VALUES ('block-1')"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = testDB.Exec("CREATE TABLE spans (id TEXT, block_id TEXT, root_id TEXT, box TEXT, path TEXT, content TEXT, markdown TEXT, type TEXT, ial TEXT)"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = testDB.Exec("INSERT INTO spans VALUES ('span-1', 'block-1', 'root-1', 'box-1', '/doc.sy', 'content', 'markdown', 'text', '')"); err != nil {
+ t.Fatal(err)
+ }
+
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ funcs := template.FuncMap{}
+ SQLTemplateFuncs(&funcs)
+
+ querySQL := funcs["querySQL"].(func(string) []map[string]any)
+ rows := querySQL("SELECT id FROM blocks")
+ if 1 != len(rows) || "block-1" != rows[0]["id"] {
+ t.Fatalf("只读模板查询结果不正确:%v", rows)
+ }
+
+ querySpans := funcs["querySpans"].(func(string, ...string) []*Span)
+ spans := querySpans("SELECT * FROM spans LIMIT ?", "1")
+ if 1 != len(spans) || "span-1" != spans[0].ID {
+ t.Fatalf("带参数的只读模板查询结果不正确:%v", spans)
+ }
+
+ queryBlocks := funcs["queryBlocks"].(func(string, ...string) []*Block)
+ queryBlocks("SELECT * FROM blocks; DELETE FROM blocks")
+ querySQL("DELETE FROM blocks RETURNING id")
+
+ var count int
+ if err = testDB.QueryRow("SELECT COUNT(*) FROM blocks").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if 1 != count {
+ t.Fatalf("模板查询执行了写入语句,剩余块数量:%d", count)
+ }
+}