跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录
修改cmd/cage-hyperv-manager/main_windows.go+5 −0看文件
@@ -5,6 +5,7 @@ package main
55import (
66 "context"
77 "encoding/json"
8新增: "errors"
89 "flag"
910 "fmt"
1011 "github.com/google/uuid"
@@ -71,6 +72,10 @@ func main() {
7172 }
7273 if err != nil {
7374 fmt.Fprintln(os.Stderr, "Windows host manager action did not complete.")
75新增: var pipeError *guestos.WindowsHostEnrollmentPipeError
76新增: if errors.As(err, &pipeError) {
77新增: fmt.Fprintln(os.Stderr, pipeError)
78新增: }
7479 os.Exit(1)
7580 }
7681}
修改internal/guestos/windows_host_enrollment.go+20 −0看文件
@@ -2,9 +2,29 @@ package guestos
22
33import (
44 "errors"
5新增: "fmt"
6新增: "syscall"
7新增:
58 "github.com/google/uuid"
69)
710
11新增:// WindowsHostEnrollmentPipeError exposes only a fixed operation and an OS code.
12新增:// The underlying PathError can contain the private pipe name.
13新增:type WindowsHostEnrollmentPipeError struct {
14新增: Operation string
15新增: Win32 syscall.Errno
16新增:}
17新增:
18新增:func (err *WindowsHostEnrollmentPipeError) Error() string {
19新增: return fmt.Sprintf("enrollment_pipe_%s_failed (win32=%d)", err.Operation, err.Win32)
20新增:}
21新增:
22新增:func enrollmentPipeError(operation string, err error) error {
23新增: var code syscall.Errno
24新增: errors.As(err, &code)
25新增: return &WindowsHostEnrollmentPipeError{Operation: operation, Win32: code}
26新增:}
27新增:
828// Options are captured by the original, unprivileged setup process. A pipe
929// client cannot replace these paths, identities, or installation choices.
1030type WindowsHostEnrollmentOptions struct {
新增internal/guestos/windows_host_enrollment_native_windows_test.go+95 −0看文件
@@ -0,0 +1,95 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "os"
8新增: "os/exec"
9新增: "path/filepath"
10新增: "runtime"
11新增: "syscall"
12新增: "testing"
13新增: "time"
14新增: "unsafe"
15新增:
16新增: "golang.org/x/sys/windows"
17新增:)
18新增:
19新增:// This exercises the shipping helper and PowerShell ready/DPAPI protocol using
20新增:// an ordinary token. Elevated CI runners must not mask the owner's pipe ACL.
21新增:func TestWindowsHostEnrollmentOrdinaryUser(t *testing.T) {
22新增: root, err := filepath.Abs(filepath.Join("..", ".."))
23新增: if err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: manager := os.Getenv("CAGE_TEST_WINDOWS_ENROLLMENT_MANAGER")
27新增: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
28新增: defer cancel()
29新增: if manager == "" {
30新增: manager = filepath.Join(t.TempDir(), "Cage.HyperVManager.exe")
31新增: build := exec.CommandContext(ctx, "go", "build", "-o", manager, "./cmd/cage-hyperv-manager")
32新增: build.Dir = root
33新增: if output, err := build.CombinedOutput(); err != nil {
34新增: t.Fatalf("build enrollment helper: %v\n%s", err, output)
35新增: }
36新增: }
37新增: shell := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
38新增: cmd := exec.CommandContext(ctx, shell, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
39新增: "-File", filepath.Join(root, "scripts", "guest-os", "windows-host-enrollment-smoke.ps1"), "-ManagerExecutable", manager)
40新增: if windows.GetCurrentProcessToken().IsElevated() {
41新增: var token windows.Token
42新增: if err := windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_DUPLICATE|windows.TOKEN_QUERY|windows.TOKEN_ASSIGN_PRIMARY|windows.TOKEN_ADJUST_DEFAULT, &token); err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: defer token.Close()
46新增: ordinary, err := token.GetLinkedToken()
47新增: if err != nil {
48新增: // Some disposable CI runners have UAC disabled and no linked token.
49新增: // LUA_TOKEN also filters administrator account groups which removing
50新增: // privileges alone leaves elevated from TokenElevation's perspective.
51新增: create := windows.NewLazySystemDLL("advapi32.dll").NewProc("CreateRestrictedToken")
52新增: const disableMaxPrivilegeAndLUA = 0x1 | 0x4
53新增: ok, _, callErr := create.Call(uintptr(token), disableMaxPrivilegeAndLUA, 0, 0, 0, 0, 0, 0, uintptr(unsafe.Pointer(&ordinary)))
54新增: if ok == 0 {
55新增: t.Fatal(callErr)
56新增: }
57新增: defer ordinary.Close()
58新增: medium, err := windows.CreateWellKnownSid(windows.WinMediumLabelSid)
59新增: if err != nil {
60新增: t.Fatal(err)
61新增: }
62新增: label := windows.Tokenmandatorylabel{Label: windows.SIDAndAttributes{Sid: medium, Attributes: windows.SE_GROUP_INTEGRITY}}
63新增: if err := windows.SetTokenInformation(ordinary, windows.TokenIntegrityLevel, (*byte)(unsafe.Pointer(&label)), label.Size()); err != nil {
64新增: t.Fatal(err)
65新增: }
66新增: user, err := ordinary.GetTokenUser()
67新增: if err != nil {
68新增: t.Fatal(err)
69新增: }
70新增: security, err := windows.SecurityDescriptorFromString("D:(A;;GA;;;" + user.User.Sid.String() + ")(A;;GA;;;SY)(A;;GA;;;BA)")
71新增: if err != nil {
72新增: t.Fatal(err)
73新增: }
74新增: dacl, _, err := security.DACL()
75新增: if err != nil {
76新增: t.Fatal(err)
77新增: }
78新增: defaults := struct{ ACL *windows.ACL }{dacl}
79新增: err = windows.SetTokenInformation(ordinary, windows.TokenDefaultDacl, (*byte)(unsafe.Pointer(&defaults)), uint32(unsafe.Sizeof(defaults)))
80新增: runtime.KeepAlive(security)
81新增: if err != nil {
82新增: t.Fatal(err)
83新增: }
84新增: } else {
85新增: defer ordinary.Close()
86新增: }
87新增: if ordinary.IsElevated() {
88新增: t.Fatal("the enrollment regression requires an unelevated token")
89新增: }
90新增: cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(ordinary)}
91新增: }
92新增: if output, err := cmd.CombinedOutput(); err != nil {
93新增: t.Fatalf("ordinary-user enrollment: %v\n%s", err, output)
94新增: }
95新增:}
修改internal/guestos/windows_host_enrollment_test.go+16 −1看文件
@@ -1,10 +1,25 @@
11package guestos
22
33import (
4删除: "github.com/google/uuid"
4新增: "errors"
5新增: "os"
6新增: "syscall"
57 "testing"
8新增:
9新增: "github.com/google/uuid"
610)
711
12新增:func TestWindowsHostEnrollmentPipeDiagnostic(t *testing.T) {
13新增: err := enrollmentPipeError("accept", &os.PathError{Op: "open", Path: `\\.\pipe\private-fixture`, Err: syscall.Errno(5)})
14新增: if err.Error() != "enrollment_pipe_accept_failed (win32=5)" {
15新增: t.Fatalf("pipe diagnostic lost its code or exposed private data: %s", err)
16新增: }
17新增: var diagnostic *WindowsHostEnrollmentPipeError
18新增: if !errors.As(err, &diagnostic) {
19新增: t.Fatal("the helper cannot recognize a safe pipe diagnostic")
20新增: }
21新增:}
22新增:
823func TestWindowsHostEnrollmentFixedAuthorityAndRole(t *testing.T) {
924 vm := uuid.New()
1025 sid := "S-1-5-21-1-2-3-1001"
修改internal/guestos/windows_host_enrollment_windows.go+5 −3看文件
@@ -582,9 +582,11 @@ func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollm
582582 }()
583583 ctx, cancel := context.WithCancel(parent)
584584 defer cancel()
585删除: listener, err := winio.ListenPipe(`\\.\pipe\`+options.Pipe, &winio.PipeConfig{SecurityDescriptor: "O:" + options.HostSID + "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + options.HostSID + ")", InputBufferSize: enrollmentWireLimit, OutputBufferSize: enrollmentWireLimit})
585新增: // go-winio opens a second server instance after creating its placeholder.
586新增: // The ordinary owner needs FILE_CREATE_PIPE_INSTANCE (0x4) for that open.
587新增: listener, err := winio.ListenPipe(`\\.\pipe\`+options.Pipe, &winio.PipeConfig{SecurityDescriptor: "O:" + options.HostSID + "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019f;;;" + options.HostSID + ")", InputBufferSize: enrollmentWireLimit, OutputBufferSize: enrollmentWireLimit})
586588 if err != nil {
587删除: return errors.New("enrollment_pipe_unavailable")
589新增: return enrollmentPipeError("listen", err)
588590 }
589591 defer listener.Close()
590592 var active sync.WaitGroup
@@ -618,7 +620,7 @@ func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollm
618620 if ctx.Err() != nil {
619621 return nil
620622 }
621删除: return errors.New("enrollment_pipe_unavailable")
623新增: return enrollmentPipeError("accept", err)
622624 }
623625 select {
624626 case slots <- struct{}{}:
修改scripts/ci-windows-build.ps1+2 −0看文件
@@ -61,6 +61,8 @@ try {
6161 $qemuSource = Join-Path $repository '_output/windows-qemu-sources/full-source.tar.gz'
6262 }
6363 & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release
64新增: Invoke-BuildTool $windowsPowerShell @('-NoProfile', '-NonInteractive', '-File', 'scripts/guest-os/windows-host-enrollment.tests.ps1')
65新增: Invoke-BuildTool 'go' @('test', './internal/guestos', '-run', '^TestWindowsHostEnrollment', '-count=1')
6466 if (-not $Release) {
6567 $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
6668 foreach ($test in @('install-guest-powershell.tests.ps1', 'windows-evaluation.tests.ps1')) {
修改scripts/guest-os/setup-windows-guest.ps1+1 −1看文件
@@ -40,7 +40,7 @@ if(!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
4040 $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{& $s @a;exit 0}catch{Write-Error $_;exit 1}'
4141 $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
4242 try{
43删除: if($context){Wait-CageHostEnrollment $context}
43新增: if($context){Wait-CageHostEnrollment $context $worker}
4444 $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru
4545 if($context){Set-CageHostEnrollmentAdmin $context $process}
4646 $process.WaitForExit()
修改scripts/guest-os/windows-host-enrollment-smoke.ps1+1 −1看文件
@@ -17,7 +17,7 @@ try {
1717 $workerArguments=@('user-enrollment','--vm-id',$vm.ToString('D'),'--host-sid',$identity.User.Value,'--profile',('"'+$profile+'"'),'--state',('"'+$state+'"'),'--installation-id',$id.ToString('D'),'--pipe',$pipe,'--parent-pid',[string]$PID)
1818 $worker=Start-Process -FilePath $ManagerExecutable -ArgumentList $workerArguments -NoNewWindow -PassThru
1919 $context=@{Pipe=$pipe;VMID=$vm.ToString('D');HostSID=$identity.User.Value;WorkerPID=[uint32]$worker.Id;WorkerStarted=[Cage.HostEnrollment.Native]::Started([uint32]$worker.Id);WorkerExe=[IO.Path]::GetFullPath($ManagerExecutable);OwnerPID=[uint32]$PID;OwnerStarted=[Cage.HostEnrollment.Native]::Started([uint32]$PID)}
20删除: Wait-CageHostEnrollment $context
20新增: Wait-CageHostEnrollment $context $worker
2121 $ctxPath=Join-Path $root 'context.json';[IO.File]::WriteAllText($ctxPath,($context|ConvertTo-Json))
2222 $module=Join-Path $PSScriptRoot 'windows-host-enrollment.ps1'
2323 $senderPath=Join-Path $root 'sender.ps1';$result=Join-Path $root 'result.json'
修改scripts/guest-os/windows-host-enrollment.ps1+8 −2看文件
@@ -110,8 +110,14 @@ function Stop-CageHostEnrollment($Context) {
110110 $null=Invoke-CageHostEnrollment $Context @{action='stop'} $null
111111}
112112
113删除:function Wait-CageHostEnrollment($Context) {
113新增:function Wait-CageHostEnrollment($Context, $Worker) {
114114 $deadline=[DateTime]::UtcNow.AddSeconds(10)
115删除: do {try{$null=Invoke-CageHostEnrollment $Context @{action='ready'} $null;return}catch{Start-Sleep -Milliseconds 100}}while([DateTime]::UtcNow -lt $deadline)
115新增: do {
116新增: if ($Worker -and $Worker.HasExited) {
117新增: throw "enrollment_worker_exited (exit=$($Worker.ExitCode)). Check the enrollment error code in operation details, then continue installation."
118新增: }
119新增: try { $null=Invoke-CageHostEnrollment $Context @{action='ready'} $null; return }
120新增: catch { Start-Sleep -Milliseconds 100 }
121新增: } while ([DateTime]::UtcNow -lt $deadline)
116122 throw 'The original user enrollment worker did not become available.'
117123}
新增scripts/guest-os/windows-host-enrollment.tests.ps1+25 −0看文件
@@ -0,0 +1,25 @@
1新增:#requires -Version 5.1
2新增:$ErrorActionPreference = 'Stop'
3新增:$parseErrors = $null
4新增:$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'windows-host-enrollment.ps1'), [ref]$null, [ref]$parseErrors)
5新增:if ($parseErrors.Count) { throw $parseErrors[0] }
6新增:$wait = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Wait-CageHostEnrollment' }, $true)
7新增:. ([scriptblock]::Create($wait.Extent.Text))
8新增:$script:requests = 0
9新增:$worker = [pscustomobject]@{ HasExited = $false; ExitCode = 1 }
10新增:function Invoke-CageHostEnrollment {
11新增: param($Context, $Request, $Secret)
12新增: $script:requests++
13新增: if ($script:failRequest) { $worker.HasExited = $true; throw 'Injected pipe failure' }
14新增: if ($Request.action -cne 'ready') { throw 'Unexpected enrollment request' }
15新增:}
16新增:Wait-CageHostEnrollment @{} $worker
17新增:if ($script:requests -ne 1) { throw 'The ready handshake was not performed.' }
18新增:$script:failRequest = $true
19新增:$watch = [Diagnostics.Stopwatch]::StartNew()
20新增:try { Wait-CageHostEnrollment @{} $worker; throw 'Worker failure was ignored.' }
21新增:catch {
22新增: if ($_.Exception.Message -notlike '*enrollment_worker_exited*') { throw }
23新增:}
24新增:if ($script:requests -ne 2 -or $watch.Elapsed.TotalSeconds -gt 2) { throw 'An exited worker was retried until the ready timeout.' }
25新增:Write-Output 'Passed ready handshake and early worker-exit reporting.'