| 1 | #requires -Version 5.1 |
| 2 | # Functions used only for a new private Windows guest disk. |
| 3 | function New-CageISOAnswer([pscredential]$Administrator) { |
| 4 | if (!$Administrator -or $Administrator.UserName.Length -gt 20 -or |
| 5 | $Administrator.UserName -match '["/\\\[\]:;|=,+*?<>@\x00-\x1f]' -or |
| 6 | $Administrator.UserName.Trim() -cne $Administrator.UserName -or $Administrator.UserName.EndsWith('.') -or |
| 7 | $Administrator.UserName -in @('Administrator', 'Guest', 'DefaultAccount', 'WDAGUtilityAccount', 'cagesetup') -or |
| 8 | $Administrator.Password.Length -eq 0) { |
| 9 | throw '请输入新的客机本地管理员名称和非空密码。用户名最多 20 个字符,请使用普通本地名称。' |
| 10 | } |
| 11 | $answer = [xml]@' |
| 12 | <unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"> |
| 13 | <settings pass="specialize"/> |
| 14 | <settings pass="oobeSystem"> |
| 15 | <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> |
| 16 | <OOBE><HideOnlineAccountScreens>true</HideOnlineAccountScreens><HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE></OOBE> |
| 17 | <UserAccounts><LocalAccounts><LocalAccount wcm:action="add"><Name/><Description>Cage ISO initial administrator</Description><Group>Administrators</Group><Password><Value/><PlainText>true</PlainText></Password></LocalAccount></LocalAccounts></UserAccounts> |
| 18 | </component> |
| 19 | </settings> |
| 20 | </unattend> |
| 21 | '@ |
| 22 | $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable) |
| 23 | $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend') |
| 24 | $answer.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText = $Administrator.UserName |
| 25 | $answer.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText = $Administrator.GetNetworkCredential().Password |
| 26 | return $answer |
| 27 | } |
| 28 | |
| 29 | function Remove-CageISOAnswer($VM, $Session, [string]$InstanceDirectory) { |
| 30 | Invoke-Command -Session $Session -ArgumentList $VM.Id -ScriptBlock { |
| 31 | param($expected) |
| 32 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) { throw 'wrong guest' } |
| 33 | $setup = Get-ItemProperty 'HKLM:\SYSTEM\Setup' |
| 34 | if ($setup.SystemSetupInProgress -ne 0 -or $setup.OOBEInProgress -ne 0 -or !(Test-Path 'C:\Program Files\PowerShell\7\pwsh.exe')) { |
| 35 | throw '请在虚拟机连接窗口完成 Windows 首次设置并登录桌面,然后回 Cage 继续安装。' |
| 36 | } |
| 37 | foreach ($path in @('C:\Windows\Panther\Unattend.xml', 'C:\Windows\Panther\Unattend\Unattend.xml')) { |
| 38 | if (!(Test-Path -LiteralPath $path -PathType Leaf)) { continue } |
| 39 | try { $answer = [xml][IO.File]::ReadAllText($path) } |
| 40 | catch { continue } # Preserve an unrecognized answer without logging its contents. |
| 41 | $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable) |
| 42 | $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend') |
| 43 | if ($answer.SelectSingleNode('//u:LocalAccount[u:Description="Cage ISO initial administrator"]', $ns)) { |
| 44 | Remove-Item -LiteralPath $path -Force |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | $answerPath = Join-Path $InstanceDirectory 'windows-guest-tools.iso' |
| 49 | $VM | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $answerPath | Hyper-V\Remove-VMDvdDrive |
| 50 | [IO.File]::Delete($answerPath) |
| 51 | } |
| 52 | |
| 53 | function New-CageCloneAnswer([pscredential]$Administrator, [string]$Language) { |
| 54 | if (!$Administrator -or $Administrator.UserName -cne 'cagesetup' -or $Language -notmatch '^[a-zA-Z]{2,3}-[a-zA-Z0-9-]{2,12}$') { |
| 55 | throw 'The new guest setup identity or language is invalid.' |
| 56 | } |
| 57 | $answer = [xml]@' |
| 58 | <unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"> |
| 59 | <settings pass="specialize"> |
| 60 | <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> |
| 61 | <ComputerName>CAGE-WINDOWS</ComputerName><TimeZone>UTC</TimeZone> |
| 62 | </component> |
| 63 | </settings> |
| 64 | <settings pass="oobeSystem"> |
| 65 | <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> |
| 66 | <InputLocale>en-US</InputLocale><SystemLocale>en-US</SystemLocale><UILanguage>en-US</UILanguage><UserLocale>en-US</UserLocale> |
| 67 | </component> |
| 68 | <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS"> |
| 69 | <OOBE><HideEULAPage>true</HideEULAPage><HideOnlineAccountScreens>true</HideOnlineAccountScreens><HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE><ProtectYourPC>3</ProtectYourPC></OOBE> |
| 70 | <UserAccounts><LocalAccounts><LocalAccount wcm:action="add"><Name>cagesetup</Name><Group>Administrators</Group><Password><Value/><PlainText>true</PlainText></Password></LocalAccount></LocalAccounts></UserAccounts> |
| 71 | </component> |
| 72 | </settings> |
| 73 | </unattend> |
| 74 | '@ |
| 75 | $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable) |
| 76 | $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend') |
| 77 | foreach ($name in @('InputLocale', 'SystemLocale', 'UILanguage', 'UserLocale')) { |
| 78 | $answer.SelectSingleNode('//u:component[@name="Microsoft-Windows-International-Core"]/u:'+$name, $ns).InnerText = $Language |
| 79 | } |
| 80 | $answer.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText = $Administrator.GetNetworkCredential().Password |
| 81 | return $answer |
| 82 | } |
| 83 | |
| 84 | function Install-CageWindowsImage([string]$Image, [string]$Disk, [string]$Edition, [string]$Language, [xml]$Answer, [string]$Build) { |
| 85 | $candidates = @() |
| 86 | foreach ($summary in @(Get-WindowsImage -ImagePath $Image)) { |
| 87 | $details = Get-WindowsImage -ImagePath $Image -Index $summary.ImageIndex |
| 88 | if ($details.EditionId -eq $Edition -and [string]$details.Architecture -in @('9','amd64','x64') -and $details.Languages -contains $Language) { |
| 89 | $candidates += $details |
| 90 | } |
| 91 | } |
| 92 | if ($candidates.Count -ne 1) { throw 'The Windows image does not contain exactly one matching edition, architecture and language.' } |
| 93 | if ($Build -and [string]$candidates[0].Version -cne ('10.0.'+$Build)) { throw 'The Windows image build differs from the selected installation preview.' } |
| 94 | $mount = $null |
| 95 | try { |
| 96 | $mount = Mount-VHD -Path $Disk -Passthru |
| 97 | $target = Get-Disk -Number $mount.DiskNumber |
| 98 | if ($target.PartitionStyle -ne 'RAW' -or $target.IsBoot -or $target.IsSystem) { |
| 99 | throw 'Windows installation requires the newly created empty virtual disk.' |
| 100 | } |
| 101 | $target | Initialize-Disk -PartitionStyle GPT |
| 102 | $efi = $target | New-Partition -Size 260MB -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -AssignDriveLetter |
| 103 | $efi | Format-Volume -FileSystem FAT32 -NewFileSystemLabel CAGE_BOOT -Confirm:$false | Out-Null |
| 104 | $target | New-Partition -Size 16MB -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}' | Out-Null |
| 105 | $windows = $target | New-Partition -UseMaximumSize -AssignDriveLetter |
| 106 | $windows | Format-Volume -FileSystem NTFS -NewFileSystemLabel CAGE_WINDOWS -Confirm:$false | Out-Null |
| 107 | $destination = $windows.DriveLetter + ':\' |
| 108 | Write-Output '正在将匹配本机版本的干净 Windows 写入独立虚拟磁盘…' |
| 109 | Expand-WindowsImage -ImagePath $Image -Index $candidates[0].ImageIndex -ApplyPath $destination -Compact -CheckIntegrity | Out-Null |
| 110 | $panther = Join-Path $destination 'Windows\Panther' |
| 111 | $null = [IO.Directory]::CreateDirectory($panther) |
| 112 | $Answer.Save((Join-Path $panther 'Unattend.xml')) |
| 113 | $boot = Join-Path ([Environment]::GetFolderPath('System')) 'bcdboot.exe' |
| 114 | & $boot (Join-Path $destination 'Windows') /s ($efi.DriveLetter+':') /f UEFI |
| 115 | if ($LASTEXITCODE -ne 0) { throw 'Could not prepare the new guest virtual disk boot files.' } |
| 116 | } finally { |
| 117 | if ($mount) { Dismount-VHD -Path $Disk } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | function Get-CageSetupCredential([string]$Profile, [guid]$InstallationID) { |
| 122 | $path = Join-Path $Profile ('windows-setup-'+$InstallationID.ToString('N')+'.dpapi') |
| 123 | if (Test-Path -LiteralPath $path) { |
| 124 | $item = Get-Item -LiteralPath $path -Force |
| 125 | if ($item -isnot [IO.FileInfo] -or $item.Length -gt 16384 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint) { |
| 126 | throw 'The saved guest setup credential is invalid.' |
| 127 | } |
| 128 | $password = Get-Content -LiteralPath $path -Raw | ConvertTo-SecureString |
| 129 | } else { |
| 130 | $instance = Join-Path (Join-Path $Profile 'state') ('windows-'+$InstallationID.ToString('N')) |
| 131 | $receipt = Join-Path $Profile 'windows-install-vm.txt' |
| 132 | $stagedBinding = Join-Path $instance 'cage-workbench/pair/windows-guest.json' |
| 133 | if ((Test-Path -LiteralPath $receipt -PathType Leaf) -and |
| 134 | (Test-Path -LiteralPath (Join-Path $instance 'cage-workbench/pair/workbench-components-ready')) -and |
| 135 | (Test-CageSetupAccountDisabled ([guid][IO.File]::ReadAllText($receipt)) $stagedBinding)) { |
| 136 | return $null |
| 137 | } |
| 138 | if ((Test-Path -LiteralPath $receipt) -or (Test-Path -LiteralPath $instance)) { |
| 139 | throw 'The saved setup credential for this Windows guest is missing. Restore the original encrypted credential to continue with its existing account and disk.' |
| 140 | } |
| 141 | $random = New-Object byte[] 32 |
| 142 | $generator = [Security.Cryptography.RandomNumberGenerator]::Create() |
| 143 | try { $generator.GetBytes($random); $password = ConvertTo-SecureString ('Cg!'+[Convert]::ToBase64String($random)) -AsPlainText -Force } |
| 144 | finally { $generator.Dispose(); [Array]::Clear($random,0,$random.Length) } |
| 145 | $encrypted = ConvertFrom-SecureString $password |
| 146 | $file = [IO.File]::Open($path, 'CreateNew', 'Write', 'None') |
| 147 | try { |
| 148 | $bytes = [Text.Encoding]::UTF8.GetBytes($encrypted) |
| 149 | $file.Write($bytes,0,$bytes.Length) |
| 150 | } finally { $file.Dispose() } |
| 151 | } |
| 152 | return [pscredential]::new('cagesetup', $password) |
| 153 | } |
| 154 | |
| 155 | function Wait-CageWindowsSetup([guid]$VMId, [pscredential]$Credential) { |
| 156 | $deadline = [DateTime]::UtcNow.AddMinutes(20) |
| 157 | Write-Output '正在等待 Windows 完成首次设置…' |
| 158 | do { |
| 159 | $session = $null |
| 160 | try { |
| 161 | $session = New-PSSession -VMId $VMId -Credential $Credential -ErrorAction Stop |
| 162 | $ready = Invoke-Command -Session $session -ArgumentList $VMId -ScriptBlock { |
| 163 | param($expected) |
| 164 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) { throw 'wrong guest' } |
| 165 | $setup = Get-ItemProperty 'HKLM:\SYSTEM\Setup' |
| 166 | $setup.SystemSetupInProgress -eq 0 -and $setup.OOBEInProgress -eq 0 -and (Test-Path 'C:\Program Files\PowerShell\7\pwsh.exe') |
| 167 | } |
| 168 | if ($ready) { return } |
| 169 | } catch { Write-Verbose $_ } |
| 170 | finally { if ($session) { Remove-PSSession $session } } |
| 171 | Start-Sleep -Seconds 3 |
| 172 | } while ([DateTime]::UtcNow -lt $deadline) |
| 173 | throw 'Windows setup is still incomplete. The private disk and progress are saved. Continue installation from Cage.' |
| 174 | } |
| 175 | |
| 176 | function Test-CageSetupAccountDisabled([guid]$VMId, [string]$Binding) { |
| 177 | if (!(Test-Path -LiteralPath $binding -PathType Leaf)) { return $false } |
| 178 | $relay = Join-Path $PSScriptRoot 'payload/Cage.GuestClipboard.exe' |
| 179 | $savedPreference = $ErrorActionPreference |
| 180 | try { |
| 181 | $ErrorActionPreference = 'Continue' |
| 182 | $raw = & $relay --relay-profile $binding status 2>$null |
| 183 | if ($LASTEXITCODE -ne 0 -or !$raw) { return $false } |
| 184 | $status = $raw | ConvertFrom-Json -ErrorAction Stop |
| 185 | return [guid]$status.vm_id -eq $VMId -and $status.setup_account_disabled -is [bool] -and $status.setup_account_disabled |
| 186 | } catch { return $false } |
| 187 | finally { $ErrorActionPreference = $savedPreference } |
| 188 | } |
| 189 | |
| 190 | function Remove-CageSetupCredential([guid]$VMId, [pscredential]$Credential, [string]$Profile, [guid]$InstallationID, [string]$Binding) { |
| 191 | $path = Join-Path $Profile ('windows-setup-'+$InstallationID.ToString('N')+'.dpapi') |
| 192 | if (!$Binding) { $Binding = Join-Path $Profile 'windows-guest.json' } |
| 193 | # A crash can occur after guest retirement but before the host deletes its |
| 194 | # encrypted copy. The paired standard-user channel can prove that state. |
| 195 | if (Test-CageSetupAccountDisabled $VMId $Binding) { |
| 196 | [IO.File]::Delete($path) |
| 197 | return |
| 198 | } |
| 199 | if (!$Credential) { throw 'The setup account retirement could not be verified. Its existing account and disk were preserved.' } |
| 200 | $session = New-PSSession -VMId $VMId -Credential $Credential |
| 201 | try { |
| 202 | Invoke-Command -Session $session -ArgumentList $VMId -ScriptBlock { |
| 203 | param($expected) |
| 204 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) { throw 'wrong guest' } |
| 205 | foreach ($path in @('C:\Windows\Panther\Unattend.xml', 'C:\Windows\Panther\Unattend\Unattend.xml')) { |
| 206 | if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force } |
| 207 | } |
| 208 | Disable-LocalUser -Name cagesetup |
| 209 | } |
| 210 | } finally { Remove-PSSession $session } |
| 211 | [IO.File]::Delete($path) |
| 212 | } |