Skip to content

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

:lock: Harden encrypted export paths #18034

Daniel5169c2f38265
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index da6c94347b..6ead1c6965 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -90,13 +90,17 @@ func listDocTree(c *gin.Context) {
p := arg["path"].(string)
p = strings.TrimSuffix(p, ".sy")
- // 越界校验:拒绝 ..,确保路径位于 <data>/<notebook>/ 内。
- // 无需 filepath.IsAbs —— notebook 路径全为 notebook 内相对路径,且跨 OS 对 "/" 判定不一致。
+ // 越界校验:拒绝 .. 和绝对路径,确保路径位于 <data>/<notebook>/ 内。
if idx := strings.Index(p, ".."); idx >= 0 {
ret.Code = -1
ret.Msg = "path must not contain '..'"
return
}
+ if filepath.IsAbs(p) && p != "/" {
+ ret.Code = -1
+ ret.Msg = "path must be relative"
+ return
+ }
var doctree []*DocFile
root := filepath.Join(util.WorkspaceDir, "data", notebook, p)
if !gulu.File.IsSubPath(filepath.Join(util.WorkspaceDir, "data", notebook), root) {
@@ -1102,8 +1106,8 @@ func listDocsByPath(c *gin.Context) {
notebook := arg["notebook"].(string)
p := arg["path"].(string)
- // 越界校验:拒绝 ..,确保路径位于 <data>/<notebook>/ 内
- if strings.Contains(p, "..") {
+ // 越界校验:拒绝 .. 和绝对路径,防止跨 box 遍历
+ if strings.Contains(p, "..") || (filepath.IsAbs(p) && p != "/") {
ret.Code = -1
ret.Msg = "path must not contain '..' and must be relative"
return
diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.go
index 6cdb89f80b..c1cd63a2a9 100644
--- a/kernel/model/encrypted_export_test.go
+++ b/kernel/model/encrypted_export_test.go
@@ -24,3 +24,36 @@ func TestManagedEncryptedExportRevocation(t *testing.T) {
t.Fatal("revoked managed export remained downloadable")
}
}
+
+func TestCopyExportResourceDirectory(t *testing.T) {
+ source := filepath.Join(t.TempDir(), "assets")
+ nested := filepath.Join(source, "nested")
+ if err := os.MkdirAll(nested, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(nested, "resource.txt"), []byte("content"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ destination := filepath.Join(t.TempDir(), "export")
+ if err := copyExportResource(source, destination); err != nil {
+ t.Fatal(err)
+ }
+ content, err := os.ReadFile(filepath.Join(destination, "nested", "resource.txt"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(content) != "content" {
+ t.Fatalf("unexpected copied content: %q", content)
+ }
+}
+
+func TestUniqueExportFilePath(t *testing.T) {
+ destination := filepath.Join(t.TempDir(), "resource.txt")
+ if err := os.WriteFile(destination, []byte("first"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if actual := uniqueExportFilePath(destination); actual != filepath.Join(filepath.Dir(destination), "resource (2).txt") {
+ t.Fatalf("unexpected unique export path: %s", actual)
+ }
+}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 415e2bb3c8..0b27187a9a 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -23,6 +23,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io/fs"
"maps"
"net/http"
"net/url"
@@ -736,6 +737,7 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
os.RemoveAll(exportFolderPath)
if err != nil {
os.Remove(zipFilePath)
+ os.Remove(zipFilePath + ".partial")
}
}()
@@ -750,26 +752,40 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
resourceBaseName := filepath.Base(resourceFullPath) // 资源名称
resourceCopyPath := filepath.Join(exportFolderPath, resourceBaseName) // 资源副本完整路径
- if err = copyAssetDecryptIfEncrypted(resourceFullPath, resourceCopyPath); err != nil {
+ if err = copyExportResource(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())
return
}
}
- zip, err := gulu.Zip.Create(zipFilePath)
+ zipPartialPath := zipFilePath + ".partial"
+ zip, err := gulu.Zip.Create(zipPartialPath)
if err != nil {
logging.LogErrorf("create export zip [%s] failed: %s", zipFilePath, err)
return
}
+ zipClosed := false
+ defer func() {
+ if !zipClosed {
+ _ = zip.Close()
+ }
+ }()
if err = zip.AddDirectory(zipBaseName, exportFolderPath); err != nil {
logging.LogErrorf("create export zip [%s] failed: %s", exportFolderPath, err)
return
}
- if err = zip.Close(); err != nil {
+ err = zip.Close()
+ zipClosed = true
+ if err != nil {
logging.LogErrorf("close export zip failed: %s", err)
+ return
+ }
+ if err = os.Rename(zipPartialPath, zipFilePath); err != nil {
+ logging.LogErrorf("publish export zip [%s] failed: %s", zipFilePath, err)
+ return
}
exportFilePath = path.Join("temp", "export")
@@ -781,6 +797,74 @@ func ExportResources(resourcePaths []string, mainName string) (exportFilePath st
return
}
+// copyExportResource 复制导出资源,目录逐文件处理以避免将加密资源作为普通文件读取。
+func copyExportResource(source, destination string) error {
+ info, err := os.Lstat(source)
+ if err != nil {
+ return err
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ return errors.New("exporting symbolic links is not supported")
+ }
+ if !info.IsDir() {
+ return copyExportFile(source, destination)
+ }
+
+ return filepath.WalkDir(source, func(current string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ return errors.New("exporting symbolic links is not supported")
+ }
+ relativePath, relErr := filepath.Rel(source, current)
+ if relErr != nil {
+ return relErr
+ }
+ target := filepath.Join(destination, relativePath)
+ if entry.IsDir() {
+ return os.MkdirAll(target, 0755)
+ }
+ if !entry.Type().IsRegular() {
+ return errors.New("exporting special files is not supported")
+ }
+ return copyExportFile(current, target)
+ })
+}
+
+// copyExportFile 复制单个导出文件,并在加密资源存在名称映射时恢复用户可见名称。
+func copyExportFile(source, destination string) error {
+ boxID := ExtractBoxIDFromAssetsPath(source)
+ if boxID != "" && IsEncryptedBox(boxID) {
+ diskName := filepath.Base(source)
+ if diskName == ".names.json" {
+ return nil
+ }
+ if originalName := LookupAssetOriginalName(boxID, diskName); originalName != "" {
+ fileName := util.FilterFileName(filepath.Base(originalName))
+ if fileName != "" && fileName != "." {
+ destination = uniqueExportFilePath(filepath.Join(filepath.Dir(destination), fileName))
+ }
+ }
+ }
+ return copyAssetDecryptIfEncrypted(source, destination)
+}
+
+// uniqueExportFilePath 在同一导出目录中为同名文件生成稳定的序号后缀。
+func uniqueExportFilePath(destination string) string {
+ if _, err := os.Lstat(destination); err != nil {
+ return destination
+ }
+ extension := filepath.Ext(destination)
+ base := strings.TrimSuffix(destination, extension)
+ for index := 2; ; index++ {
+ candidate := fmt.Sprintf("%s (%d)%s", base, index, extension)
+ if _, err := os.Lstat(candidate); err != nil {
+ return candidate
+ }
+ }
+}
+
// exportResourcesEncryptedBox 校验资源导出是否跨越加密边界,并返回唯一允许的加密来源 boxID。
func exportResourcesEncryptedBox(resourcePaths []string) (encryptedBoxID string, err error) {
hasNormalResource := false
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index b5d75e9e3e..5d2be7bdce 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -698,7 +698,7 @@ func serveAssets(ginServer *gin.Engine) {
}
// 硬边界:拒绝路径遍历
- if strings.Contains(requestPath, "..") {
+ if strings.Contains(requestPath, "..") || filepath.IsAbs(requestPath) {
context.Status(http.StatusForbidden)
return
}