Skip to content

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

:lock: Harden encrypted notebook recovery and reference isolation #18034

Daniel8c5741e8967d
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index 128096ad71..1e62eb3126 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -347,7 +347,7 @@ The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and ba
## 20. Backup, Recovery, and Metadata Policy
-`notebook-crypto-backup.json` is recovery material, not a secret, but its integrity and freshness must be handled separately. It contains a format version, backup ID, creation time, and content digest. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.
+`notebook-crypto-backup.json` is recovery material, not a secret, but its integrity and freshness must be handled separately. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. The current format requires the HMAC: after the master password derives the KEK, a missing or mismatched HMAC rejects recovery instead of being treated as a compatibility fallback. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.
Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Before the master password is entered, trustworthy authentication based on the KEK cannot be established; the system can validate structure and the verifier after unlock only. A successful sync restore must not be presented as proof that the source is trusted. Users should keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable.
@@ -355,7 +355,8 @@ Sync endpoints and offline backups are storage that may be lost, copied, or roll
|---|---|
| Document body, attribute values, original asset names, database cells, index text | No |
| boxID, directory structure, file count, ciphertext size, modification time, asset extension, block-ID time information | Yes |
-| Notebook name, icon, sorting, document title/count, relation count, tags, bookmarks, history and snapshot names | Must not be exposed while locked by default; if compatibility requires exposure, list each field here and explain it in the UI |
+| Notebook name | Yes. The notebook list and encrypted-notebook status API retain the name while locked so users can identify the notebook they intend to unlock; the name is therefore outside the confidentiality boundary |
+| Icon, sorting, document title/count, relation count, tags, bookmarks, history and snapshot names | Must not be exposed while locked by default; if compatibility requires exposure, list each field here and explain it in the UI |
## 21. Feature Boundaries, Plaintext Temporaries, and Interface Rules
@@ -369,13 +370,13 @@ Exports have two classes: a user-selected external destination may contain plain
| Scenario | Expected result |
|---|---|
-| Access while locked through UI, HTTP, file APIs, CLI, MCP, WebDAV, plugins, and background tasks | Cannot read, write, copy, delete, or enumerate encrypted content; returns no plaintext, ciphertext, or title-inferable error |
+| Access while locked through UI, HTTP, file APIs, CLI, MCP, WebDAV, plugins, and background tasks | Other than the explicitly exposed notebook name, cannot read, write, copy, delete, or enumerate encrypted content; returns no plaintext, ciphertext, or document-title-inferable error |
| Unlock, lock, application restart, and authentication failure | DEK and database connections exist only in `Unlocked`; no plaintext cache or usable handle remains after failure or restart |
| Lock concurrent with export, preview, sync, indexing, or history restore | No plaintext task continues after lock; controlled temporary files and access tokens are removed or invalidated |
| Refs, moves, mirrors, assets, and database operations between an encrypted box and a normal box or another encrypted box | Island boundaries hold; rejection creates no partial files, global indexes, or relation data |
| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, logs, and temporary directories | No readable body, asset contents, original asset names, or plaintext SQLite pages in kernel-managed locations |
| Ciphertext tampering, path substitution, nonce reuse, and backup corruption | Authentication or format validation fails safely; never fall back to a normal path, generate replacement key material, or silently overwrite configuration |
-| Master-password change and migration to a new DEK | WrappedDEKs and backup update atomically; old-password exposure warning is accurate; data and history are verifiably readable before and after migration |
+| Master-password change and KEK rewrapping | WrappedDEKs and backup update atomically; an interrupted update remains pending until the new password authenticates the backup; the old-password exposure warning is accurate; data and history are verifiably readable before and after migration |
## 16. Usage Guide
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 7f64679339..fbfd2642c4 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -347,7 +347,7 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
## 20. 备份、恢复与元数据策略
-`notebook-crypto-backup.json` 是恢复材料而非秘密,但必须处理完整性和新鲜度。文件必须带格式版本、备份 ID、创建时间和内容摘要。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
+`notebook-crypto-backup.json` 是恢复材料而非秘密,但必须处理完整性和新鲜度。文件必须带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC。当前格式强制要求 HMAC:主密码派生 KEK 后,HMAC 缺失或不匹配均拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证,因此“同步恢复成功”不得表述为来源可信;系统只能验证结构和用户解锁后的 verifier。用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。
@@ -355,7 +355,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
|---|---|
| 文档正文、属性值、资源原始名称、数据库单元格、索引文本 | 否 |
| boxID、目录结构、文件数量、密文大小、修改时间、资源扩展名、块 ID 时间信息 | 是 |
-| 笔记本名称、图标、排序、文档标题和数量、关系数量、标签、书签、历史与快照名称 | 锁定时默认不得暴露;若兼容性要求暴露,必须逐项在本表及界面中说明 |
+| 笔记本名称 | 是。笔记本列表与加密笔记本状态 API 在锁定时保留名称,以便用户识别要解锁的笔记本,因此笔记本名称不属于机密性保护边界 |
+| 图标、排序、文档标题和数量、关系数量、标签、书签、历史与快照名称 | 锁定时默认不得暴露;若兼容性要求暴露,必须逐项在本表及界面中说明 |
## 21. 功能边界、临时明文与接口规则
@@ -369,13 +370,13 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
| 场景 | 预期结果 |
|---|---|
-| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断标题的信息 |
+| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 除明确允许暴露的笔记本名称外,不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断文档标题的信息 |
| 解锁、锁定、应用重启和认证失败 | DEK 与数据库连接只在 `Unlocked` 存在;失败和重启后没有明文缓存或可用句柄 |
| 锁定与导出、预览、同步、索引、历史恢复并发 | 无明文任务在锁定后继续执行;受控临时文件及访问令牌被清理或失效 |
| 加密盒与普通盒、两个加密盒之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |
| 文件、资源、数据库、WAL/SHM、历史、快照、日志和临时目录的磁盘检查 | 内核管理范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页 |
| 密文篡改、路径替换、nonce 重复、备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |
-| 改主密码和迁移到新 DEK | WrappedDEK 与备份原子更新;旧密码泄露风险提示正确;迁移前后数据与历史均可验证读取 |
+| 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后保持待完成状态,直到新密码认证备份;旧密码泄露风险提示正确;迁移前后数据与历史均可验证读取 |
## 16. 使用指南
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 4202a2b08c..4f47e30f12 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -201,12 +201,15 @@ func ImportNotebookCryptoBackup(data []byte, password string) error {
if validErr != nil {
return errors.New(Conf.Language(317))
}
+ if nc.Spec != conf.CurrentNotebookCryptoSpec || nc.Checksum == "" || len(nc.KEKMAC) == 0 {
+ return errors.New(Conf.Language(317))
+ }
kek := util.DeriveKey(password, nc.MasterSalt, params)
defer zeroAndClear(kek)
- if nc.Spec >= 1 && nc.Checksum != "" && nc.Checksum != computeBackupChecksum(nc) {
+ if nc.Checksum != computeBackupChecksum(nc) {
return errors.New(Conf.Language(317))
}
- if nc.Spec >= 1 && len(nc.KEKMAC) > 0 && !verifyKEKMAC(nc, kek) {
+ if !verifyKEKMAC(nc, kek) {
return errors.New(Conf.Language(317))
}
decrypted, dErr := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:v1:kek-verifier"))
@@ -488,14 +491,10 @@ func recoverMasterPasswordMigration() {
return // 保留 manifest
}
}
- // 持久化全局 conf + backup,再清除 manifest
+ // 持久化全局 conf。此时没有新密码派生出的 KEK,不能为新备份生成可信 MAC,
+ // 因此保留迁移清单和旧备份,待用户首次输入新密码后校验全部 WrappedDEK,再完成备份切换。
Conf.Save()
- if err = saveNotebookCryptoBackup(nil); err != nil {
- logging.LogErrorf("save notebook crypto backup failed: %s", err)
- return // 保留 manifest
- }
- removeMasterPasswordMigration()
- logging.LogInfof("master password migration recovered successfully")
+ logging.LogInfof("master password migration data recovered, waiting for the new password to authenticate the backup")
} else {
// Phase 2 未完成:清除 manifest,保留旧 verifier + 旧 WrappedDEK,状态一致
removeMasterPasswordMigration()
@@ -655,9 +654,6 @@ func restoreNotebookCryptoConfigFromBackup() {
backup.KDFParams = params
backup.Enabled = true
- // 自动恢复无主密码,无法验证 MAC。清零 KEKMAC 避免 stale MAC 阻断后续密码恢复路径。
- // 首次输入主密码时 tryRestoreNotebookCryptoFromBackupLocked 会重新校验并补全 MAC。
- backup.KEKMAC = nil
Conf.m.Lock()
*Conf.NotebookCrypto = *backup
Conf.m.Unlock()
@@ -685,16 +681,19 @@ func tryRestoreNotebookCryptoFromBackupLocked(password string) (kek []byte, err
decrypted, dErr := util.DecryptWithAAD(kek, backup.KEKVerifier, []byte("siyuan:v1:kek-verifier"))
if dErr != nil || string(decrypted) != string(kekVerifierMagic) {
// 主密码错误(或备份损坏),不能恢复
+ zeroAndClear(kek)
return nil, errors.New(Conf.Language(311))
}
- // Spec>=1 时验证 KEKMAC:用 KEK 校验备份内容未被篡改。
- // len(KEKMAC)==0 时跳过(兼容旧备份/启动回填等无 MAC 写入),与 ImportNotebookCryptoBackup 的门控一致
- if backup.Spec >= 1 && len(backup.KEKMAC) > 0 && !verifyKEKMAC(backup, kek) {
+ // 当前格式的备份必须携带有效 KEKMAC;缺失与不匹配都按篡改处理。
+ if backup.Spec != conf.CurrentNotebookCryptoSpec || backup.Checksum == "" ||
+ len(backup.KEKMAC) == 0 || !verifyKEKMAC(backup, kek) {
+ zeroAndClear(kek)
return nil, errors.New(Conf.Language(316))
}
// 若有加密笔记本,校验 KEK 能解密其 WrappedDEK(防止 salt 不匹配的备份导致数据锁死)
if !verifyKEKAgainstExistingBoxes(kek) {
+ zeroAndClear(kek)
return nil, errors.New(Conf.Language(316)) // 密钥不匹配
}
@@ -718,7 +717,7 @@ func tryRestoreNotebookCryptoFromBackupLocked(password string) (kek []byte, err
// deriveKEK 从主密码派生 KEK 并校验。校验失败返回错误。KEK 仅在函数作用域内有效,调用方负责使用。
func deriveKEK(password string) ([]byte, error) {
Conf.m.RLock()
- nc := Conf.NotebookCrypto
+ nc := *Conf.NotebookCrypto
Conf.m.RUnlock()
if !nc.Enabled {
@@ -743,6 +742,36 @@ func deriveKEK(password string) ([]byte, error) {
if string(decrypted) != string(kekVerifierMagic) {
return nil, errors.New(Conf.Language(311))
}
+
+ // 正常配置必须通过 KEKMAC 认证,不能把“MAC 缺失”当作兼容路径,否则同步端攻击者可删除 MAC、
+ // 重算无密钥 Checksum 后篡改 AutoLockMinutes 等安全配置。
+ mig, migErr := readMasterPasswordMigration()
+ migrationPending := migErr == nil && mig != nil && bytes.Equal(nc.KEKVerifier, mig.NewVerifier)
+ if !migrationPending {
+ backup, backupErr := loadNotebookCryptoBackup()
+ backupMatchesConf := backupErr == nil && backup != nil &&
+ bytes.Equal(backup.MasterSalt, nc.MasterSalt) &&
+ bytes.Equal(backup.KEKVerifier, nc.KEKVerifier) &&
+ backup.KDFParams == nc.KDFParams
+ if !backupMatchesConf || backup.Spec != conf.CurrentNotebookCryptoSpec || backup.Checksum == "" ||
+ len(backup.KEKMAC) == 0 || !verifyKEKMAC(backup, kek) {
+ zeroAndClear(kek)
+ return nil, errors.New(Conf.Language(316))
+ }
+ }
+
+ if migrationPending {
+ // 崩溃恢复后的首次新密码验证:确认所有笔记本都已切换到新 KEK,再生成带认证的全局备份并结束迁移。
+ if !verifyKEKAgainstExistingBoxes(kek) {
+ zeroAndClear(kek)
+ return nil, errMasterPasswordMigrationPending
+ }
+ if err = saveNotebookCryptoBackup(kek); err != nil {
+ zeroAndClear(kek)
+ return nil, fmt.Errorf("%w: %v", errMasterPasswordMigrationPending, err)
+ }
+ removeMasterPasswordMigration()
+ }
return kek, nil
}
@@ -1208,6 +1237,7 @@ func DeepCopyBoxEncryption(src *conf.BoxEncryption) *conf.BoxEncryption {
return nil
}
return &conf.BoxEncryption{
+ Spec: src.Spec,
WrappedDEK: append([]byte(nil), src.WrappedDEK...),
WrapNonce: append([]byte(nil), src.WrapNonce...),
CreatedAt: src.CreatedAt,
@@ -1281,9 +1311,15 @@ func IsBlockRefCrossingBoundary(srcBoxID, defBlockID string) bool {
}
}
if nil == bt {
- return false // def 块不存在(可能是新建块的临时态),不拦
+ // 普通库未命中且锁定的加密 blocktree 不可查询时必须 fail-closed,否则只要知道加密块 ID,
+ // 就能在加密笔记本锁定后把跨边界引用写入全局明文数据库。同一事务树内的新块由调用方单独放行。
+ return normalBoxBlockRefCrossesBoundary(nil)
}
- return IsEncryptedBox(bt.BoxID)
+ return normalBoxBlockRefCrossesBoundary(bt)
+}
+
+func normalBoxBlockRefCrossesBoundary(bt *treenode.BlockTree) bool {
+ return bt == nil || IsEncryptedBox(bt.BoxID)
}
// IsEncryptedAssetPath 判断给定 asset 绝对路径是否属于加密笔记本。
diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.go
index dc69a29505..b66653e58a 100644
--- a/kernel/model/crypto_test.go
+++ b/kernel/model/crypto_test.go
@@ -303,6 +303,100 @@ func TestBackupKEKMACVerification(t *testing.T) {
}
}
+// TestDeriveKEKRejectsTamperedBackupMAC 验证 verifier 正确但备份 MAC 被篡改时仍拒绝派生。
+func TestDeriveKEKRejectsTamperedBackupMAC(t *testing.T) {
+ origDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() { util.DataDir = origDataDir }()
+
+ password := "authenticated-backup-test"
+ salt, _ := util.GenerateSalt()
+ params := util.DefaultArgon2Params()
+ kek := util.DeriveKey(password, salt, params)
+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))
+ nc := conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ Spec: 1,
+ KEKMAC: []byte("tampered"),
+ }
+ prepareBackupForWrite(&nc)
+ nc.KEKMAC = []byte("tampered")
+ backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")
+ if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ backupData, _ := json.Marshal(&nc)
+ if err := os.WriteFile(backupPath, backupData, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ originalConf := Conf
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = &nc
+ defer func() { Conf = originalConf }()
+
+ if derived, err := deriveKEK(password); err == nil {
+ zeroAndClear(derived)
+ t.Fatalf("deriveKEK should reject a backup with an invalid KEKMAC")
+ }
+}
+
+// TestDeriveKEKAllowsLocalAutoLockChange 验证本机修改自动锁定时间不会使已认证的密钥备份失效。
+func TestDeriveKEKAllowsLocalAutoLockChange(t *testing.T) {
+ origDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() { util.DataDir = origDataDir }()
+
+ password := "local-auto-lock-test"
+ salt, _ := util.GenerateSalt()
+ params := util.DefaultArgon2Params()
+ kek := util.DeriveKey(password, salt, params)
+ defer zeroAndClear(kek)
+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:v1:kek-verifier"))
+ backup := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ AutoLockMinutes: 5,
+ }
+ if err := writeNotebookCryptoBackupData(backup, kek); err != nil {
+ t.Fatal(err)
+ }
+
+ local := *backup
+ local.AutoLockMinutes = 30
+ originalConf := Conf
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = &local
+ defer func() { Conf = originalConf }()
+
+ derived, err := deriveKEK(password)
+ if err != nil {
+ t.Fatalf("deriveKEK rejected a local AutoLockMinutes change: %v", err)
+ }
+ zeroAndClear(derived)
+}
+
+// TestDeepCopyBoxEncryptionPreservesSpec 验证保存笔记本配置前的深拷贝不会丢失包络版本。
+func TestDeepCopyBoxEncryptionPreservesSpec(t *testing.T) {
+ src := &conf.BoxEncryption{Spec: 1, WrappedDEK: []byte{1, 2}, WrapNonce: []byte{3, 4}, CreatedAt: 5}
+ got := DeepCopyBoxEncryption(src)
+ if got.Spec != src.Spec {
+ t.Fatalf("BoxEncryption.Spec changed during deep copy: got %d want %d", got.Spec, src.Spec)
+ }
+}
+
+// TestUnknownBlockRefFailsClosed 验证普通库无法定位定义块时按跨边界处理,防止锁定加密块 ID 被写入全局库。
+func TestUnknownBlockRefFailsClosed(t *testing.T) {
+ if !normalBoxBlockRefCrossesBoundary(nil) {
+ t.Fatalf("an unresolved block reference should fail closed")
+ }
+}
+
// TestBackupMACRoundTrip 验证 writeNotebookCryptoBackupData(nc, kek) 写入的备份,
// 重新加载后 verifyKEKMAC 能通过——即 MAC 在 prepareBackupForWrite 之后计算(顺序正确)。
func TestBackupMACRoundTrip(t *testing.T) {
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index a4a331b14c..f4af2846ed 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -1731,12 +1731,22 @@ func getRefDefIDs(node *ast.Node) (refDefIDs []string) {
// 返回被降级的引用数。
func degradeCrossBoundaryBlockRefs(root *ast.Node, srcBox string) int {
degraded := 0
+ localBlockIDs := map[string]struct{}{}
+ ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n.IsBlock() && n.ID != "" {
+ localBlockIDs[n.ID] = struct{}{}
+ }
+ return ast.WalkContinue
+ })
ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if ast.NodeTextMark == n.Type && n.IsTextMarkType("block-ref") {
+ if _, local := localBlockIDs[n.TextMarkBlockRefID]; local {
+ return ast.WalkContinue
+ }
if IsBlockRefCrossingBoundary(srcBox, n.TextMarkBlockRefID) {
logging.LogWarnf("block ref crosses encrypted boundary, src box [%s] -> def block [%s], degrade to text", srcBox, n.TextMarkBlockRefID)
n.TextMarkBlockRefID = ""