Skip to content

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

:lock: Harden encrypted notebook: fail-closed paths, AV index encryption, HKDF subkeys with AAD https://github.com/siyuan-note/siyuan/issues/18034

Daniela246cda7858a
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 46a8a16906..bb26c550dd 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -281,14 +281,22 @@ func setFileAnnotation(c *gin.Context) {
return
}
} else {
- // 加密笔记本的 .sya 写盘前加密
+ // 加密笔记本的 .sya 写盘前必须加密;加密 box 未解锁时拒绝写入(fail-closed,避免明文落盘)
writeData := []byte(data)
- if boxID := model.ExtractBoxIDFromAssetsPath(writePath); boxID != "" {
- if dek, decErr := model.GetDEK(boxID); decErr == nil && dek != nil {
- if enc, encErr := util.Encrypt(dek, writeData); encErr == nil {
- writeData = enc
- }
+ if boxID := model.ExtractBoxIDFromAssetsPath(writePath); boxID != "" && model.IsEncryptedBox(boxID) {
+ dek, dekErr := model.GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ ret.Code = -1
+ ret.Msg = dekErr.Error()
+ return
}
+ enc, encErr := model.EncryptAsset(boxID, dek, writeData)
+ if encErr != nil {
+ ret.Code = -1
+ ret.Msg = encErr.Error()
+ return
+ }
+ writeData = enc
}
if err = filelock.WriteFile(writePath, writeData); err != nil {
ret.Code = -1
@@ -329,13 +337,21 @@ func getFileAnnotation(c *gin.Context) {
ret.Msg = err.Error()
return
}
- // 加密笔记本的 .sya 读盘后解密
- if boxID := model.ExtractBoxIDFromAssetsPath(readPath); boxID != "" {
- if dek, decErr := model.GetDEK(boxID); decErr == nil && dek != nil {
- if plain, decErr := util.Decrypt(dek, data); decErr == nil {
- data = plain
- }
+ // 加密笔记本的 .sya 读盘后必须解密;未解锁时拒绝返回(fail-closed,避免返回密文或误判)
+ if boxID := model.ExtractBoxIDFromAssetsPath(readPath); boxID != "" && model.IsEncryptedBox(boxID) {
+ dek, dekErr := model.GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ ret.Code = -1
+ ret.Msg = dekErr.Error()
+ return
+ }
+ plain, decErr := model.DecryptAsset(boxID, dek, data)
+ if decErr != nil {
+ ret.Code = -1
+ ret.Msg = decErr.Error()
+ return
}
+ data = plain
}
ret.Data = map[string]any{
"data": string(data),
diff --git a/kernel/api/file.go b/kernel/api/file.go
index 80f03b2af2..2a23b9dbd5 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -41,6 +41,15 @@ import (
// errMsgSeeKernelLog 接在 API 错误提示末尾,引导用户查看内核日志以获取完整信息(避免在 Msg 暴露工作空间绝对路径)。
const errMsgSeeKernelLog = ". For details, see the SiYuan kernel log."
+// rejectEncryptedBoxPath 检查 absPath 是否落在加密 box 目录下,是则返回 true。
+// 原始文件 API(getFile/putFile/copyFile/renameFile/removeFile)是绕过加密层的逃生口,
+// 对加密 box 的任何文件读写都应拒绝——合法读写走专用 API(upload/getBlockKramdown 等,已加密感知),
+// 避免密文泄漏给插件或明文破坏加密格式。
+func rejectEncryptedBoxPath(absPath string) bool {
+ boxID := model.ExtractBoxIDFromAssetsPath(absPath)
+ return boxID != "" && model.IsEncryptedBox(boxID)
+}
+
func getUniqueFilename(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -290,6 +299,14 @@ func copyFile(c *gin.Context) {
return
}
+ // 加密 box 的文件不允许通过原始文件 API 复制(src 读出密文/明文,dest 写入破坏加密存储)
+ if rejectEncryptedBoxPath(src) || rejectEncryptedBoxPath(dest) {
+ ret.Code = -1
+ ret.Msg = "copying encrypted notebook files is not supported via this API"
+ ret.Data = map[string]any{"closeTimeout": 5000}
+ return
+ }
+
info, err := os.Stat(src)
if err != nil {
logging.LogErrorf("stat [%s] failed: %s", src, err)
@@ -348,6 +365,13 @@ func getFile(c *gin.Context) {
c.JSON(http.StatusAccepted, ret)
return
}
+ // 加密 box 的任何文件都不允许通过原始文件 API 读取(不只 .sy):
+ // 密文对插件无意义,且可能被误解析或泄漏;合法读取走专用 API(已加密感知)
+ if rejectEncryptedBoxPath(fileAbsPath) {
+ ret.Code = -1
+ ret.Msg = "access to encrypted notebook files is not supported via this API"
+ return
+ }
if !filelock.IsExist(fileAbsPath) {
ret.Code = http.StatusNotFound
ret.Msg = "file does not exist"
@@ -394,16 +418,6 @@ func getFile(c *gin.Context) {
}
}
- // 加密笔记本的 .sy 是密文,直接返回密文无意义且可能被插件误解析
- if strings.HasSuffix(filePath, ".sy") {
- boxID := model.ExtractBoxIDFromAssetsPath(fileAbsPath)
- if "" != boxID && model.IsEncryptedBox(boxID) {
- ret.Code = -1
- ret.Msg = "access to encrypted notebook .sy files is not supported via this API"
- return
- }
- }
-
data, err := filelock.ReadFile(fileAbsPath)
if err != nil {
logging.LogErrorf("read file [%s] failed: %s", fileAbsPath, err)
@@ -607,6 +621,12 @@ func renameFile(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ // 加密 box 的文件不允许通过原始文件 API 重命名(会破坏加密存储结构/跨 box 搬运密文)
+ if rejectEncryptedBoxPath(srcAbsPath) || rejectEncryptedBoxPath(destAbsPath) {
+ ret.Code = -1
+ ret.Msg = "renaming encrypted notebook files is not supported via this API"
+ return
+ }
if filelock.IsExist(destAbsPath) {
ret.Code = http.StatusConflict
ret.Msg = "Field [newPath]: path already exists"
@@ -675,6 +695,12 @@ func removeFile(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ // 加密 box 的文件不允许通过原始文件 API 删除(破坏加密存储结构)
+ if rejectEncryptedBoxPath(fileAbsPath) {
+ ret.Code = -1
+ ret.Msg = "removing encrypted notebook files is not supported via this API"
+ return
+ }
_, err = os.Stat(fileAbsPath)
if os.IsNotExist(err) {
ret.Code = http.StatusNotFound
@@ -720,6 +746,14 @@ func putFile(c *gin.Context) {
return
}
+ // 加密 box 的任何文件都不允许通过原始文件 API 写入(不只 .sy):
+ // 明文写入会破坏密文格式或污染加密存储;合法写入走专用 API(已加密感知)
+ if rejectEncryptedBoxPath(fileAbsPath) {
+ ret.Code = -1
+ ret.Msg = "writing to encrypted notebook files is not supported via this API"
+ return
+ }
+
fileExists := filelock.IsExist(fileAbsPath)
if !fileExists {
if !util.IsValidUploadFileName(filepath.Base(fileAbsPath)) { // Improve kernel API `/api/file/putFile` parameter validation https://github.com/siyuan-note/siyuan/issues/14658
@@ -777,16 +811,6 @@ func putFile(c *gin.Context) {
break
}
- // 加密笔记本的 .sy 写入会破坏密文格式
- if strings.HasSuffix(fileAbsPath, ".sy") {
- boxID := model.ExtractBoxIDFromAssetsPath(fileAbsPath)
- if "" != boxID && model.IsEncryptedBox(boxID) {
- ret.Code = -1
- ret.Msg = "writing to encrypted notebook .sy files is not supported via this API"
- return
- }
- }
-
err = filelock.WriteFile(fileAbsPath, data)
if err != nil {
logging.LogErrorf("write file [%s] failed: %s", fileAbsPath, err)
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index 00fe5ec456..6736aa15bd 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -156,6 +156,7 @@ func mirrorBlocksPathByAvID(avID string) string {
}
// readMirrorBlocks 按路径读取镜像索引(boxID 为空读全局,非空读加密 box)。
+// 加密 box 的镜像索引是 DEK 加密的密文,读取后需解密。
func readMirrorBlocks(boxID string) (ret map[string][]string) {
ret = map[string][]string{}
p := mirrorBlocksPath(boxID)
@@ -167,6 +168,15 @@ func readMirrorBlocks(boxID string) (ret map[string][]string) {
logging.LogErrorf("read attribute view blocks failed: %s", err)
return
}
+ if boxID != "" {
+ // 加密 box 的镜像索引是密文,解密后再反序列化
+ dec, decErr := decryptAVData(boxID, data)
+ if decErr != nil {
+ logging.LogErrorf("decrypt attribute view blocks failed: %s", decErr)
+ return
+ }
+ data = dec
+ }
if err = msgpack.Unmarshal(data, &ret); err != nil {
logging.LogErrorf("unmarshal attribute view blocks failed: %s", err)
return
@@ -175,6 +185,7 @@ func readMirrorBlocks(boxID string) (ret map[string][]string) {
}
// writeMirrorBlocks 按路径写入镜像索引。
+// 加密 box 的镜像索引写入前用 DEK 加密。
func writeMirrorBlocks(boxID string, data map[string][]string) error {
p := mirrorBlocksPath(boxID)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
@@ -184,6 +195,14 @@ func writeMirrorBlocks(boxID string, data map[string][]string) error {
if err != nil {
return err
}
+ if boxID != "" {
+ // 加密 box 的镜像索引写入前加密
+ enc, encErr := encryptAVData(boxID, raw)
+ if encErr != nil {
+ return encErr
+ }
+ raw = enc
+ }
return filelock.WriteFile(p, raw)
}
@@ -218,7 +237,8 @@ func encryptAVData(boxID string, data []byte) ([]byte, error) {
if dek == nil {
return data, nil // 非加密 box
}
- return util.Encrypt(dek, data)
+ avKey := util.DeriveSubKey(dek, "siyuan/av")
+ return util.EncryptWithAAD(avKey, data, []byte(boxID))
}
func decryptAVData(boxID string, data []byte) ([]byte, error) {
@@ -232,5 +252,6 @@ func decryptAVData(boxID string, data []byte) ([]byte, error) {
if dek == nil {
return data, nil // 非加密 box
}
- return util.Decrypt(dek, data)
+ avKey := util.DeriveSubKey(dek, "siyuan/av")
+ return util.DecryptWithAAD(avKey, data, []byte(boxID))
}
diff --git a/kernel/av/relation.go b/kernel/av/relation.go
index d56ae42639..c52d0382d0 100644
--- a/kernel/av/relation.go
+++ b/kernel/av/relation.go
@@ -16,27 +16,82 @@ var (
attributeViewRelationsLock = sync.Mutex{}
)
-func GetSrcAvIDs(destAvID string) []string {
- attributeViewRelationsLock.Lock()
- defer attributeViewRelationsLock.Unlock()
-
- relations := filepath.Join(util.DataDir, "storage", "av", "relations.msgpack")
- if !filelock.IsExist(relations) {
- return nil
+// relationsPath 返回 relations 索引文件路径,按 AV 归属 box 分箱。
+// 加密 box:<DataDir>/<boxID>/storage/av/relations.msgpack(DEK 加密)
+// 普通 box:<DataDir>/storage/av/relations.msgpack(明文)
+func relationsPath(boxID string) string {
+ if boxID != "" {
+ return filepath.Join(util.DataDir, boxID, "storage", "av", "relations.msgpack")
}
+ return filepath.Join(util.DataDir, "storage", "av", "relations.msgpack")
+}
- data, err := filelock.ReadFile(relations)
+// readRelations 读取 relations 索引(boxID 非空时自动解密)。
+func readRelations(boxID string) (avRels map[string][]string) {
+ avRels = map[string][]string{}
+ p := relationsPath(boxID)
+ if !filelock.IsExist(p) {
+ return
+ }
+ data, err := filelock.ReadFile(p)
if err != nil {
logging.LogErrorf("read attribute view relations failed: %s", err)
- return nil
+ return
+ }
+ if boxID != "" {
+ dec, decErr := decryptAVData(boxID, data)
+ if decErr != nil {
+ logging.LogErrorf("decrypt attribute view relations failed: %s", decErr)
+ return
+ }
+ data = dec
}
-
- avRels := map[string][]string{}
if err = msgpack.Unmarshal(data, &avRels); err != nil {
logging.LogErrorf("unmarshal attribute view relations failed: %s", err)
- return nil
+ return
+ }
+ return
+}
+
+// writeRelations 写入 relations 索引(boxID 非空时加密)。
+func writeRelations(boxID string, avRels map[string][]string) {
+ p := relationsPath(boxID)
+ if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
+ logging.LogErrorf("create attribute view dir failed: %s", err)
+ return
+ }
+ data, err := msgpack.Marshal(avRels)
+ if err != nil {
+ logging.LogErrorf("marshal attribute view relations failed: %s", err)
+ return
+ }
+ if boxID != "" {
+ enc, encErr := encryptAVData(boxID, data)
+ if encErr != nil {
+ logging.LogErrorf("encrypt attribute view relations failed: %s", encErr)
+ return
+ }
+ data = enc
}
+ if err = filelock.WriteFile(p, data); err != nil {
+ logging.LogErrorf("write attribute view relations failed: %s", err)
+ return
+ }
+}
+
+// relationsBoxIDByAvID 由 destAvID 反查归属 boxID,决定 relations 索引的存储位置。
+// 加密 box 的 AV 返回其 boxID;普通 box 的 AV 返回空串(全局路径)。
+func relationsBoxIDByAvID(avID string) string {
+ _, boxID := FindAttributeViewPath(avID)
+ return boxID
+}
+
+func GetSrcAvIDs(destAvID string) []string {
+ attributeViewRelationsLock.Lock()
+ defer attributeViewRelationsLock.Unlock()
+ boxID := relationsBoxIDByAvID(destAvID)
+ avRels := readRelations(boxID)
srcAvIDs := avRels[destAvID]
if nil == srcAvIDs {
return nil
@@ -48,22 +103,8 @@ func RemoveAvRel(srcAvID, destAvID string) {
attributeViewRelationsLock.Lock()
defer attributeViewRelationsLock.Unlock()
- relations := filepath.Join(util.DataDir, "storage", "av", "relations.msgpack")
- if !filelock.IsExist(relations) {
- return
- }
-
- data, err := filelock.ReadFile(relations)
- if err != nil {
- logging.LogErrorf("read attribute view relations failed: %s", err)
- return
- }
-
- avRels := map[string][]string{}
- if err = msgpack.Unmarshal(data, &avRels); err != nil {
- logging.LogErrorf("unmarshal attribute view relations failed: %s", err)
- return
- }
+ boxID := relationsBoxIDByAvID(destAvID)
+ avRels := readRelations(boxID)
srcAvIDs := avRels[destAvID]
if nil == srcAvIDs {
@@ -77,54 +118,32 @@ func RemoveAvRel(srcAvID, destAvID string) {
}
}
avRels[destAvID] = newAvIDs
-
- data, err = msgpack.Marshal(avRels)
- if err != nil {
- logging.LogErrorf("marshal attribute view relations failed: %s", err)
- return
- }
- if err = filelock.WriteFile(relations, data); err != nil {
- logging.LogErrorf("write attribute view relations failed: %s", err)
- return
- }
+ writeRelations(boxID, avRels)
}
func UpsertAvBackRel(srcAvID, destAvID string) {
attributeViewRelationsLock.Lock()
defer attributeViewRelationsLock.Unlock()
- avRelations := map[string][]string{}
- relations := filepath.Join(util.DataDir, "storage", "av", "relations.msgpack")
- if !filelock.IsExist(relations) {
- if err := os.MkdirAll(filepath.Dir(relations), 0755); err != nil {
- logging.LogErrorf("create attribute view dir failed: %s", err)
- return
- }
- } else {
- data, err := filelock.ReadFile(relations)
- if err != nil {
- logging.LogErrorf("read attribute view relations failed: %s", err)
- return
- }
-
- if err = msgpack.Unmarshal(data, &avRelations); err != nil {
- logging.LogErrorf("unmarshal attribute view relations failed: %s", err)
+ // 跨加密边界拒绝:src 和 dest 必须处于同一加密边界(都普通或同一加密 box),
+ // 否则关联会把加密 AV 的存在/结构泄漏到普通库或另一个加密 box
+ _, srcBox := FindAttributeViewPath(srcAvID)
+ _, destBox := FindAttributeViewPath(destAvID)
+ if AVIsEncryptedBox != nil {
+ srcEnc := srcBox != "" && AVIsEncryptedBox(srcBox)
+ destEnc := destBox != "" && AVIsEncryptedBox(destBox)
+ if srcEnc != destEnc || (srcEnc && destEnc && srcBox != destBox) {
+ logging.LogWarnf("skip cross-boundary AV relation: src=%s(box=%s) dest=%s(box=%s)", srcAvID, srcBox, destAvID, destBox)
return
}
}
- srcAvIDs := avRelations[destAvID]
+ boxID := destBox
+ avRels := readRelations(boxID)
+
+ srcAvIDs := avRels[destAvID]
srcAvIDs = append(srcAvIDs, srcAvID)
srcAvIDs = gulu.Str.RemoveDuplicatedElem(srcAvIDs)
- avRelations[destAvID] = srcAvIDs
-
- data, err := msgpack.Marshal(avRelations)
- if err != nil {
- logging.LogErrorf("marshal attribute view relations failed: %s", err)
- return
- }
- if err = filelock.WriteFile(relations, data); err != nil {
- logging.LogErrorf("write attribute view relations failed: %s", err)
- return
- }
+ avRels[destAvID] = srcAvIDs
+ writeRelations(boxID, avRels)
}
diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.go
index aafecc04c7..9e8e217b1a 100644
--- a/kernel/filesys/crypto_hook.go
+++ b/kernel/filesys/crypto_hook.go
@@ -30,8 +30,8 @@ import (
// filesys 不能直接 import model(会形成 model → filesys → model 循环依赖),故采用回调注入。
var DEKProvider func(boxID string) ([]byte, error)
-// encryptData 若 boxID 是已解锁的加密 box,用其 DEK 加密 data;非加密 box 原样返回;
-// 加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。
+// encryptData 若 boxID 是已解锁的加密 box,用 fileKey(DEK 派生子密钥)加密 data 并绑定 boxID 为 AAD;
+// 非加密 box 原样返回;加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。
func encryptData(boxID string, data []byte) ([]byte, error) {
if DEKProvider == nil {
return data, nil
@@ -43,7 +43,8 @@ func encryptData(boxID string, data []byte) ([]byte, error) {
if dek == nil {
return data, nil // 非加密 box
}
- return util.Encrypt(dek, data)
+ fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ return util.EncryptWithAAD(fileKey, data, []byte(boxID))
}
// decryptData 对应解密。非加密 box 原样返回;加密但未解锁时返回 error,拒绝读盘。
@@ -58,7 +59,8 @@ func decryptData(boxID string, data []byte) ([]byte, error) {
if dek == nil {
return data, nil // 非加密 box
}
- return util.Decrypt(dek, data)
+ fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ return util.DecryptWithAAD(fileKey, data, []byte(boxID))
}
// docIALBoxID 从 .sy 绝对路径反推 boxID,供 DocIAL 判断是否需整体解密。
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 58a4f63cb2..0d0f524ae8 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -558,6 +558,18 @@ func IsEncryptedBox(boxID string) bool {
return boxConf != nil && boxConf.Encrypted
}
+// IsSameCryptoBoundary 判断 srcBox 与 dstBox 是否处于同一加密边界(跨 box 操作是否安全)。
+// 普通笔记本之间允许(都不加密);加密笔记本仅允许同一 box 内部操作——两个不同的加密 box 各有独立 DEK,
+// 之间互为"加密边界外",跨 box 移动/合并会用错 DEK 导致密文损坏。供 MoveDocs/Doc2Heading 等跨 box 操作校验。
+func IsSameCryptoBoundary(srcBox, dstBox string) bool {
+ srcEnc := IsEncryptedBox(srcBox)
+ dstEnc := IsEncryptedBox(dstBox)
+ if !srcEnc && !dstEnc {
+ return true // 普通↔普通:允许
+ }
+ return srcEnc && dstEnc && srcBox == dstBox // 加密:仅同一 box 内允许
+}
+
// IsBlockRefCrossingBoundary 判断从 srcBoxID 引用 defBlockID 是否跨越加密边界。
// 加密笔记本禁止跨边界块引(双向):加密 box 的块只能引用同一加密 box 内的块,普通 box 的块不能引用加密 box 的块。
// 供 transaction 落库时兜底校验,防止手工输入/拖拽/粘贴/API 直调绕过前端搜索分流。
@@ -643,23 +655,39 @@ func ExtractBoxIDFromAssetsPath(absPath string) string {
// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。
// 若 srcPath 在已解锁的加密 box 下,读密文→解密→写明文到 destPath(导出目录);
// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。
+// EncryptAsset 用 assetKey(DEK 派生子密钥)加密 asset 字节,AAD 绑定 boxID。
+// 供 assets/.names.json/.sya 等资源类数据统一加密,与 .sy(fileKey)和 AV(avKey)用途分离。
+func EncryptAsset(boxID string, dek, plaintext []byte) ([]byte, error) {
+ assetKey := util.DeriveSubKey(dek, "siyuan/asset")
+ return util.EncryptWithAAD(assetKey, plaintext, []byte(boxID))
+}
+
+// DecryptAsset 对应解密。
+func DecryptAsset(boxID string, dek, ciphertext []byte) ([]byte, error) {
+ assetKey := util.DeriveSubKey(dek, "siyuan/asset")
+ return util.DecryptWithAAD(assetKey, ciphertext, []byte(boxID))
+}
+
func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {
boxID := ExtractBoxIDFromAssetsPath(srcPath)
- if boxID != "" {
- if dek, err := GetDEK(boxID); err == nil && dek != nil {
- raw, readErr := filelock.ReadFile(srcPath)
- if readErr != nil {
- return readErr
- }
- plain, decErr := util.Decrypt(dek, raw)
- if decErr != nil {
- return errors.New(Conf.Language(316))
- }
- if err := filelock.WriteFile(destPath, plain); err != nil {
- return err
- }
- return nil
+ if boxID != "" && IsEncryptedBox(boxID) {
+ dek, err := GetDEKIfUnlocked(boxID)
+ if err != nil {
+ // 加密 box 未解锁:fail-closed,不解密
+ return filelock.Copy(srcPath, destPath)
+ }
+ raw, readErr := filelock.ReadFile(srcPath)
+ if readErr != nil {
+ return readErr
+ }
+ plain, decErr := DecryptAsset(boxID, dek, raw)
+ if decErr != nil {
+ return errors.New(Conf.Language(316))
}
+ if err := filelock.WriteFile(destPath, plain); err != nil {
+ return err
+ }
+ return nil
}
return filelock.Copy(srcPath, destPath)
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index c166ba5a44..6b2f573ddf 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1393,10 +1393,10 @@ func MoveDocs(fromPaths []string, toBoxID, toPath string, callback any) (err err
}
}
- // 禁止跨加密边界移动文档:加密笔记本是孤岛,密文↔明文边界转换未实现,移动会导致数据损坏
- toEncrypted := IsEncryptedBox(toBox.ID)
+ // 禁止跨加密边界移动文档:加密笔记本是孤岛,不同加密 box 各有独立 DEK,
+ // 跨边界移动(普通↔加密、加密 A↔加密 B)会导致密文用错 DEK 损坏数据
for _, fromBox := range pathsBoxes {
- if fromBox.ID != toBox.ID && IsEncryptedBox(fromBox.ID) != toEncrypted {
+ if fromBox.ID != toBox.ID && !IsSameCryptoBoundary(fromBox.ID, toBox.ID) {
err = errors.New(Conf.Language(313))
return
}
diff --git a/kernel/model/filesys_init.go b/kernel/model/filesys_init.go
index c2f69475f1..1c52b65b94 100644
--- a/kernel/model/filesys_init.go
+++ b/kernel/model/filesys_init.go
@@ -19,15 +19,18 @@ package model
import (
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
)
-// init 把 GetDEKIfUnlocked 注入 filesys 包,让 filesys 的 .sy 读写插点能查询 box 的 DEK。
-// 同时把 AV 相关回调注入 av 包,让 AV 定义的笔记本级存储能查询 DEK 和已打开的加密 box。
-// filesys / av 不能直接 import model(循环依赖),故通过回调注入。
+// init 把加密相关的回调注入各底层包,让它们能查询 box 的 DEK / 加密状态。
+// filesys / av / sql / treenode 不能直接 import model(循环依赖),故通过回调注入。
+// sql / treenode 的路由函数据此 fail-closed:加密 box 未解锁时绝不回退全局库。
func init() {
filesys.DEKProvider = GetDEKIfUnlocked
av.AVDEKProvider = GetDEKIfUnlocked
av.AVEncryptedBoxIDs = treenode.GetOpenedEncryptedBoxIDs
av.AVIsEncryptedBox = IsEncryptedBox
+ sql.IsEncryptedBoxFn = IsEncryptedBox
+ treenode.IsEncryptedBoxFn = IsEncryptedBox
}
diff --git a/kernel/model/heading.go b/kernel/model/heading.go
index 9b6c1047ef..7c20a8a9f3 100644
--- a/kernel/model/heading.go
+++ b/kernel/model/heading.go
@@ -177,8 +177,9 @@ func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath st
return
}
- // 禁止跨加密边界:Doc2Heading 会合并 srcTree 和 targetTree 的内容
- if IsEncryptedBox(srcTree.Box) != IsEncryptedBox(targetTree.Box) {
+ // 禁止跨加密边界:Doc2Heading 会合并 srcTree 和 targetTree 的内容,
+ // 不同加密 box 各有独立 DEK,跨边界合并会导致密文用错 DEK 损坏数据
+ if !IsSameCryptoBoundary(srcTree.Box, targetTree.Box) {
err = errors.New(Conf.Language(313))
return
}
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index 018edf3b28..5f26649dac 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -394,22 +394,26 @@ func getAssetsDir(boxLocalPath, docDirLocalPath string) (assets string) {
return
}
-// writeAssetFile 把 src 的内容写入 writePath。若 boxID 是已解锁的加密 box,先加密字节流再落盘;
-// 否则直接按 reader 写(走 filelock.WriteFileByReader 原路径,保留锁语义)。
+// writeAssetFile 把 src 的内容写入 writePath。加密 box 必须已解锁(DEK 在内存)才写入——
+// 先全读 → 加密 → 落盘;加密但未解锁时返回错误(fail-closed,避免明文落盘到加密 box)。
+// 非加密 box 按 reader 直接写(走 filelock.WriteFileByReader 原路径,保留锁语义)。
func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
- if boxID != "" {
- if dek, decErr := GetDEK(boxID); decErr == nil && dek != nil {
- // 已解锁的加密 box:全读 → 加密 → 落盘
- raw, readErr := io.ReadAll(src)
- if readErr != nil {
- return readErr
- }
- enc, encErr := util.Encrypt(dek, raw)
- if encErr != nil {
- return encErr
- }
- return filelock.WriteFile(writePath, enc)
+ if boxID != "" && IsEncryptedBox(boxID) {
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ // 加密 box 未解锁:拒绝写入,避免明文落盘(深度防御,见 issue #18034)
+ return dekErr
+ }
+ // 已解锁的加密 box:全读 → 加密 → 落盘
+ raw, readErr := io.ReadAll(src)
+ if readErr != nil {
+ return readErr
+ }
+ enc, encErr := EncryptAsset(boxID, dek, raw)
+ if encErr != nil {
+ return encErr
}
+ return filelock.WriteFile(writePath, enc)
}
return filelock.WriteFileByReader(writePath, src)
}
@@ -442,7 +446,7 @@ func writeAssetNameMapping(boxID, diskName, originalName string) {
logging.LogErrorf("get DEK for asset name mapping failed: %s", err)
return
}
- enc, err := util.Encrypt(dek, data)
+ enc, err := EncryptAsset(boxID, dek, data)
if err != nil {
logging.LogErrorf("encrypt asset name mapping failed: %s", err)
return
@@ -467,7 +471,7 @@ func readAssetNameMapping(boxID string) map[string]string {
if err != nil || dek == nil {
return ret
}
- data, err := util.Decrypt(dek, enc)
+ data, err := DecryptAsset(boxID, dek, enc)
if err != nil {
logging.LogErrorf("decrypt asset name mapping failed: %s", err)
return ret
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 000bf07336..239eb21449 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -58,6 +58,11 @@ var (
// encryptedDBs 维护已打开的加密笔记本独立 db 连接,按 boxID 索引。
// UnlockBox 时打开并注册,LockBox/Unmount 时关闭并移除。
encryptedDBs = &sync.Map{} // boxID -> *sql.DB
+
+ // IsEncryptedBoxFn 由 model 层注入,用于判断 boxID 是否为加密笔记本。
+ // sql 包不直接 import model(循环依赖),路由函数据此 fail-closed:
+ // 加密 box 未解锁时绝不回退全局库,避免加密 box 索引污染全局明文库。
+ IsEncryptedBoxFn func(boxID string) bool
)
func init() {
@@ -1428,6 +1433,7 @@ func query(query string, args ...any) (*sql.Rows, error) {
}
// queryRowForBox 按 box 路由查询单行。加密 box 用独立 db,否则用全局 db。boxID 为空走全局。
+// 加密 box 未解锁(db 未打开)时返回 nil——绝不回退全局库,避免加密 box 查询命中全局明文库。
func queryRowForBox(boxID, query string, args ...any) *sql.Row {
query = strings.TrimSpace(query)
if "" == query {
@@ -1437,6 +1443,10 @@ func queryRowForBox(boxID, query string, args ...any) *sql.Row {
if boxDB := GetEncryptedDB(boxID); boxDB != nil {
return boxDB.QueryRow(query, args...)
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) {
+ // 加密 box 未解锁:fail-closed,不回退全局库
+ return nil
+ }
if nil == db {
return nil
}
@@ -1444,6 +1454,7 @@ func queryRowForBox(boxID, query string, args ...any) *sql.Row {
}
// queryForBox 按 box 路由查询多行。加密 box 用独立 db,否则用全局 db。boxID 为空走全局。
+// 加密 box 未解锁时返回错误——绝不回退全局库。
func queryForBox(boxID, query string, args ...any) (*sql.Rows, error) {
query = strings.TrimSpace(query)
if "" == query {
@@ -1452,6 +1463,9 @@ func queryForBox(boxID, query string, args ...any) (*sql.Rows, error) {
if boxDB := GetEncryptedDB(boxID); boxDB != nil {
return boxDB.Query(query, args...)
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) {
+ return nil, errors.New("encrypted box db not opened for box " + boxID)
+ }
if nil == db {
return nil, errors.New("database is nil")
}
@@ -1821,17 +1835,19 @@ func vacuum() {
}
// OpenEncryptedDB 打开加密笔记本的独立 SQLCipher db 并注册到 encryptedDBs。
-// dek 是该 box 的 32 字节数据密钥;DSN 用 SQLCipher 原始 key 格式 x'<hex>',避免 SQLCipher 再做 KDF。
+// dek 是该 box 的 32 字节数据密钥;先用 HKDF 派生 content 子密钥(用途分离),DSN 用 raw key 格式 x'<hex>'。
// 首次打开会建表(幂等 IF NOT EXISTS)。UnlockBox 时调用。
func OpenEncryptedDB(boxID string, dek []byte) (err error) {
if _, loaded := encryptedDBs.Load(boxID); loaded {
return nil // 已打开
}
dbPath := util.EncryptedDBPath(boxID)
+ // 派生 content 子密钥,与 blocktree/assets/file/AV 用途分离
+ contentKey := util.DeriveSubKey(dek, "siyuan/sqlcipher/content")
// SQLCipher DSN:_key=x'<hex>' 让 go-sqlite3 执行 PRAGMA key;其余 PRAGMA 与全局 siyuan.db 对齐
dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
"&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
- "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(dek) + "'"
+ "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(contentKey) + "'"
boxDB, err := sql.Open("sqlite3_extended", dsn)
if err != nil {
return err
@@ -1897,6 +1913,8 @@ func RemoveAllEncryptedDBFiles() {
}
// beginTxForBox 按 box 选 db 开事务。加密 box 用其独立 db,否则用全局 db。
+// beginTxForBox 按 box 选 db 开事务。加密 box 用其独立 db,否则用全局 db。
+// 加密 box 未解锁时返回错误——绝不回退全局库,避免加密 box 的索引写操作污染全局明文库。
func beginTxForBox(box string) (tx *sql.Tx, err error) {
if boxDB := GetEncryptedDB(box); boxDB != nil {
if tx, err = boxDB.Begin(); err != nil {
@@ -1905,6 +1923,10 @@ func beginTxForBox(box string) (tx *sql.Tx, err error) {
}
return
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {
+ // 加密 box 未解锁:fail-closed,不回退全局库
+ return nil, errors.New("encrypted box db not opened for box " + box)
+ }
return beginTx()
}
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index 5fdc304049..0735c91557 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -869,16 +869,23 @@ func vacuum() {
// 加密笔记本的独立 blocktree db 注册表。boxID -> *sql.DB。
var encryptedBlockTreeDBs = &sync.Map{}
+// IsEncryptedBoxFn 由 model 层注入,用于判断 boxID 是否为加密笔记本。
+// treenode 包不直接 import model(循环依赖),路由函数据此 fail-closed:
+// 加密 box 未解锁时绝不回退全局库,避免加密 box 块树元数据污染全局明文 blocktree.db。
+var IsEncryptedBoxFn func(boxID string) bool
+
// OpenEncryptedBlockTreeDB 打开加密笔记本的独立 SQLCipher blocktree db。
-// 与 sql.OpenEncryptedDB 配对,UnlockBox 时调用。dek 为该 box 的 32 字节 DEK。
+// 与 sql.OpenEncryptedDB 配对,UnlockBox 时调用。dek 为该 box 的 32 字节 DEK;
+// 先用 HKDF 派生 blocktree 子密钥(与 content 子密钥分离)。
func OpenEncryptedBlockTreeDB(boxID string, dek []byte) (err error) {
if _, loaded := encryptedBlockTreeDBs.Load(boxID); loaded {
return nil
}
dbPath := util.EncryptedBlockTreeDBPath(boxID)
+ blocktreeKey := util.DeriveSubKey(dek, "siyuan/sqlcipher/blocktree")
dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
"&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
- "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(dek) + "'"
+ "&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(blocktreeKey) + "'"
boxDB, err := sql.Open("sqlite3_extended", dsn)
if err != nil {
return err
@@ -961,11 +968,15 @@ func initEncryptedBlockTreeTables(boxDB *sql.DB) (err error) {
}
// --- box-scoped wrapper(加密 box 用独立 db,否则用全局 db)---
+// 加密 box 未解锁(db 未打开)时 fail-closed:绝不回退全局库,避免加密 box 块树操作污染全局 blocktree.db。
func queryForBox(box, stmt string, args ...any) (*sql.Rows, error) {
if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
return boxDB.Query(stmt, args...)
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {
+ return nil, errors.New("encrypted blocktree db not opened for box " + box)
+ }
return query(stmt, args...)
}
@@ -973,6 +984,9 @@ func queryRowForBox(box, stmt string, args ...any) *sql.Row {
if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
return boxDB.QueryRow(stmt, args...)
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {
+ return nil
+ }
return queryRow(stmt, args...)
}
@@ -980,6 +994,9 @@ func execForBox(box, stmt string, args ...any) (sql.Result, error) {
if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
return boxDB.Exec(stmt, args...)
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {
+ return nil, errors.New("encrypted blocktree db not opened for box " + box)
+ }
return exec(stmt, args...)
}
@@ -987,6 +1004,9 @@ func beginTxForBox(box string) (tx *sql.Tx, err error) {
if boxDB := getEncryptedBlockTreeDB(box); boxDB != nil {
return boxDB.Begin()
}
+ if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {
+ return nil, errors.New("encrypted blocktree db not opened for box " + box)
+ }
return db.Begin()
}
diff --git a/kernel/util/kdf.go b/kernel/util/kdf.go
index 5b2f272b97..11254b8102 100644
--- a/kernel/util/kdf.go
+++ b/kernel/util/kdf.go
@@ -20,9 +20,12 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
+ "crypto/sha256"
"errors"
+ "io"
"golang.org/x/crypto/argon2"
+ "golang.org/x/crypto/hkdf"
)
// Argon2Params 是 Argon2id 密钥派生函数的参数。参数本身不是秘密,会随配置落盘,以便跨平台一致地派生密钥。
@@ -92,6 +95,64 @@ func Decrypt(key, ciphertext []byte) ([]byte, error) {
return gcm.Open(nil, nonce, ct, nil)
}
+// DeriveSubKey 用 HKDF-SHA256 从主 DEK 派生用途隔离的子密钥。
+// 同一 (dek, purpose) 多次调用结果一致;不同 purpose 派生出相互独立的子密钥,
+// 实现用途分离——.sy/assets/AV 各用独立子密钥,互不可替代,限制单点密钥泄漏的影响面。
+func DeriveSubKey(dek []byte, purpose string) []byte {
+ // HKDF info 用 purpose 字节;salt 为 nil(DEK 本身已是高熵随机密钥,无需额外 salt)
+ r := hkdf.New(sha256.New, dek, nil, []byte(purpose))
+ out := make([]byte, 32) // AES-256
+ if _, err := io.ReadFull(r, out); err != nil {
+ // hkdf.Read 不应出错(除非 dek 为空);防御性 panic 避免静默返回弱密钥
+ panic("hkdf derive failed: " + err.Error())
+ }
+ return out
+}
+
+// EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD(附加认证数据)。
+// AAD 不被加密,但参与 GCM 认证——解密时必须提供相同 AAD,否则认证失败。
+// 把用途/boxID/路径等元数据放入 AAD,可防止同 box 内密文被替换用途或路径(bind 到上下文)。
+// 返回格式:nonce(12B) || ciphertext || GCM tag(16B),与 Encrypt 一致但 AAD 参与校验。
+func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error) {
+ if len(key) != 32 {
+ return nil, errors.New("EncryptWithAAD requires a 32-byte (AES-256) key")
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+ gcm, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+ nonce := make([]byte, gcm.NonceSize())
+ if _, err := rand.Read(nonce); err != nil {
+ return nil, err
+ }
+ return gcm.Seal(nonce, nonce, plaintext, aad), nil
+}
+
+// DecryptWithAAD 对应 EncryptWithAAD 的解密,AAD 不匹配或密文被篡改时返回错误。
+func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {
+ if len(key) != 32 {
+ return nil, errors.New("DecryptWithAAD requires a 32-byte (AES-256) key")
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+ gcm, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+ nonceSize := gcm.NonceSize()
+ if len(ciphertext) < nonceSize {
+ return nil, errors.New("ciphertext too short")
+ }
+ nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
+ return gcm.Open(nil, nonce, ct, aad)
+}
+
// GenerateSalt 生成随机 salt(16 字节)。
func GenerateSalt() ([]byte, error) {
return randomBytes(16)