| 1 | #requires -Version 5.1 |
| 2 | [CmdletBinding()] |
| 3 | param( |
| 4 | [Parameter(Mandatory)][string]$Profile, |
| 5 | [Parameter(Mandatory)][string]$State, |
| 6 | [Parameter(Mandatory)][guid]$InstallationID, |
| 7 | [Parameter(Mandatory)][string]$IsoPath, |
| 8 | [Parameter(Mandatory)][ValidatePattern('^[0-9A-Fa-f]{64}$')][string]$ExpectedIsoSha256, |
| 9 | [string]$ManifestPath, |
| 10 | [string]$ManifestSHA256, |
| 11 | [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value), |
| 12 | [object]$HostEnrollment |
| 13 | ) |
| 14 | $ErrorActionPreference='Stop' |
| 15 | $ProgressPreference='SilentlyContinue' |
| 16 | [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) |
| 17 | $identity=[Security.Principal.WindowsIdentity]::GetCurrent() |
| 18 | $principal=[Security.Principal.WindowsPrincipal]::new($identity) |
| 19 | . (Join-Path $PSScriptRoot 'windows-host-image.ps1') |
| 20 | |
| 21 | function Wait-CageWindowsInstaller($Process, [string]$ProgressFile) { |
| 22 | $lastStage = '' |
| 23 | do { |
| 24 | $exited = $Process.WaitForExit(250) |
| 25 | $stage = '' |
| 26 | $reader = $null |
| 27 | try { |
| 28 | $reader = [IO.StreamReader]::new([IO.File]::Open($ProgressFile, 'Open', 'Read', 'ReadWrite')) |
| 29 | $stage = $reader.ReadToEnd() |
| 30 | } catch [IO.IOException] { } |
| 31 | finally { if ($reader) { $reader.Dispose() } } |
| 32 | if ($stage -cmatch '^CAGE_GUEST_STAGE windows-11 (account|oobe|credentials|media|tools|services)$' -and $stage -cne $lastStage) { |
| 33 | Write-Output $stage |
| 34 | $lastStage = $stage |
| 35 | } |
| 36 | } while (!$exited) |
| 37 | } |
| 38 | |
| 39 | if(!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ |
| 40 | if($identity.User.Value -cne $HostUserSID){throw 'Continue setup with the already authorized host user.'} |
| 41 | if($HostEnrollment){throw 'Original user enrollment must be created by this setup process.'} |
| 42 | $worker=$null;$context=$null |
| 43 | $receipt=Join-Path $Profile 'windows-install-vm.txt' |
| 44 | if((Test-Path -LiteralPath $receipt -PathType Leaf) -and !(Test-Path -LiteralPath (Join-Path $Profile 'windows-guest.json'))){ |
| 45 | . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1') |
| 46 | $expectedVM=[guid][IO.File]::ReadAllText($receipt) |
| 47 | $manager=Join-Path $PSScriptRoot 'payload/Cage.HyperVManager.exe' |
| 48 | if($expectedVM -eq [guid]::Empty -or !(Test-Path -LiteralPath $manager -PathType Leaf)){throw 'The fixed VM enrollment payload is unavailable.'} |
| 49 | $pipe='Cage.Enroll.'+[guid]::NewGuid().ToString('N') |
| 50 | $arguments=@('user-enrollment','--vm-id',$expectedVM.ToString('D'),'--host-sid',$HostUserSID,'--profile',('"'+[IO.Path]::GetFullPath($Profile)+'"'),'--state',('"'+[IO.Path]::GetFullPath($State)+'"'),'--installation-id',$InstallationID.ToString('D'),'--pipe',$pipe,'--parent-pid',[string]$PID) |
| 51 | $worker=Start-Process -FilePath $manager -ArgumentList $arguments -NoNewWindow -PassThru |
| 52 | $context=@{Pipe=$pipe;WorkerPID=[uint32]$worker.Id;WorkerStarted=[Cage.HostEnrollment.Native]::Started([uint32]$worker.Id);WorkerExe=[IO.Path]::GetFullPath($manager);OwnerPID=[uint32]$PID;OwnerStarted=[Cage.HostEnrollment.Native]::Started([uint32]$PID);HostSID=$HostUserSID;VMID=$expectedVM.ToString('D');InstallationID=$InstallationID.ToString('D');Profile=[IO.Path]::GetFullPath($Profile);State=[IO.Path]::GetFullPath($State)} |
| 53 | } |
| 54 | # Preserve every selected installation argument across the one-time UAC |
| 55 | # boundary. Encoded data cannot become executable PowerShell syntax. |
| 56 | $progressFile=Join-Path ([IO.Path]::GetTempPath()) ('cage-windows-setup-'+[guid]::NewGuid().ToString('N')+'.stage') |
| 57 | # Hold the new file without delete sharing across UAC. The elevated writer |
| 58 | # opens this existing file once, so its path cannot be replaced mid-install. |
| 59 | $progressHandle=[IO.File]::Open($progressFile,'CreateNew','ReadWrite','ReadWrite') |
| 60 | $parameters=@{Profile=$Profile;State=$State;InstallationID=$InstallationID.ToString('D');IsoPath=$IsoPath;ExpectedIsoSha256=$ExpectedIsoSha256;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;HostUserSID=$HostUserSID;HostEnrollment=$context;ProgressFile=$progressFile} |
| 61 | $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($parameters|ConvertTo-Json -Depth 6 -Compress))) |
| 62 | $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($PSCommandPath)) |
| 63 | $command=@' |
| 64 | $ErrorActionPreference='Stop' |
| 65 | $p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PARAMETERS__'))|ConvertFrom-Json |
| 66 | $a=@{} |
| 67 | $p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value} |
| 68 | $progressFile=$a.ProgressFile |
| 69 | $a.Remove('ProgressFile') |
| 70 | $s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__SCRIPT__')) |
| 71 | $progressStream=$null |
| 72 | try { |
| 73 | $progressStream=[IO.File]::Open($progressFile,'Open','Write','ReadWrite') |
| 74 | & $s @a | ForEach-Object { |
| 75 | $line=[string]$_ |
| 76 | if ($line -cmatch '^CAGE_GUEST_STAGE windows-11 (account|oobe|credentials|media|tools|services)$') { |
| 77 | $bytes=[Text.Encoding]::UTF8.GetBytes($line) |
| 78 | $progressStream.Position=0 |
| 79 | $progressStream.SetLength(0) |
| 80 | $progressStream.Write($bytes,0,$bytes.Length) |
| 81 | $progressStream.Flush() |
| 82 | } |
| 83 | Write-Output $_ |
| 84 | } |
| 85 | exit 0 |
| 86 | } catch { Write-Error $_; exit 1 } |
| 87 | finally { if ($progressStream) { $progressStream.Dispose() } } |
| 88 | '@ |
| 89 | $command=$command.Replace('__PARAMETERS__',$payload).Replace('__SCRIPT__',$script) |
| 90 | $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) |
| 91 | try{ |
| 92 | if($context){Wait-CageHostEnrollment $context $worker} |
| 93 | $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru |
| 94 | # Windows PowerShell 5.1 must retain a handle before waiting to read ExitCode. |
| 95 | $null=$process.Handle |
| 96 | if($context){Set-CageHostEnrollmentAdmin $context $process} |
| 97 | Wait-CageWindowsInstaller $process $progressFile |
| 98 | if($process.ExitCode -ne 0){throw 'Windows setup did not complete; existing VM and data were preserved.'} |
| 99 | }finally{ |
| 100 | if($context){try{Stop-CageHostEnrollment $context}catch{}} |
| 101 | if($worker){if(!$worker.WaitForExit(5000) -and [Cage.HostEnrollment.Native]::Started([uint32]$worker.Id) -eq [long]$context.WorkerStarted){$worker.Kill();$worker.WaitForExit()};$worker.Dispose()} |
| 102 | $progressHandle.Dispose() |
| 103 | try { [IO.File]::Delete($progressFile) } catch [IO.IOException] { } |
| 104 | } |
| 105 | return |
| 106 | } |
| 107 | $state=[IO.Path]::GetFullPath($State) |
| 108 | $stateAnchor=Get-Item -LiteralPath (Join-Path $Profile 'state') -Force -ErrorAction SilentlyContinue |
| 109 | if ($stateAnchor -and $stateAnchor.Attributes -band [IO.FileAttributes]::ReparsePoint) { |
| 110 | $expectedState=@($stateAnchor.Target) |
| 111 | if ($expectedState.Count -ne 1 -or ![IO.Path]::IsPathRooted($expectedState[0]) -or [IO.Path]::GetFullPath($expectedState[0]) -ne $state) { throw 'The selected storage path changed.' } |
| 112 | } elseif ([IO.Path]::GetFullPath((Join-Path $Profile 'state')) -ne $state) { throw 'The selected storage path changed.' } |
| 113 | $instance=Join-Path $state ('windows-'+$InstallationID.ToString('N')) |
| 114 | $name='Cage-'+$InstallationID.ToString('N') |
| 115 | $receipt=Join-Path $Profile 'windows-install-vm.txt' |
| 116 | $owner=Get-Content -LiteralPath (Join-Path $Profile 'guest-install.json') -Raw | ConvertFrom-Json |
| 117 | $preparedPath = Join-Path $Profile ('guest-install-media-'+$InstallationID.ToString('D')+'.json') |
| 118 | if ($owner.source.host.system -ceq 'windows-11') { |
| 119 | $preparedFile = Get-Item -LiteralPath $preparedPath -Force |
| 120 | if ($preparedFile -isnot [IO.FileInfo] -or $preparedFile.Length -gt 32768 -or $preparedFile.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid verified installation media receipt.' } |
| 121 | $prepared = Get-Content -LiteralPath $preparedPath -Raw | ConvertFrom-Json |
| 122 | if ([guid]$prepared.id -ne $InstallationID -or $prepared.source.digest -cne $owner.source.digest -or |
| 123 | $prepared.source.host.edition -cne $owner.source.host.edition -or $prepared.source.host.language -cne $owner.source.host.language -or |
| 124 | $prepared.source.version -cne $owner.source.version -or $prepared.source.build -cne $owner.source.build -or $prepared.source.format -cne 'esd') { |
| 125 | throw 'The verified Windows image no longer matches the selected host system.' |
| 126 | } |
| 127 | $owner | Add-Member -NotePropertyName media -NotePropertyValue $prepared.source.path -Force |
| 128 | $owner | Add-Member -NotePropertyName sha256 -NotePropertyValue $prepared.source.digest.Substring(7) -Force |
| 129 | } |
| 130 | if ([guid]$owner.id -ne $InstallationID -or $owner.system -ne 'windows-11' -or $owner.media -ne $IsoPath -or $owner.sha256 -ne $ExpectedIsoSha256) { |
| 131 | throw 'The selected Windows installation no longer matches this profile.' |
| 132 | } |
| 133 | $fromHost = $owner.source.host.system -ceq 'windows-11' |
| 134 | $setupCredential = $null |
| 135 | $published = Test-Path -LiteralPath (Join-Path $Profile 'windows-guest.json') |
| 136 | $credentialPath = Join-Path $Profile ('windows-setup-'+$InstallationID.ToString('N')+'.dpapi') |
| 137 | if ($fromHost -and (!$published -or (Test-Path -LiteralPath $credentialPath))) { |
| 138 | if ($identity.User.Value -cne $HostUserSID) { throw 'Automatic system creation requires the same Windows host account after elevation.' } |
| 139 | $setupCredential = Get-CageSetupCredential $Profile $InstallationID |
| 140 | } |
| 141 | $null=New-Item -ItemType Directory -Path $state -Force |
| 142 | function Assert-Instance($VM) { |
| 143 | if ($null -eq $VM -or $VM.Name -cne $name -or $VM.Generation -ne 2 -or |
| 144 | !($VM.ConfigurationLocation -eq $instance -or $VM.ConfigurationLocation.StartsWith($instance.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or |
| 145 | @(Hyper-V\Get-VMNetworkAdapter -VM $VM).Count) { throw 'The selected installation no longer owns this offline virtual machine.' } |
| 146 | } |
| 147 | $readyToProvision=Test-Path -LiteralPath $receipt -PathType Leaf |
| 148 | if ($readyToProvision) { |
| 149 | $vm=Hyper-V\Get-VM -Id ([guid][IO.File]::ReadAllText($receipt)) |
| 150 | Assert-Instance $vm |
| 151 | } else { |
| 152 | $vm=@(Hyper-V\Get-VM -Name $name -ErrorAction SilentlyContinue) |
| 153 | if (!$vm.Count) { |
| 154 | $imageOptions = @{} |
| 155 | if ($fromHost) { $imageOptions = @{ ImageEdition=$owner.source.host.edition; ImageLanguage=$owner.source.host.language; ImageBuild=$owner.source.build; GuestAdministrator=$setupCredential } } |
| 156 | else { Write-Output 'CAGE_GUEST_STAGE windows-11 account' } |
| 157 | $created=& (Join-Path $PSScriptRoot 'new-windows-guest.ps1') -Name $name -IsoPath $IsoPath -ExpectedIsoSha256 $ExpectedIsoSha256 -InstanceDirectory $instance -Confirm:$false @imageOptions |
| 158 | $vm=Hyper-V\Get-VM -Id $created.VMId |
| 159 | } elseif ($vm.Count -eq 1) { $vm=$vm[0] } |
| 160 | else { throw 'The installation has an ambiguous Hyper-V registration.' } |
| 161 | Assert-Instance $vm |
| 162 | if (@($vm | Hyper-V\Get-VMHardDiskDrive | Where-Object Path -eq (Join-Path $instance 'system.vhdx')).Count -ne 1 -or |
| 163 | (!$fromHost -and @($vm | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $IsoPath).Count -ne 1)) { |
| 164 | throw 'The retained Windows installation disk or setup media does not match.' |
| 165 | } |
| 166 | $next=$receipt+'.'+[guid]::NewGuid().ToString('N') |
| 167 | try { [IO.File]::WriteAllText($next,$vm.Id.ToString('D')); [IO.File]::Move($next,$receipt) } |
| 168 | finally { if ([IO.File]::Exists($next)) { [IO.File]::Delete($next) } } |
| 169 | } |
| 170 | if ($vm.State -eq 'Off') { Hyper-V\Start-VM -VM $vm; $vm=Hyper-V\Get-VM -Id $vm.Id } |
| 171 | if ($vm.State -ne 'Running') { throw 'The private Windows guest is not running yet. Retry after its current operation.' } |
| 172 | if (!$readyToProvision -and !$fromHost) { |
| 173 | Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'vmconnect.exe') -ArgumentList @('localhost',$name) |
| 174 | Write-Output 'CAGE_GUEST_STAGE windows-11 oobe' |
| 175 | Write-Output '在虚拟机连接窗口完成 Windows 安装,用安装前设置的本地管理员登录桌面,再回 Cage 点击「已进入桌面,继续安装」。本轮 PowerShell 创建窗口会自动关闭。' |
| 176 | return |
| 177 | } |
| 178 | $componentsReady = (Test-Path -LiteralPath (Join-Path $instance 'cage-workbench/pair/workbench-components-ready')) -and |
| 179 | (Test-Path -LiteralPath (Join-Path $instance 'cage-workbench/pair/windows-guest.json')) |
| 180 | if ($fromHost -and $setupCredential -and !$published -and !$componentsReady) { Wait-CageWindowsSetup $vm.Id $setupCredential } |
| 181 | & (Join-Path $PSScriptRoot 'complete-windows-guest.ps1') -VMId $vm.Id -InstanceDirectory $instance -HostProfileDirectory $Profile -HostUserSID $HostUserSID -StateDirectory $state -HostEnrollment $HostEnrollment -ManifestPath $ManifestPath -ManifestSHA256 $ManifestSHA256 -GuestAdministrator $setupCredential |
| 182 | Write-Output 'CAGE_GUEST_STAGE windows-11 services' |