Skip to content

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

:lock: Fix cross-boundary transaction, orphan db, export guard, and import password verification https://github.com/siyuan-note/siyuan/issues/18034

Danielda655de71c7f
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index 1e3252918f..bda31ed78f 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -408,19 +408,46 @@ const mountEncryptedNotebook = (root: HTMLElement) => {
if (!file) {
return;
}
- const formData = new FormData();
- formData.append("file", file);
- fetch("/api/notebook/importNotebookCryptoBackup", {
- method: "POST",
- body: formData,
- }).then((res) => res.json()).then((response: IWebSocketData) => {
- if (response.code === -1) {
- showMessage(response.msg, 6000, "error");
+ // 导入前需输入主密码校验(备份文件不含密码,校验用导入备份对应的主密码)
+ const passwordDialog = new Dialog({
+ title: window.siyuan.languages.masterPassword,
+ content: `<div class="b3-dialog__content">
+ <input type="password" placeholder="${window.siyuan.languages.masterPassword}" class="b3-text-field fn__block">
+</div>
+<div class="b3-dialog__action">
+ <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button>
+ <div class="fn__space"></div>
+ <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
+</div>`,
+ width: "520px",
+ });
+ const pwdInput = passwordDialog.element.querySelector(".b3-text-field") as HTMLInputElement;
+ passwordDialog.element.querySelector(".b3-button--cancel")?.addEventListener("click", () => {
+ passwordDialog.close();
+ });
+ passwordDialog.element.querySelector(".b3-button--text")?.addEventListener("click", () => {
+ const password = pwdInput.value.trim();
+ if (!password) {
+ showMessage(window.siyuan.languages.masterPassword);
return;
}
- showMessage(window.siyuan.languages.importNotebookCryptoBackupTip);
- refresh();
+ const formData = new FormData();
+ formData.append("file", file);
+ formData.append("password", password);
+ fetch("/api/notebook/importNotebookCryptoBackup", {
+ method: "POST",
+ body: formData,
+ }).then((res) => res.json()).then((response: IWebSocketData) => {
+ if (response.code === -1) {
+ showMessage(response.msg, 6000, "error");
+ return;
+ }
+ showMessage(window.siyuan.languages.importNotebookCryptoBackupTip);
+ passwordDialog.close();
+ refresh();
+ });
});
+ pwdInput.focus();
};
fileInput.click();
});
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index 6aa782c371..c8a35687ce 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -686,7 +686,11 @@ func importNotebookCryptoBackup(c *gin.Context) {
ret.Msg = err.Error()
return
}
- if err := model.ImportNotebookCryptoBackup(data); err != nil {
+ password := ""
+ if vals := form.Value["password"]; len(vals) > 0 {
+ password = vals[0]
+ }
+ if err := model.ImportNotebookCryptoBackup(data, password); err != nil {
ret.Code = -1
ret.Msg = err.Error()
return
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 33f6368c5c..06472ef8d7 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -83,7 +83,9 @@ func ExportNotebookCryptoBackup() (downloadPath string, err error) {
// 用于新设备/重装后不依赖同步、手动恢复加密配置(详见设计文档 §4.1)。
// 安全:备份文件不含主密码(salt 不保密、verifier 是密文),导入只恢复配置,解锁仍需主密码。
// 防呆:本机已启用加密笔记本时拒绝导入,避免覆盖现有 salt/verifier 孤立现有 WrappedDEK。
-func ImportNotebookCryptoBackup(data []byte) error {
+// ImportNotebookCryptoBackup 接收用户导入的密钥备份文件内容(JSON 字节)+ 主密码,
+// 校验主密码能解开备份里的 verifier 后才写回配置。防止 crafted 备份设置弱 KDFParams 等攻击。
+func ImportNotebookCryptoBackup(data []byte, password string) error {
nc := &conf.NotebookCrypto{}
if err := json.Unmarshal(data, nc); err != nil {
return errors.New(Conf.Language(317))
@@ -100,6 +102,17 @@ func ImportNotebookCryptoBackup(data []byte) error {
return errors.New(Conf.Language(312))
}
+ // 用导入的 salt + 用户输入的主密码派生 KEK,校验能否解开备份里的 verifier
+ params := nc.KDFParams
+ if params.KeyLength == 0 {
+ params = util.DefaultArgon2Params()
+ }
+ kek := util.DeriveKey(password, nc.MasterSalt, params)
+ decrypted, dErr := util.Decrypt(kek, nc.KEKVerifier)
+ if dErr != nil || string(decrypted) != string(kekVerifierMagic) {
+ return errors.New(Conf.Language(311)) // 主密码错误
+ }
+
nc.Enabled = true
Conf.m.Lock()
*Conf.NotebookCrypto = *nc
@@ -379,7 +392,7 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
return err
}
if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {
- sql.CloseEncryptedDB(boxID)
+ sql.RemoveEncryptedDBFile(boxID) // 清理已创建的 content db 文件,避免遗留空加密库
return err
}
cachedDEKs[boxID] = dek
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 3045c3660d..46a1bb95f3 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -682,6 +682,11 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
resourceBaseName := filepath.Base(resourceFullPath) // 资源名称
resourceCopyPath := filepath.Join(exportFolderPath, resourceBaseName) // 资源副本完整路径
+ // 加密 box 未解锁时拒绝导出(copyAssetDecryptIfEncrypted 锁定时复制密文,这里提前拦截避免产出无效文件)
+ if resBoxID := ExtractBoxIDFromAssetsPath(resourceFullPath); resBoxID != "" && IsEncryptedBox(resBoxID) && !IsBoxUnlocked(resBoxID) {
+ err = errors.New(Conf.Language(314))
+ return
+ }
if err = copyAssetDecryptIfEncrypted(resourceFullPath, resourceCopyPath); err != nil {
logging.LogErrorf("copy resource will be exported from [%s] to [%s] failed: %s", resourcePath, resourceCopyPath, err)
err = fmt.Errorf(Conf.Language(14), err.Error())
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 21531bfa41..825663004d 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -508,6 +508,10 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
if isSameTree {
targetTree = srcTree
}
+ // 禁止跨加密边界移动块:加密笔记本是孤岛,跨 box 移动会破坏隔离(内容从 A 泄漏到 B)
+ if !isSameTree && !IsSameCryptoBoundary(srcTree.Box, targetTree.Box) {
+ return &TxErr{code: TxErrCodeBlockNotFound, id: id, msg: Conf.Language(313)}
+ }
targetNode := treenode.GetNodeInTree(targetTree, targetPreviousID)
if nil == targetNode {
@@ -585,6 +589,10 @@ func (tx *Transaction) doMove(operation *Operation) (ret *TxErr) {
if isSameTree {
targetTree = srcTree
}
+ // 禁止跨加密边界移动块(同 doMove targetPreviousID 分支)
+ if !isSameTree && !IsSameCryptoBoundary(srcTree.Box, targetTree.Box) {
+ return &TxErr{code: TxErrCodeBlockNotFound, id: id, msg: Conf.Language(313)}
+ }
targetNode := treenode.GetNodeInTree(targetTree, targetParentID)
if nil == targetNode {
@@ -925,6 +933,10 @@ func (tx *Transaction) doAppend(operation *Operation) (ret *TxErr) {
if isSameTree {
targetTree = srcTree
}
+ // 禁止跨加密边界插入块(同 doMove 守卫)
+ if !isSameTree && !IsSameCryptoBoundary(srcTree.Box, targetTree.Box) {
+ return &TxErr{code: TxErrCodeBlockNotFound, id: id, msg: Conf.Language(313)}
+ }
targetRoot := targetTree.Root
if nil != targetNewList {