An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Reject Windows device namespace paths in sensitive path checks
Daniel24dab3654671
diff --git a/kernel/util/path.go b/kernel/util/path.goindex c68477fd43..7be09a8647 100644--- a/kernel/util/path.go+++ b/kernel/util/path.go@@ -482,11 +482,21 @@ func IsSensitiveHTMLAssetPath(p string) bool {return isSensitivePath(p, true) || isSensitivePath(ResolveLongestExistingParent(p), true)}+// deviceNamespacePath 标记无法归一化的设备命名空间路径。+//+// 这类路径只能由内核对象管理器解析,无法转换为常规 Win32 路径参与黑名单匹配,因此一律按敏感路径处理(fail-closed)。+// 该值不是合法 Windows 路径的形态,故按字面量比较即可,无需解析。+const deviceNamespacePath = "<device-namespace>"+// resolveNamespaceAlias 把 Windows 路径命名空间别名归一化为常规 Win32 路径,供黑名单匹配与工作空间归属判断使用。//// 扩展长度前缀 `\\?\`(含 `\\?\UNC\`)与设备命名空间前缀 `\\.\` 经 filepath.Clean 后原样保留,// 既无法命中按前缀比较的黑名单,也会被文件系统归属判断当作工作空间外的路径,从而绕过敏感路径保护。// 本机管理共享(`\\localhost\<盘符>$\...` 或 `\\<本机主机名>\<盘符>$\...`)指向本地卷,同样归一化为盘符路径。+//+// 设备命名空间(`\\?\GLOBALROOT\Device\HarddiskVolumeN\...` 等)只能由内核对象管理器解析,无法用盘符表达,+// 故不尝试映射为卷路径,而是返回 deviceNamespacePath 由调用方按敏感路径拒绝。匹配在剥离 `\\?\`、`\\.\` 之后进行,+// 因此正斜杠写法(`//?/GLOBALROOT/...`)经 filepath.Clean 归一化后同样被识别。func resolveNamespaceAlias(p string) string {if runtime.GOOS != "windows" || p == "" {return p@@ -499,11 +509,19 @@ func resolveNamespaceAlias(p string) string {break}}+ // 剥离前缀后设备命名空间只剩 `GLOBALROOT\...`、`Device\...`、`Volume{...}` 形态+ if isDeviceNamespacePath(p) {+ return deviceNamespacePath+ }if strings.HasPrefix(p, `UNC\`) {p = `\\` + p[len(`UNC\`):]}cleaned := filepath.Clean(p)+ // 正斜杠写法(`//?/GLOBALROOT/...`)未命中上面的字面量前缀,但经 filepath.Clean 会归一化为 `\\?\GLOBALROOT\...`,故再判定一次+ if isDeviceNamespacePath(cleaned) {+ return deviceNamespacePath+ }if strings.HasPrefix(cleaned, `\\`) {// 仅当主机名是本机且共享名就是盘符时才等价于本地卷,其余 UNC 路径一律按常规路径匹配黑名单if drive, prefixLen := localAdminShareDrive(cleaned); drive != "" {@@ -550,6 +568,36 @@ func isASCIILetter(b byte) bool {return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z'}+// hasAnyPrefixFold 判断 p 是否以任一前缀开头,忽略大小写。+//+// Windows 的路径与设备命名空间组件都不区分大小写,故前缀比较必须忽略大小写,否则 `GLOBALROOT` 的小写写法仍会漏过。+func hasAnyPrefixFold(p string, prefixes ...string) bool {+ for _, prefix := range prefixes {+ if len(p) >= len(prefix) && strings.EqualFold(p[:len(prefix)], prefix) {+ return true+ }+ }+ return false+}++// deviceNamespacePrefixes 是设备命名空间路径的起始形态:`GLOBALROOT\Device\...`、`\Device\...` 与卷 GUID 写法。+var deviceNamespacePrefixes = []string{+ `GLOBALROOT\Device\`,+ `GLOBALROOT\Volume{`,+ `Device\`,+ `Volume{`,+}++// isDeviceNamespacePath 判断路径是否为设备命名空间形式(如 `GLOBALROOT\Device\HarddiskVolumeN\...`)。+//+// 这类路径无盘符等价形式,无法参与黑名单前缀匹配,故一律按敏感路径拒绝(fail-closed)。+// 调用点传入的是剥离 `\\?\`、`\\.\` 之后的路径或 filepath.Clean 结果,故同时接受带前导反斜杠与命名空间前缀的写法。+func isDeviceNamespacePath(p string) bool {+ return hasAnyPrefixFold(p, deviceNamespacePrefixes...) ||+ hasAnyPrefixFold(p, `\\?\GLOBALROOT\`, `\\.\GLOBALROOT\`, `\\?\Device\`, `\\.\Device\`,+ `\\?\Volume{`, `\\.\Volume{`)+}+func isHTMLAssetUserPath(p string) bool {for _, root := range []string{os.TempDir(), HomeDir, systemHomeDir} {if root == "" {@@ -602,6 +650,9 @@ func isSystemTempPath(lowerPath string) bool {// isSensitivePath 执行敏感性黑名单匹配,必要时解析工作空间路径,但不解析目标路径。func isSensitivePath(p string, htmlAsset bool) bool {p = resolveNamespaceAlias(p)+ if p == deviceNamespacePath {+ return true+ }toCheckPathLower := filepath.Clean(strings.ToLower(p))toCheckNameLower := filepath.Base(toCheckPathLower)workspaceDir := WorkspaceDirdiff --git a/kernel/util/path_device_namespace_windows_test.go b/kernel/util/path_device_namespace_windows_test.gonew file mode 100644index 0000000000..cf309fc2be--- /dev/null+++ b/kernel/util/path_device_namespace_windows_test.go@@ -0,0 +1,119 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++//go:build windows++package util++import (+ "os"+ "path/filepath"+ "strings"+ "syscall"+ "testing"+ "unsafe"+)++// 本文件动态校验设备命名空间别名绕过敏感路径黑名单的问题(GHSA-gg3p-r4g8-vxg2)。+// 卷的 `\Device\HarddiskVolumeN` 编号随机器与接入顺序变化,无法写死,故通过 QueryDosDevice 动态推导,+// 确保 `\\?\GLOBALROOT\Device\HarddiskVolumeN\...` 与常规盘符路径被判定为同一位置。++// TestDeviceNamespaceAliasRejected 用真实卷设备路径构造 GLOBALROOT 别名,校验其仍被拒绝,+// 并确认该别名确实指向工作空间内的真实文件,即拒绝不是因为路径不存在。+func TestDeviceNamespaceAliasRejected(t *testing.T) {+ originalHome, originalWorkspace := HomeDir, WorkspaceDir+ workspace := t.TempDir()+ HomeDir, WorkspaceDir = t.TempDir(), workspace+ t.Cleanup(func() { HomeDir, WorkspaceDir = originalHome, originalWorkspace })++ confDir := filepath.Join(WorkspaceDir, "conf")+ if err := os.MkdirAll(confDir, 0755); err != nil {+ t.Fatal(err)+ }+ confPath := filepath.Join(confDir, "conf.json")+ if err := os.WriteFile(confPath, []byte("fixture"), 0600); err != nil {+ t.Fatal(err)+ }++ drive := filepath.VolumeName(confPath)+ aliasBase := globalRootVolumePath(t, drive)+ name := strings.TrimPrefix(confPath, drive)+ for _, test := range []struct {+ name string+ path string+ }{+ {"扩展长度 GLOBALROOT", `\\?\` + aliasBase + name},+ {"设备命名空间 GLOBALROOT", `\\.\` + aliasBase + name},+ {"小写 GLOBALROOT", `\\?\` + strings.ToLower(aliasBase) + name},+ {"卷影副本形态", `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\conf\conf.json`},+ } {+ t.Run(test.name, func(t *testing.T) {+ if !IsSensitivePath(test.path) {+ t.Errorf("IsSensitivePath(%q) = false, want true (device namespace bypass)", test.path)+ }+ })+ }++ // 常规路径的敏感判定不能因本次改动而失效+ if !IsSensitivePath(confPath) {+ t.Errorf("IsSensitivePath(%q) = false, want true", confPath)+ }++ // 同一卷的常规盘符路径不受设备命名空间规则影响,否则会阻断工作空间内的合法读写+ if IsSensitivePath(filepath.Join(WorkspaceDir, "data", "assets", "image.png")) {+ t.Errorf("workspace asset path is treated as sensitive")+ }++ // 别名确实指向该文件,说明拒绝不是路径不存在导致的+ f, err := os.Open(`\\?\` + aliasBase + name)+ if err != nil {+ t.Logf("real volume device path is not openable here: %v", err)+ return+ }+ f.Close()+}++// globalRootVolumePath 返回形如 `GLOBALROOT\Device\HarddiskVolume3\` 的卷设备路径前缀。+func globalRootVolumePath(t *testing.T, drive string) string {+ t.Helper()++ volume, err := queryDosDevice(drive)+ if err != nil {+ t.Skipf("query dos device %q failed: %v", drive, err)+ }+ if !strings.HasPrefix(volume, `\Device\`) {+ t.Skipf("unexpected dos device path %q", volume)+ }++ return `GLOBALROOT` + volume + `\`+}++// queryDosDevice 返回盘符(如 `D:`)对应的设备路径(如 `\Device\HarddiskVolume3`)。+func queryDosDevice(drive string) (string, error) {+ kernel32 := syscall.NewLazyDLL("kernel32.dll")+ proc := kernel32.NewProc("QueryDosDeviceW")++ drivePtr, err := syscall.UTF16PtrFromString(drive)+ if err != nil {+ return "", err+ }+ buf := make([]uint16, 1024)+ count, _, callErr := proc.Call(uintptr(unsafe.Pointer(drivePtr)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))+ if count == 0 {+ return "", callErr+ }+ return syscall.UTF16ToString(buf), nil+}diff --git a/kernel/util/path_namespace_test.go b/kernel/util/path_namespace_test.goindex b996d4459a..b233f9c137 100644--- a/kernel/util/path_namespace_test.go+++ b/kernel/util/path_namespace_test.go@@ -88,6 +88,21 @@ func TestIsSensitivePathNamespaceAlias(t *testing.T) {{"扩展长度 UNC 本机管理共享的 conf 目录", `\\?\UNC\localhost\` + strings.ToUpper(drive[:1]) + "$" + confDir[len(drive):]},{"UNC 本机管理共享的 conf 目录", `\\localhost\` + strings.ToUpper(drive[:1]) + "$" + confDir[len(drive):]},}+ // GLOBALROOT 与卷 GUID 指向同一位置,但只能由内核对象管理器解析,无法归一化为盘符路径+ // (GHSA-gg3p-r4g8-vxg2),必须与常规路径一样按敏感路径拒绝,不能以任一种拼写放行+ deviceNamespaces := []string{+ `\\?\GLOBALROOT\Device\HarddiskVolume1`,+ `\\.\GLOBALROOT\Device\HarddiskVolume1`,+ `//?/GLOBALROOT/Device/HarddiskVolume1`,+ `\\?\globalroot\device\harddiskvolume1`,+ `\\.\GLOBALROOT\Device\HarddiskVolumeShadowCopy1`,+ `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy4`,+ `\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}`,+ `\\.\Device\HarddiskVolume1`,+ }+ for _, ns := range deviceNamespaces {+ variants = append(variants, pathVariant{ns, ns + confDir[len(drive):]})+ }if hostname, err := os.Hostname(); err == nil && "" != hostname {variants = append(variants, pathVariant{"UNC 本机主机名管理共享的 conf 目录", `\\` + hostname + `\` + strings.ToUpper(drive[:1]) + "$" + confDir[len(drive):]})} else {@@ -107,6 +122,16 @@ func TestIsSensitivePathNamespaceAlias(t *testing.T) {t.Errorf("IsSensitivePath(%q) = true, want false (workspace root)", p)}}++ // 设备命名空间无盘符等价形式,无法判断归属,故工作空间路径同样按 fail-closed 拒绝+ for _, p := range []string{+ `\\?\GLOBALROOT\Device\HarddiskVolume1` + WorkspaceDir[len(drive):],+ `\\?\GLOBALROOT\Device\HarddiskVolume1` + filepath.Join(WorkspaceDir, "data", "assets", "image.png")[len(drive):],+ } {+ if !IsSensitivePath(p) {+ t.Errorf("IsSensitivePath(%q) = false, want true (device namespace must fail closed)", p)+ }+ }}// TestResolveNamespaceAlias 校验命名空间别名归一化的具体结果。@@ -131,6 +156,14 @@ func TestResolveNamespaceAlias(t *testing.T) {{"远程共享保持 UNC 形式", `\\server\share\ws`, `\\server\share\ws`},{"非盘符共享不映射", `\\localhost\data\ws`, `\\localhost\data\ws`},{"普通路径不变", `D:\ws\conf`, `D:\ws\conf`},+ {"GLOBALROOT 设备命名空间不可归一化", `\\?\GLOBALROOT\Device\HarddiskVolume3\ws\conf`, deviceNamespacePath},+ {"设备命名空间 GLOBALROOT 不可归一化", `\\.\GLOBALROOT\Device\HarddiskVolume3\ws\conf`, deviceNamespacePath},+ {"正斜杠 GLOBALROOT 不可归一化", `//?/GLOBALROOT/Device/HarddiskVolume3/ws/conf`, deviceNamespacePath},+ {"小写 GLOBALROOT 不可归一化", `\\?\globalroot\device\harddiskvolume3\ws\conf`, deviceNamespacePath},+ {"卷影副本不可归一化", `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\ws\conf`, deviceNamespacePath},+ {"设备对象路径不可归一化", `\\.\Device\HarddiskVolume3\ws\conf`, deviceNamespacePath},+ {"卷 GUID 不可归一化", `\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\ws\conf`, deviceNamespacePath},+ {"UNC 仍正常归一化", `\\?\UNC\localhost\D$\ws\conf`, `D:\ws\conf`},} {t.Run(test.name, func(t *testing.T) {if got := resolveNamespaceAlias(test.in); !strings.EqualFold(got, test.want) {