Skip to content

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

:bug: Use native Windows elevation for Defender exclusions https://github.com/siyuan-note/siyuan/issues/20459

Daniel2f1be69fe105
diff --git a/kernel/internal/elevator/elevator.go b/kernel/internal/elevator/elevator.go
deleted file mode 100644
index 2d95ba161a..0000000000
--- a/kernel/internal/elevator/elevator.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// 包 elevator 执行 Windows 提权工具,并等待其返回最终结果。
-package elevator
-
-import (
- "fmt"
- "os/exec"
- "strings"
-
- "github.com/88250/gulu"
-)
-
-func Run(executable, workingDir, arguments string) error {
- script := commandScript(executable, workingDir, arguments)
- cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", script)
- gulu.CmdAttr(cmd)
- output, err := cmd.CombinedOutput()
- if err != nil {
- return fmt.Errorf("elevated helper failed: %w: %s", err, strings.TrimSpace(string(output)))
- }
- return nil
-}
-
-func commandScript(executable, workingDir, arguments string) string {
- // 参数已按 Windows 命令行语法转义,单引号字符串仅负责保留 PowerShell 中的字面值
- return "$ErrorActionPreference = 'Stop'; try { $process = Start-Process -FilePath " + quotePowerShell(executable) +
- " -WorkingDirectory " + quotePowerShell(workingDir) + " -ArgumentList " + quotePowerShell(arguments) +
- " -Verb RunAs -WindowStyle Hidden -Wait -PassThru; " +
- "if ($null -eq $process.ExitCode) { throw 'Elevated helper exit code unavailable' }; " +
- "exit $process.ExitCode } catch { Write-Error $_; exit 1 }"
-}
-
-func quotePowerShell(value string) string {
- return "'" + strings.ReplaceAll(value, "'", "''") + "'"
-}
diff --git a/kernel/internal/elevator/elevator_test.go b/kernel/internal/elevator/elevator_test.go
deleted file mode 100644
index 042ff32cf9..0000000000
--- a/kernel/internal/elevator/elevator_test.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package elevator
-
-import (
- "strings"
- "testing"
-)
-
-func TestElevatedCommandScript(t *testing.T) {
- for value, expected := range map[string]string{
- "": "''", `D:\Program Files\SiYuan`: `'D:\Program Files\SiYuan'`,
- `D:\O'Brien\$notes`: `'D:\O''Brien\$notes'`,
- } {
- if result := quotePowerShell(value); result != expected {
- t.Fatalf("literal changed: %q, expected %q", result, expected)
- }
- }
- script := commandScript(`D:\Program Files\SiYuan\elevator.exe`, `D:\Program Files\SiYuan`, `add-defender-exclusion "D:\Program Files\SiYuan" D:\notes`)
- for _, fragment := range []string{"$ErrorActionPreference = 'Stop'", "-Verb RunAs", "-WindowStyle Hidden", "-Wait -PassThru", "exit $process.ExitCode", "$null -eq $process.ExitCode"} {
- if !strings.Contains(script, fragment) {
- t.Fatalf("missing process requirement %q: %s", fragment, script)
- }
- }
-}
diff --git a/kernel/internal/elevator/elevator_windows.go b/kernel/internal/elevator/elevator_windows.go
new file mode 100644
index 0000000000..e6bf7f80ab
--- /dev/null
+++ b/kernel/internal/elevator/elevator_windows.go
@@ -0,0 +1,119 @@
+// 包 elevator 执行 Windows 提权工具,并等待其返回最终结果。
+package elevator
+
+import (
+ "errors"
+ "fmt"
+ "runtime"
+ "syscall"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+const (
+ seeMaskNoCloseProcess = 0x00000040
+ seeMaskNoAsync = 0x00000100
+ seeMaskFlagNoUI = 0x00000400
+ coInitApartment = 0x2
+ coInitDisableOLE1DDE = 0x4
+)
+
+var shellExecuteEx = windows.NewLazySystemDLL("shell32.dll").NewProc("ShellExecuteExW")
+
+// shellExecuteInfo 按 SHELLEXECUTEINFOW 的字段顺序和平台对齐规则保存原生调用参数。
+type shellExecuteInfo struct {
+ size uint32
+ mask uint32
+ window windows.Handle
+ verb *uint16
+ file *uint16
+ parameters *uint16
+ directory *uint16
+ show int32
+ instance windows.Handle
+ idList unsafe.Pointer
+ class *uint16
+ classKey windows.Handle
+ hotKey uint32
+ icon windows.Handle
+ process windows.Handle
+}
+
+func Run(executable, workingDir, arguments string) error {
+ return run(executable, workingDir, arguments, launch)
+}
+
+func run(executable, workingDir, arguments string, start func(*shellExecuteInfo) error) error {
+ info := shellExecuteInfo{
+ mask: seeMaskNoCloseProcess | seeMaskNoAsync | seeMaskFlagNoUI,
+ show: windows.SW_HIDE,
+ }
+ info.size = uint32(unsafe.Sizeof(info))
+ var err error
+ if info.verb, err = windows.UTF16PtrFromString("runas"); err != nil {
+ return err
+ }
+ if info.file, err = windows.UTF16PtrFromString(executable); err != nil {
+ return fmt.Errorf("invalid elevated helper path: %w", err)
+ }
+ if info.directory, err = windows.UTF16PtrFromString(workingDir); err != nil {
+ return fmt.Errorf("invalid elevated helper working directory: %w", err)
+ }
+ // 参数已按 Windows 命令行语法转义,直接交给提权工具解析,不经过脚本解释器。
+ if info.parameters, err = windows.UTF16PtrFromString(arguments); err != nil {
+ return fmt.Errorf("invalid elevated helper arguments: %w", err)
+ }
+ if err = start(&info); err != nil {
+ return fmt.Errorf("launch elevated helper: %w", err)
+ }
+ if info.process == 0 {
+ return errors.New("elevated helper process handle unavailable")
+ }
+ return waitForProcess(info.process, windows.WaitForSingleObject, windows.GetExitCodeProcess)
+}
+
+func waitForProcess(process windows.Handle, wait func(windows.Handle, uint32) (uint32, error), getExitCode func(windows.Handle, *uint32) error) error {
+ defer windows.CloseHandle(process)
+
+ // 提权调用完成并释放自身的 COM 引用后,等待工具返回最终结果。
+ state, err := wait(process, windows.INFINITE)
+ if err != nil {
+ return fmt.Errorf("wait for elevated helper: %w", err)
+ }
+ if state != windows.WAIT_OBJECT_0 {
+ return fmt.Errorf("unexpected elevated helper wait result: %d", state)
+ }
+ var exitCode uint32
+ if err = getExitCode(process, &exitCode); err != nil {
+ return fmt.Errorf("get elevated helper exit code: %w", err)
+ }
+ if exitCode != 0 {
+ return fmt.Errorf("elevated helper failed with exit code %d", exitCode)
+ }
+ return nil
+}
+
+func launch(info *shellExecuteInfo) error {
+ // COM 初始化、提权调用和反初始化必须在同一系统线程完成。
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ err := windows.CoInitializeEx(0, coInitApartment|coInitDisableOLE1DDE)
+ switch {
+ case err == nil, errors.Is(err, syscall.Errno(windows.S_FALSE)):
+ defer windows.CoUninitialize()
+ case errors.Is(err, syscall.Errno(windows.RPC_E_CHANGED_MODE)):
+ // 已初始化为其他单元模型时沿用现有 COM 状态,不释放调用方持有的引用。
+ default:
+ return fmt.Errorf("initialize COM for elevated helper: %w", err)
+ }
+ result, _, callErr := shellExecuteEx.Call(uintptr(unsafe.Pointer(info)))
+ runtime.KeepAlive(info)
+ if result == 0 {
+ if callErr == syscall.Errno(0) {
+ return errors.New("ShellExecuteExW failed without an error code")
+ }
+ return fmt.Errorf("ShellExecuteExW: %w", callErr)
+ }
+ return nil
+}
diff --git a/kernel/internal/elevator/elevator_windows_test.go b/kernel/internal/elevator/elevator_windows_test.go
index 24f96b6e0d..cde337766f 100644
--- a/kernel/internal/elevator/elevator_windows_test.go
+++ b/kernel/internal/elevator/elevator_windows_test.go
@@ -2,62 +2,231 @@ package elevator
import (
"encoding/json"
+ "errors"
"os"
- "os/exec"
"path/filepath"
+ "reflect"
+ "runtime"
+ "strconv"
"strings"
+ "syscall"
"testing"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
)
+func TestShellExecuteInfoLayout(t *testing.T) {
+ var info shellExecuteInfo
+ size, processOffset := uintptr(60), uintptr(56)
+ if unsafe.Sizeof(uintptr(0)) == 8 {
+ size, processOffset = 112, 104
+ }
+ if unsafe.Sizeof(info) != size || unsafe.Offsetof(info.process) != processOffset {
+ t.Fatalf("unexpected native structure layout: size %d, process offset %d", unsafe.Sizeof(info), unsafe.Offsetof(info.process))
+ }
+}
+
func TestElevatedProcessResult(t *testing.T) {
- for _, result := range []string{"0", "7", "cancel", "missing"} {
- t.Run(result, func(t *testing.T) {
+ // 使用不提权的测试进程验证原生接口、Unicode 路径和最终退出码,不修改系统配置。
+ source, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(source)
+ if err != nil {
+ t.Fatal(err)
+ }
+ executable := filepath.Join(t.TempDir(), "思源 helper.exe")
+ if err = os.WriteFile(executable, data, 0700); err != nil {
+ t.Fatal(err)
+ }
+ for _, exitCode := range []int{0, 7, 259} {
+ t.Run(strconv.Itoa(exitCode), func(t *testing.T) {
+ workingDir := filepath.Join(t.TempDir(), "工作 空间")
+ if err := os.Mkdir(workingDir, 0700); err != nil {
+ t.Fatal(err)
+ }
receipt := filepath.Join(t.TempDir(), "arguments.json")
- // 替换提权边界,验证真实 PowerShell 的参数解析和退出码,不启动 UAC 或修改系统配置
- mock := `function Start-Process {
-param($FilePath, $WorkingDirectory, $ArgumentList, $Verb, $WindowStyle, [switch]$Wait, [switch]$PassThru)
-if ($Verb -ne 'RunAs' -or $WindowStyle -ne 'Hidden' -or -not $Wait -or -not $PassThru) { throw 'Missing process flags' }
-[IO.File]::WriteAllText(` + quotePowerShell(receipt) + `, (ConvertTo-Json -Compress -InputObject @($FilePath, $WorkingDirectory, $ArgumentList)))
-`
- if result == "cancel" {
- mock += "throw (New-Object System.ComponentModel.Win32Exception 1223)\n}"
- } else if result == "missing" {
- mock += "[pscustomobject]@{ExitCode=$null}\n}"
- } else {
- mock += "[pscustomobject]@{ExitCode=" + result + "}\n}"
- }
- executable := `D:\O'Brien\SiYuan\elevator.exe`
- workingDir := `D:\Program Files\SiYuan`
- arguments := `add-defender-exclusion "D:\Program Files\SiYuan" "D:\notes\\"`
- command := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", mock+"\n"+commandScript(executable, workingDir, arguments))
- output, err := command.CombinedOutput()
- if result == "0" && err != nil || result != "0" && err == nil {
- t.Fatalf("unexpected process result: %v: %s", err, output)
- }
- if result == "7" {
- if failure, ok := err.(*exec.ExitError); !ok || failure.ExitCode() != 7 {
- t.Fatalf("helper exit code was lost: %v", err)
+ expected := []string{"add-defender-exclusion", `D:\Program Files\SiYuan`, `D:\工作 空间\`, `D:\O'Brien\$notes`}
+ args := append([]string{"-test.run=^TestElevatedProcessHelper$", "--", receipt, strconv.Itoa(exitCode)}, expected...)
+ for i := range args {
+ args[i] = syscall.EscapeArg(args[i])
+ }
+ arguments := strings.Join(args, " ")
+ var process windows.Handle
+ err := run(executable, workingDir, arguments, func(info *shellExecuteInfo) error {
+ if windows.UTF16PtrToString(info.verb) != "runas" || info.mask != seeMaskNoCloseProcess|seeMaskNoAsync|seeMaskFlagNoUI || info.show != windows.SW_HIDE {
+ t.Fatal("missing native elevation flags")
+ }
+ if windows.UTF16PtrToString(info.file) != executable || windows.UTF16PtrToString(info.directory) != workingDir || windows.UTF16PtrToString(info.parameters) != arguments {
+ t.Fatal("native process parameters changed")
+ }
+ info.verb, _ = windows.UTF16PtrFromString("open")
+ if err := launch(info); err != nil {
+ return err
}
+ process = info.process
+ return nil
+ })
+ if exitCode == 0 && err != nil || exitCode != 0 && (err == nil || !strings.Contains(err.Error(), "exit code "+strconv.Itoa(exitCode))) {
+ t.Fatalf("unexpected process result: %v", err)
+ }
+ assertHandleClosed(t, process)
+ data, err := os.ReadFile(receipt)
+ if err != nil {
+ t.Fatal(err)
}
- data, readErr := os.ReadFile(receipt)
- if readErr != nil {
- t.Fatal(readErr)
+ var actual struct {
+ Arguments []string
+ WorkingDir string
}
- var actual []string
if err := json.Unmarshal(data, &actual); err != nil {
t.Fatal(err)
}
- if strings.Join(actual, "\n") != strings.Join([]string{executable, workingDir, arguments}, "\n") {
- t.Fatalf("PowerShell changed process arguments: %q", actual)
+ if !reflect.DeepEqual(actual.Arguments, expected) || !strings.EqualFold(actual.WorkingDir, workingDir) {
+ t.Fatalf("process arguments or working directory changed: %+v", actual)
}
})
}
}
+func TestElevatedProcessHelper(t *testing.T) {
+ for i, arg := range os.Args {
+ if arg != "--" {
+ continue
+ }
+ if len(os.Args) < i+4 {
+ t.Fatal("missing helper arguments")
+ }
+ workingDir, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(struct {
+ Arguments []string
+ WorkingDir string
+ }{os.Args[i+3:], workingDir})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(os.Args[i+1], data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ exitCode, err := strconv.Atoi(os.Args[i+2])
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Exit(exitCode)
+ }
+}
+
func TestElevatedProcessLaunchFailure(t *testing.T) {
- // 不存在的绝对路径在请求提权前失败,用于检查调用方接收真实进程错误
err := Run(filepath.Join(t.TempDir(), "missing.exe"), t.TempDir(), "add-defender-exclusion install workspace")
- if err == nil {
- t.Fatal("launch failure was reported as success")
+ if !errors.Is(err, windows.ERROR_FILE_NOT_FOUND) {
+ t.Fatalf("expected missing executable error, got %v", err)
+ }
+ for _, failure := range []error{windows.ERROR_CANCELLED, windows.ERROR_ACCESS_DENIED} {
+ err := run("helper.exe", "working", "arguments", func(*shellExecuteInfo) error { return failure })
+ if !errors.Is(err, failure) {
+ t.Fatalf("launch error was lost: %v", err)
+ }
+ }
+}
+
+func TestElevatedProcessInvalidInput(t *testing.T) {
+ for _, args := range [][3]string{{"helper\x00.exe", "working", "arguments"}, {"helper.exe", "working\x00", "arguments"}, {"helper.exe", "working", "arguments\x00"}} {
+ err := run(args[0], args[1], args[2], func(*shellExecuteInfo) error {
+ t.Fatal("invalid input reached the elevation boundary")
+ return nil
+ })
+ if err == nil {
+ t.Fatal("invalid UTF-16 input was accepted")
+ }
+ }
+}
+
+func TestElevatedProcessHandleFailures(t *testing.T) {
+ t.Run("missing", func(t *testing.T) {
+ err := run("helper.exe", "working", "arguments", func(*shellExecuteInfo) error { return nil })
+ if err == nil || !strings.Contains(err.Error(), "handle unavailable") {
+ t.Fatalf("missing process handle was accepted: %v", err)
+ }
+ })
+ t.Run("wait", func(t *testing.T) {
+ process, err := windows.CreateEvent(nil, 1, 1, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = windows.CloseHandle(process); err != nil {
+ t.Fatal(err)
+ }
+ err = run("helper.exe", "working", "arguments", func(info *shellExecuteInfo) error {
+ info.process = process
+ return nil
+ })
+ if !errors.Is(err, windows.ERROR_INVALID_HANDLE) || !strings.Contains(err.Error(), "wait for") {
+ t.Fatalf("wait failure was accepted: %v", err)
+ }
+ })
+ t.Run("exitCode", func(t *testing.T) {
+ // 使用已触发事件完成真实等待,在查询边界模拟权限错误并检查句柄释放。
+ process, err := windows.CreateEvent(nil, 1, 1, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = waitForProcess(process, windows.WaitForSingleObject, func(windows.Handle, *uint32) error {
+ return windows.ERROR_ACCESS_DENIED
+ })
+ if !errors.Is(err, windows.ERROR_ACCESS_DENIED) || !strings.Contains(err.Error(), "get elevated helper exit code") {
+ t.Fatalf("exit code query failure was accepted: %v", err)
+ }
+ assertHandleClosed(t, process)
+ })
+ t.Run("unexpectedWait", func(t *testing.T) {
+ process, err := windows.CreateEvent(nil, 1, 1, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = waitForProcess(process, func(windows.Handle, uint32) (uint32, error) {
+ return uint32(windows.WAIT_TIMEOUT), nil
+ }, func(windows.Handle, *uint32) error {
+ t.Fatal("exit code queried before process termination")
+ return nil
+ })
+ if err == nil || !strings.Contains(err.Error(), "unexpected elevated helper wait result") {
+ t.Fatalf("unexpected wait result was accepted: %v", err)
+ }
+ assertHandleClosed(t, process)
+ })
+}
+
+func TestNativeLaunchPreservesCOM(t *testing.T) {
+ for _, mode := range []uint32{coInitApartment, 0} {
+ t.Run(strconv.FormatUint(uint64(mode), 10), func(t *testing.T) {
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ if err := windows.CoInitializeEx(0, mode); err != nil && !errors.Is(err, syscall.Errno(windows.S_FALSE)) {
+ t.Fatal(err)
+ }
+ defer windows.CoUninitialize()
+ if err := Run(filepath.Join(t.TempDir(), "missing.exe"), t.TempDir(), "arguments"); !errors.Is(err, windows.ERROR_FILE_NOT_FOUND) {
+ t.Fatalf("native launch failed in existing COM apartment: %v", err)
+ }
+ err := windows.CoInitializeEx(0, mode)
+ if err == nil || errors.Is(err, syscall.Errno(windows.S_FALSE)) {
+ defer windows.CoUninitialize()
+ }
+ if !errors.Is(err, syscall.Errno(windows.S_FALSE)) {
+ t.Fatalf("caller's COM reference was released: %v", err)
+ }
+ })
+ }
+}
+
+func assertHandleClosed(t *testing.T, process windows.Handle) {
+ t.Helper()
+ if _, err := windows.WaitForSingleObject(process, 0); !errors.Is(err, windows.ERROR_INVALID_HANDLE) {
+ t.Fatalf("process handle was not closed: %v", err)
}
}