Skip to content

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

:lock: Prevent SQL injection in graph query tags https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954

Daniel50471b8ad280
diff --git a/kernel/model/graph.go b/kernel/model/graph.go
index 8b49b07a2d..555e189f87 100644
--- a/kernel/model/graph.go
+++ b/kernel/model/graph.go
@@ -677,7 +677,9 @@ func query2Stmt(queryStr string) (ret string) {
return ast.WalkContinue
}
if n.IsTextMarkType("tag") {
- tags = append(tags, n.Text())
+ // 转义单引号,避免标签内容闭合 SQL 字符串字面量造成注入
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954
+ tags = append(tags, strings.ReplaceAll(n.Text(), "'", "''"))
}
return ast.WalkContinue
})
diff --git a/kernel/model/graph_test.go b/kernel/model/graph_test.go
index 07248e954b..b81b321ac9 100644
--- a/kernel/model/graph_test.go
+++ b/kernel/model/graph_test.go
@@ -8,7 +8,12 @@
package model
-import "testing"
+import (
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+)
func TestMarkLinkedNodesWithSize(t *testing.T) {
nodes := []*GraphNode{
@@ -72,3 +77,26 @@ func TestGrowLinkedNodesUsesIndexesAndStopsCycles(t *testing.T) {
t.Fatalf("unexpected grown nodes: %+v", nodes)
}
}
+
+// TestQuery2StmtEscapesTagQuote 验证行级标签文本中的单引号在拼接 SQL 前被转义,
+// 防止标签内容闭合字符串字面量注入查询 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954
+func TestQuery2StmtEscapesTagQuote(t *testing.T) {
+ oldConf := Conf
+ Conf = &AppConf{Search: conf.NewSearch()}
+ t.Cleanup(func() {
+ Conf = oldConf
+ })
+
+ stmt := query2Stmt(`<span data-type="tag">z') UNION SELECT null-- </span>`)
+ if strings.Contains(stmt, `z')`) {
+ t.Fatalf("tag content quote not escaped: %s", stmt)
+ }
+ if !strings.Contains(stmt, `z'')`) {
+ t.Fatalf("escaped tag content not found: %s", stmt)
+ }
+
+ stmt = query2Stmt(`#a' OR '1'='1#`)
+ if strings.Contains(stmt, `' OR '`) {
+ t.Fatalf("shorthand tag content quote not escaped: %s", stmt)
+ }
+}
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 69f579a213..b1c40efd3d 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -976,6 +976,15 @@ func GetChildBlocks(parentID, condition string, limit int) (ret []*Block) {
sqlStmt += " AND " + condition
}
sqlStmt += " LIMIT " + strconv.Itoa(limit)
+ // 关系图查询条件由用户输入动态拼接,执行前校验单条只读语句,防止注入
+ if err := CheckSingleStatement(sqlStmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-single statement: %s", sqlStmt, err)
+ return
+ }
+ if err := CheckReadonlyStatement(sqlStmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-readonly statement: %s", sqlStmt, err)
+ return
+ }
rows, err := query(sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
@@ -997,6 +1006,15 @@ func GetAllChildBlocks(rootIDs []string, condition string, limit int) (ret []*Bl
sqlStmt += " AND " + condition
}
sqlStmt += " LIMIT " + strconv.Itoa(limit)
+ // 关系图查询条件由用户输入动态拼接,执行前校验单条只读语句,防止注入
+ if err := CheckSingleStatement(sqlStmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-single statement: %s", sqlStmt, err)
+ return
+ }
+ if err := CheckReadonlyStatement(sqlStmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-readonly statement: %s", sqlStmt, err)
+ return
+ }
rows, err := query(sqlStmt)
if err != nil {
logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)
diff --git a/kernel/sql/block_query_test.go b/kernel/sql/block_query_test.go
index 73d25659de..ffa60eb1a7 100644
--- a/kernel/sql/block_query_test.go
+++ b/kernel/sql/block_query_test.go
@@ -21,6 +21,85 @@ import (
"testing"
)
+func createGraphTestBlocksTable(t *testing.T) *gosql.DB {
+ t.Helper()
+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")
+ if err != nil {
+ t.Fatalf("open test database failed: %s", err)
+ }
+ testDB.SetMaxOpenConns(1)
+ t.Cleanup(func() {
+ testDB.Close()
+ })
+ if _, err = testDB.Exec("CREATE TABLE blocks (id TEXT, parent_id TEXT, root_id TEXT, hash TEXT, box TEXT, path TEXT, hpath TEXT, name TEXT, alias TEXT, memo TEXT, tag TEXT, content TEXT, fcontent TEXT, markdown TEXT, length INTEGER, type TEXT, subtype TEXT, ial TEXT, sort INTEGER, created TEXT, updated TEXT)"); err != nil {
+ t.Fatalf("create blocks table failed: %s", err)
+ }
+ if _, err = testDB.Exec("INSERT INTO blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES ('child', 'root', 'root', '', '', '/', '/', '', '', '', '', 'hello', '', '', 0, 'p', '', '', 0, '', '')"); err != nil {
+ t.Fatalf("insert block failed: %s", err)
+ }
+ return testDB
+}
+
+// TestGraphChildBlocksRejectNonSingleStatement 验证关系图查询条件无法通过多语句拼接执行写入语句,
+// 执行前由 CheckSingleStatement 拒绝 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954
+func TestGraphChildBlocksRejectNonSingleStatement(t *testing.T) {
+ testDB := createGraphTestBlocksTable(t)
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ blocks := GetAllChildBlocks([]string{"root"}, "1=1); DELETE FROM blocks; --", 10)
+ if 0 != len(blocks) {
+ t.Fatalf("unexpected blocks returned for injected condition: %#v", blocks)
+ }
+ var count int
+ if err := testDB.QueryRow("SELECT COUNT(*) FROM blocks").Scan(&count); err != nil {
+ t.Fatalf("query block count failed: %s", err)
+ }
+ if 1 != count {
+ t.Fatalf("injected statement changed blocks, count: %d", count)
+ }
+}
+
+// TestGraphLocalChildBlocksRejectNonSingleStatement 验证局部关系图查询条件同样无法通过多语句拼接执行写入语句
+func TestGraphLocalChildBlocksRejectNonSingleStatement(t *testing.T) {
+ testDB := createGraphTestBlocksTable(t)
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ blocks := GetChildBlocks("root", "1=1); DELETE FROM blocks; --", 10)
+ if 0 != len(blocks) {
+ t.Fatalf("unexpected blocks returned for injected condition: %#v", blocks)
+ }
+ var count int
+ if err := testDB.QueryRow("SELECT COUNT(*) FROM blocks").Scan(&count); err != nil {
+ t.Fatalf("query block count failed: %s", err)
+ }
+ if 1 != count {
+ t.Fatalf("injected statement changed blocks, count: %d", count)
+ }
+}
+
+// TestGraphChildBlocksAcceptNormalCondition 验证正常的只读查询条件不受校验影响
+func TestGraphChildBlocksAcceptNormalCondition(t *testing.T) {
+ testDB := createGraphTestBlocksTable(t)
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ blocks := GetAllChildBlocks([]string{"root"}, "(content LIKE '%hello%')", 10)
+ if 1 != len(blocks) || "child" != blocks[0].ID {
+ t.Fatalf("unexpected blocks: %#v", blocks)
+ }
+}
+
func TestRootBlockExactMatchCondition(t *testing.T) {
condition, arg := rootBlockExactMatchCondition("Math%_\\", true)
if "content = ?" != condition || "Math%_\\" != arg {
diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.go
index 4b6578ac74..14ed784801 100644
--- a/kernel/sql/block_ref_query.go
+++ b/kernel/sql/block_ref_query.go
@@ -736,6 +736,16 @@ func DefRefs(condition string, limit int) (ret []map[*Block]*Block) {
stmt += " AND " + condition
}
+ // 关系图查询条件由用户输入动态拼接,执行前校验单条只读语句,防止注入
+ if err := CheckSingleStatement(stmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-single statement: %s", stmt, err)
+ return
+ }
+ if err := CheckReadonlyStatement(stmt); nil != err {
+ logging.LogErrorf("sql query [%s] rejected as non-readonly statement: %s", stmt, err)
+ return
+ }
+
rows, err := query(stmt)
if err != nil {
logging.LogErrorf("sql query failed: %s", err)
diff --git a/kernel/sql/block_ref_query_test.go b/kernel/sql/block_ref_query_test.go
index e538901503..a2e7b6a50e 100644
--- a/kernel/sql/block_ref_query_test.go
+++ b/kernel/sql/block_ref_query_test.go
@@ -169,3 +169,49 @@ func TestQueryRefsByDefIDsInBoxBatchesAndParameterizesIDs(t *testing.T) {
t.Fatalf("query argument changed stored refs, count: %d", count)
}
}
+
+// TestDefRefsRejectNonSingleStatement 验证关系图引用查询条件无法通过多语句拼接执行写入语句,
+// 执行前由 CheckSingleStatement 拒绝 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5rwv-4j4c-f954
+func TestDefRefsRejectNonSingleStatement(t *testing.T) {
+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")
+ if nil != err {
+ t.Fatalf("open test database failed: %s", err)
+ }
+ testDB.SetMaxOpenConns(1)
+ defer testDB.Close()
+ if _, err = testDB.Exec("CREATE TABLE blocks (id TEXT, parent_id TEXT, root_id TEXT, hash TEXT, box TEXT, path TEXT, hpath TEXT, name TEXT, alias TEXT, memo TEXT, tag TEXT, content TEXT, fcontent TEXT, markdown TEXT, length INTEGER, type TEXT, subtype TEXT, ial TEXT, sort INTEGER, created TEXT, updated TEXT)"); nil != err {
+ t.Fatalf("create blocks table failed: %s", err)
+ }
+ if _, err = testDB.Exec("CREATE TABLE refs (block_id TEXT, def_block_id TEXT)"); nil != err {
+ t.Fatalf("create refs table failed: %s", err)
+ }
+ if _, err = testDB.Exec("INSERT INTO blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES ('def', '', 'def', '', '', '/', '/', '', '', '', '', '', '', '', 0, 'd', '', '', 0, '', '')"); nil != err {
+ t.Fatalf("insert block failed: %s", err)
+ }
+ if _, err = testDB.Exec("INSERT INTO refs VALUES ('def', 'def')"); nil != err {
+ t.Fatalf("insert ref failed: %s", err)
+ }
+
+ previousDB := db
+ db = testDB
+ defer func() {
+ db = previousDB
+ }()
+
+ ret := DefRefs("1=1); DELETE FROM blocks; --", 10)
+ if 0 != len(ret) {
+ t.Fatalf("unexpected refs returned for injected condition: %#v", ret)
+ }
+ var count int
+ if err = testDB.QueryRow("SELECT COUNT(*) FROM blocks").Scan(&count); nil != err {
+ t.Fatalf("query block count failed: %s", err)
+ }
+ if 1 != count {
+ t.Fatalf("injected statement changed blocks, count: %d", count)
+ }
+
+ ret = DefRefs("ref.content LIKE '%x%'", 10)
+ if 0 != len(ret) {
+ t.Fatalf("unexpected refs returned for non-matching condition: %#v", ret)
+ }
+}