提交记录修改cmd/cage-hyperv-manager/main_windows.go+5 −0看文件
修改internal/guestos/windows_host_enrollment.go+20 −0看文件
新增internal/guestos/windows_host_enrollment_native_windows_test.go+95 −0看文件
修改internal/guestos/windows_host_enrollment_test.go+16 −1看文件
修改internal/guestos/windows_host_enrollment_windows.go+5 −3看文件
修改scripts/ci-windows-build.ps1+2 −0看文件
修改scripts/guest-os/setup-windows-guest.ps1+1 −1看文件
修改scripts/guest-os/windows-host-enrollment-smoke.ps1+1 −1看文件
修改scripts/guest-os/windows-host-enrollment.ps1+8 −2看文件
新增scripts/guest-os/windows-host-enrollment.tests.ps1+25 −0看文件
| @@ -5,6 +5,7 @@ package main | ||
| 5 | 5 | import ( |
| 6 | 6 | "context" |
| 7 | 7 | "encoding/json" |
| 8 | 新增: "errors" | |
| 8 | 9 | "flag" |
| 9 | 10 | "fmt" |
| 10 | 11 | "github.com/google/uuid" |
| @@ -71,6 +72,10 @@ func main() { | ||
| 71 | 72 | } |
| 72 | 73 | if err != nil { |
| 73 | 74 | 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 | 新增: } | |
| 74 | 79 | os.Exit(1) |
| 75 | 80 | } |
| 76 | 81 | } |
| @@ -2,9 +2,29 @@ package guestos | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "errors" |
| 5 | 新增: "fmt" | |
| 6 | 新增: "syscall" | |
| 7 | 新增: | |
| 5 | 8 | "github.com/google/uuid" |
| 6 | 9 | ) |
| 7 | 10 | |
| 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 | 新增: | |
| 8 | 28 | // Options are captured by the original, unprivileged setup process. A pipe |
| 9 | 29 | // client cannot replace these paths, identities, or installation choices. |
| 10 | 30 | type WindowsHostEnrollmentOptions struct { |
| @@ -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 | 新增:} | |
| @@ -1,10 +1,25 @@ | ||
| 1 | 1 | package guestos |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 删除: "github.com/google/uuid" | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "syscall" | |
| 5 | 7 | "testing" |
| 8 | 新增: | |
| 9 | 新增: "github.com/google/uuid" | |
| 6 | 10 | ) |
| 7 | 11 | |
| 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 | 新增: | |
| 8 | 23 | func TestWindowsHostEnrollmentFixedAuthorityAndRole(t *testing.T) { |
| 9 | 24 | vm := uuid.New() |
| 10 | 25 | sid := "S-1-5-21-1-2-3-1001" |
| @@ -582,9 +582,11 @@ func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollm | ||
| 582 | 582 | }() |
| 583 | 583 | ctx, cancel := context.WithCancel(parent) |
| 584 | 584 | 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}) | |
| 586 | 588 | if err != nil { |
| 587 | 删除: return errors.New("enrollment_pipe_unavailable") | |
| 589 | 新增: return enrollmentPipeError("listen", err) | |
| 588 | 590 | } |
| 589 | 591 | defer listener.Close() |
| 590 | 592 | var active sync.WaitGroup |
| @@ -618,7 +620,7 @@ func RunWindowsHostEnrollment(parent context.Context, options WindowsHostEnrollm | ||
| 618 | 620 | if ctx.Err() != nil { |
| 619 | 621 | return nil |
| 620 | 622 | } |
| 621 | 删除: return errors.New("enrollment_pipe_unavailable") | |
| 623 | 新增: return enrollmentPipeError("accept", err) | |
| 622 | 624 | } |
| 623 | 625 | select { |
| 624 | 626 | case slots <- struct{}{}: |
| @@ -61,6 +61,8 @@ try { | ||
| 61 | 61 | $qemuSource = Join-Path $repository '_output/windows-qemu-sources/full-source.tar.gz' |
| 62 | 62 | } |
| 63 | 63 | & (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') | |
| 64 | 66 | if (-not $Release) { |
| 65 | 67 | $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe' |
| 66 | 68 | foreach ($test in @('install-guest-powershell.tests.ps1', 'windows-evaluation.tests.ps1')) { |
| @@ -40,7 +40,7 @@ if(!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) | ||
| 40 | 40 | $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}' |
| 41 | 41 | $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) |
| 42 | 42 | try{ |
| 43 | 删除: if($context){Wait-CageHostEnrollment $context} | |
| 43 | 新增: if($context){Wait-CageHostEnrollment $context $worker} | |
| 44 | 44 | $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru |
| 45 | 45 | if($context){Set-CageHostEnrollmentAdmin $context $process} |
| 46 | 46 | $process.WaitForExit() |
| @@ -17,7 +17,7 @@ try { | ||
| 17 | 17 | $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) |
| 18 | 18 | $worker=Start-Process -FilePath $ManagerExecutable -ArgumentList $workerArguments -NoNewWindow -PassThru |
| 19 | 19 | $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 | |
| 21 | 21 | $ctxPath=Join-Path $root 'context.json';[IO.File]::WriteAllText($ctxPath,($context|ConvertTo-Json)) |
| 22 | 22 | $module=Join-Path $PSScriptRoot 'windows-host-enrollment.ps1' |
| 23 | 23 | $senderPath=Join-Path $root 'sender.ps1';$result=Join-Path $root 'result.json' |
| @@ -110,8 +110,14 @@ function Stop-CageHostEnrollment($Context) { | ||
| 110 | 110 | $null=Invoke-CageHostEnrollment $Context @{action='stop'} $null |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | 删除:function Wait-CageHostEnrollment($Context) { | |
| 113 | 新增:function Wait-CageHostEnrollment($Context, $Worker) { | |
| 114 | 114 | $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) | |
| 116 | 122 | throw 'The original user enrollment worker did not become available.' |
| 117 | 123 | } |
| @@ -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.' | |

