Skip to content

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

:lock: Fix SQL injection in history search https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c

Daniel719633831a2d
diff --git a/kernel/model/history.go b/kernel/model/history.go
index e8f21ebcc5..3f06ec952a 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -822,7 +822,9 @@ func buildSearchHistoryQueryFilter(query, op, box, table string, typ int) (stmt
case HistoryTypeDoc:
stmt += table + " MATCH '{title content}:(" + query + ")'"
case HistoryTypeDocID:
- stmt += " id = '" + query + "'"
+ // id 为等值比较,仅需按 SQL 字符串字面量转义单引号,不能使用面向 FTS 的 stringQuery
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+ stmt += " id = '" + strings.ReplaceAll(query, "'", "''") + "'"
case HistoryTypeAsset:
stmt += table + " MATCH '{title content}:(" + query + ")'"
case HistoryTypeDatabase:
@@ -833,7 +835,13 @@ func buildSearchHistoryQueryFilter(query, op, box, table string, typ int) (stmt
}
if op = strings.TrimSpace(op); op != "" && op != "all" {
- stmt += " AND op = '" + op + "'"
+ if !gulu.Str.Contains(op, validOps) {
+ // 白名单外的 op 取值直接判为空结果,避免拼入 SQL
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+ stmt += " AND 1=0"
+ } else {
+ stmt += " AND op = '" + op + "'"
+ }
}
if "%" != box && !ast.IsNodeIDPattern(box) {
diff --git a/kernel/model/history_search_injection_test.go b/kernel/model/history_search_injection_test.go
new file mode 100644
index 0000000000..e9b949ede5
--- /dev/null
+++ b/kernel/model/history_search_injection_test.go
@@ -0,0 +1,107 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// TestHistorySearchInjection 覆盖历史搜索的注入回归
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+func TestHistorySearchInjection(t *testing.T) {
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir = filepath.Join(root, "data")
+ util.TempDir = filepath.Join(root, "temp")
+ util.ConfDir = filepath.Join(root, "conf")
+ util.HistoryDir = filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir, util.QueueDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ Conf.Search = conf.NewSearch()
+ Conf.FileTree = conf.NewFileTree()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+
+ const boxID = "20260101000000-box0001"
+ const docID = "20260101000000-doc0001"
+ const deletedDocID = "20260101000001-doc0002"
+ created := strconv.FormatInt(time.Now().Unix(), 10)
+ deletedCreated := strconv.FormatInt(time.Now().Add(-time.Minute).Unix(), 10)
+ sql.IndexHistoriesQueue([]*sql.History{
+ {ID: docID, Type: HistoryTypeDoc, Op: HistoryOpUpdate, Title: "Canary", Content: "HISTORYCANARY",
+ Path: "2026-01-01-000000-update/" + boxID + "/" + docID + ".sy", Created: created},
+ {ID: deletedDocID, Type: HistoryTypeDoc, Op: HistoryOpDelete, Title: "Deleted title", Content: "DELETEDTEXT",
+ Path: "2026-01-01-000000-delete/" + boxID + "/" + deletedDocID + ".sy", Created: deletedCreated},
+ })
+ sql.FlushHistoryQueue()
+
+ countRows := func() int {
+ t.Helper()
+ result, err := sql.QueryHistory("SELECT COUNT(*) AS total FROM histories_fts_case_insensitive")
+ if nil != err || 1 > len(result) {
+ t.Fatalf("count history rows failed: %s", err)
+ }
+ return int(result[0]["total"].(int64))
+ }
+ if 2 != countRows() {
+ t.Fatalf("history seed failed: %d rows", countRows())
+ }
+
+ // 正常查询不受影响
+ if items := FullTextSearchHistoryItems(created, docID, "%", "", HistoryTypeDocID); 1 != len(items) || docID != items[0].ID {
+ t.Fatalf("normal docID search broken: %+v", items)
+ }
+ if _, _, total := FullTextSearchHistory("", "%", HistoryOpUpdate, HistoryTypeDoc, 1); 1 != total {
+ t.Fatalf("normal op filter broken: %d", total)
+ }
+ if _, _, total := FullTextSearchHistory("Canary", "%", "all", HistoryTypeDoc, 1); 1 != total {
+ t.Fatalf("normal content search broken: %d", total)
+ }
+
+ // type=3 的 query 注入不再泄漏其他历史记录
+ union := "x' UNION SELECT id, type, op, title, content, path, created FROM histories_fts_case_insensitive --"
+ if items := FullTextSearchHistoryItems(created, union, "%", "", HistoryTypeDocID); 0 != len(items) {
+ t.Fatalf("UNION injection leaked %d items", len(items))
+ }
+ if items := FullTextSearchHistoryItems(created, docID+"' OR '1'='1", "%", "", HistoryTypeDocID); 0 != len(items) {
+ t.Fatalf("quote injection leaked %d items", len(items))
+ }
+
+ // op 注入不再绕过过滤条件
+ if _, _, total := FullTextSearchHistory("", "%", "delete' OR '1'='1", HistoryTypeDoc, 1); 0 != total {
+ t.Fatalf("op injection bypassed the filter: %d", total)
+ }
+
+ // 堆叠写语句被拒绝
+ before := countRows()
+ write := "x'; INSERT INTO histories_fts_case_insensitive (id, type, op, title, content, path, created) " +
+ "SELECT '20260101000002-doc0003', '1', 'update', 'INJECTED', 'PWNED', '/box/evil.sy', '" + created + "' FROM histories_fts_case_insensitive WHERE '1'='1"
+ FullTextSearchHistoryItems(created, write, "%", "", HistoryTypeDocID)
+ if after := countRows(); before != after {
+ t.Fatalf("stacked INSERT was executed: %d -> %d rows", before, after)
+ }
+ if items := FullTextSearchHistoryItems(created, "20260101000002-doc0003", "%", "", HistoryTypeDocID); 0 != len(items) {
+ t.Fatal("the injected history row is retrievable")
+ }
+}
diff --git a/kernel/sql/history.go b/kernel/sql/history.go
index 0072417e21..fe35375002 100644
--- a/kernel/sql/history.go
+++ b/kernel/sql/history.go
@@ -38,6 +38,12 @@ type History struct {
func QueryHistory(stmt string) (ret []map[string]any, err error) {
ret = []map[string]any{}
+ // 历史查询语句由调用方拼接,执行前必须校验为单条只读语句
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+ if err = CheckHistoryReadonlyStatement(stmt); nil != err {
+ logging.LogWarnf("sql query [%s] rejected as non-readonly: %s", stmt, err)
+ return
+ }
rows, err := queryHistory(stmt)
if err != nil {
logging.LogWarnf("sql query [%s] failed: %s", stmt, err)
@@ -75,6 +81,12 @@ func SelectHistoriesRawStmt(stmt string) (ret []*History) {
if nil == historyDB {
return
}
+ // 历史查询语句由调用方拼接,执行前必须校验为单条只读语句
+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+ if err := CheckHistoryReadonlyStatement(stmt); nil != err {
+ logging.LogWarnf("sql query [%s] rejected as non-readonly: %s", stmt, err)
+ return
+ }
rows, err := historyDB.Query(stmt)
if err != nil {
logging.LogWarnf("sql query [%s] failed: %s", stmt, err)
diff --git a/kernel/sql/history_readonly_stmt_test.go b/kernel/sql/history_readonly_stmt_test.go
new file mode 100644
index 0000000000..e7ff0ed3ed
--- /dev/null
+++ b/kernel/sql/history_readonly_stmt_test.go
@@ -0,0 +1,86 @@
+package sql
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// TestHistoryReadonlyStatementGuard 覆盖历史查询 sink 的「单条 + 只读」校验
+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+func TestHistoryReadonlyStatementGuard(t *testing.T) {
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir = filepath.Join(root, "data")
+ util.TempDir = filepath.Join(root, "temp")
+ util.ConfDir = filepath.Join(root, "conf")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.QueueDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ InitDatabase(true)
+ InitHistoryDatabase(true)
+ InitAssetContentDatabase(true)
+ t.Cleanup(CloseDatabase)
+
+ countRows := func() int {
+ t.Helper()
+ result, err := QueryHistory("SELECT COUNT(*) AS total FROM histories_fts_case_insensitive")
+ if nil != err || 1 > len(result) {
+ t.Fatalf("count history rows failed: %s", err)
+ }
+ return int(result[0]["total"].(int64))
+ }
+
+ valid := []string{
+ "SELECT DISTINCT created FROM histories_fts_case_insensitive WHERE 1=1 AND op = 'update'",
+ "SELECT * FROM histories_fts_case_insensitive WHERE histories_fts_case_insensitive MATCH '{title content}:(foo)'",
+ "SELECT * FROM histories_fts_case_insensitive WHERE id = '20260101000000-aaaaaaa' AND created = '1700000000' ORDER BY created DESC LIMIT 32",
+ }
+ for _, stmt := range valid {
+ if err := CheckHistoryReadonlyStatement(stmt); nil != err {
+ t.Fatalf("valid history statement [%s] rejected: %s", stmt, err)
+ }
+ }
+
+ invalid := []string{
+ "DELETE FROM histories_fts_case_insensitive",
+ "INSERT INTO histories_fts_case_insensitive (id) VALUES ('20260101000000-aaaaaaa')",
+ "SELECT * FROM histories_fts_case_insensitive; DELETE FROM histories_fts_case_insensitive",
+ "SELECT * FROM histories_fts_case_insensitive WHERE 1=1; INSERT INTO histories_fts_case_insensitive SELECT * FROM histories_fts_case_insensitive",
+ "PRAGMA journal_mode=DELETE",
+ "ATTACH DATABASE 'attached.db' AS attached",
+ }
+ for _, stmt := range invalid {
+ if err := CheckHistoryReadonlyStatement(stmt); nil == err {
+ t.Fatalf("statement [%s] was not rejected", stmt)
+ }
+ }
+
+ IndexHistoriesQueue([]*History{{ID: "20260101000000-aaaaaaa", Type: 1, Op: "update", Title: "t", Content: "c",
+ Path: "2026-01-01-000000-update/box/20260101000000-aaaaaaa.sy", Created: "1700000000"}})
+ FlushHistoryQueue()
+ if 1 != countRows() {
+ t.Fatalf("history seed failed: %d rows", countRows())
+ }
+
+ SelectHistoriesRawStmt("SELECT * FROM histories_fts_case_insensitive WHERE 1=0; DELETE FROM histories_fts_case_insensitive")
+ if 1 != countRows() {
+ t.Fatal("SelectHistoriesRawStmt executed a non-readonly statement")
+ }
+
+ if _, err := QueryHistory("SELECT * FROM histories_fts_case_insensitive; DELETE FROM histories_fts_case_insensitive"); nil == err {
+ t.Fatal("QueryHistory accepted a multi-statement query")
+ }
+ if 1 != countRows() {
+ t.Fatal("QueryHistory executed a non-readonly statement")
+ }
+}
diff --git a/kernel/sql/stmt_validate.go b/kernel/sql/stmt_validate.go
index 7d7f7f0051..2b2e6a9a48 100644
--- a/kernel/sql/stmt_validate.go
+++ b/kernel/sql/stmt_validate.go
@@ -172,6 +172,16 @@ func CheckAssetContentReadonlyStatement(stmt string) error {
return checkReadonlyStatement(stmt, assetContentDB)
}
+// CheckHistoryReadonlyStatement 在历史数据库连接上检查 SQL 为「单条 + 只读」。
+// 历史查询语句只引用 history.db 中的表,必须在该连接上 prepare 才能通过校验。
+// 见 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-4hjx-84f6-gr7c
+func CheckHistoryReadonlyStatement(stmt string) error {
+ if err := CheckSingleStatement(stmt); nil != err {
+ return err
+ }
+ return checkReadonlyStatement(stmt, historyDB)
+}
+
// CheckReadonlyBlockQueryStatement 校验原始块查询语句为「单条 + 只读」,boxID 为空或普通笔记本时
// 在全局库上校验,加密笔记本在其独立加密库上校验。
//