| 1 | #requires -Version 5.1 |
| 2 | #requires -RunAsAdministrator |
| 3 | [CmdletBinding(SupportsShouldProcess)] |
| 4 | param( |
| 5 | [Parameter(Mandatory)][guid]$VMId, |
| 6 | [Parameter(Mandatory)][string]$HostSID, |
| 7 | [Parameter(Mandatory)][string]$PayloadExecutable, |
| 8 | [Parameter(Mandatory)][ValidatePattern('^[0-9a-fA-F]{64}$')][string]$PayloadSHA256 |
| 9 | ) |
| 10 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 11 | if($VMId -eq [guid]::Empty -or $HostSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$'){throw 'Select the exact VM and authorized host user.'} |
| 12 | # HostSID is the ordinary Cage user's identity carried across its UAC boundary. |
| 13 | # The administrator may be another account; its SID is never substituted here. |
| 14 | function Assert-NoLink([string]$Path){ |
| 15 | $item=Get-Item -LiteralPath $Path -Force |
| 16 | while($item){if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager files cannot traverse links.'};if($item -is [IO.FileInfo]){$item=$item.Directory}else{$item=$item.Parent}} |
| 17 | } |
| 18 | function Protect-ManagerPath([string]$Path,[switch]$Shared){ |
| 19 | $item=Get-Item -LiteralPath $Path -Force |
| 20 | if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager paths cannot be links.'} |
| 21 | if($item -is [IO.DirectoryInfo]){$acl=[Security.AccessControl.DirectorySecurity]::new()}else{$acl=[Security.AccessControl.FileSecurity]::new()} |
| 22 | $acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'));$acl.SetAccessRuleProtection($true,$false) |
| 23 | $reader=if($Shared){'S-1-5-32-545'}else{$HostSID} |
| 24 | foreach($id in @('S-1-5-18','S-1-5-32-544',$reader)){ |
| 25 | $rights=if($id -ceq $reader){'ReadAndExecute'}else{'FullControl'} |
| 26 | if($item -is [IO.DirectoryInfo]){$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'ContainerInherit,ObjectInherit','None','Allow')}else{$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'Allow')} |
| 27 | $acl.AddAccessRule($rule) |
| 28 | } |
| 29 | Set-Acl -LiteralPath $Path -AclObject $acl |
| 30 | } |
| 31 | $payload=Get-Item -LiteralPath $PayloadExecutable |
| 32 | if($payload -isnot [IO.FileInfo]){throw 'Select the built manager executable.'};Assert-NoLink $payload.FullName |
| 33 | if((Get-FileHash $payload.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Manager payload checksum does not match.'} |
| 34 | $programRoot=Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'Cage Host Manager' |
| 35 | $program=Join-Path $programRoot $VMId.ToString('D');$exe=Join-Path $program 'Cage.HyperVManager.exe' |
| 36 | $cageDataRoot=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'Cage' |
| 37 | $dataRoot=Join-Path $cageDataRoot 'HyperVManager' |
| 38 | $data=Join-Path $dataRoot $VMId.ToString('D');$bindingPath=Join-Path $data 'binding.json' |
| 39 | $name='CageHV-'+$VMId.ToString('D');$binary='"'+$exe+'" service --binding "'+$bindingPath+'"' |
| 40 | if(!$PSCmdlet.ShouldProcess($VMId,'Install the protected local fixed-VM manager; keep VM, disks, accounts and host networking')){return} |
| 41 | foreach($path in @($programRoot,$program,$cageDataRoot,$dataRoot,$data)){ |
| 42 | if(!(Test-Path -LiteralPath $path)){New-Item -ItemType Directory -Path $path|Out-Null};Assert-NoLink $path |
| 43 | Protect-ManagerPath $path -Shared:($path -in @($programRoot,$cageDataRoot,$dataRoot)) |
| 44 | } |
| 45 | $prepare=Join-Path $program ('manager-prepare-'+[guid]::NewGuid().ToString('N')+'.exe') |
| 46 | try{ |
| 47 | # Hash and execute the same protected copy. The caller's original payload |
| 48 | # may change while setup runs; it never becomes an execution authority. |
| 49 | Copy-Item -LiteralPath $payload.FullName -Destination $prepare |
| 50 | Protect-ManagerPath $prepare |
| 51 | if((Get-FileHash $prepare -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Protected manager preparation checksum does not match.'} |
| 52 | $payload=Get-Item -LiteralPath $prepare |
| 53 | $service=Get-Service -Name $name -ErrorAction SilentlyContinue |
| 54 | if($service){ |
| 55 | $existing=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") |
| 56 | if($existing.PathName -cne $binary -or $existing.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM')){throw 'An unrelated service already uses this name.'} |
| 57 | } |
| 58 | # Existing installations retain their protected authority and recovery journal. |
| 59 | # They can repair a stopped helper while its bound data volume is disconnected. |
| 60 | # Fresh registration verifies the actual VM using the protected payload copy. |
| 61 | $operation=if(Test-Path -LiteralPath $bindingPath){'binding'}else{'prepare'} |
| 62 | $raw=& $payload.FullName $operation --vm-id $VMId.ToString('D') --host-sid $HostSID |
| 63 | if($LASTEXITCODE -ne 0){throw 'The exact VM/disk binding could not be verified.'} |
| 64 | $binding=$raw|ConvertFrom-Json |
| 65 | if($binding.version -ne 1 -or [guid]$binding.vm_id -ne $VMId -or $binding.host_sid -cne $HostSID){throw 'The prepared manager binding does not match.'} |
| 66 | if(Test-Path -LiteralPath $bindingPath){ |
| 67 | Assert-NoLink $bindingPath;$old=Get-Content -LiteralPath $bindingPath -Raw|ConvertFrom-Json |
| 68 | foreach($key in @('version','vm_id','host_sid','disk_path','disk_volume','disk_file_id')){if([string]$old.$key -cne [string]$binding.$key){throw 'The existing protected VM/disk binding changed; preserved it.'}} |
| 69 | } |
| 70 | $rollback=$null;$cleanupRollback=$false;$wasRunning=$service -and $service.Status -eq 'Running' |
| 71 | try{ |
| 72 | if($service){ |
| 73 | Assert-NoLink $exe |
| 74 | $rollback=Join-Path $program ('manager-rollback-'+[guid]::NewGuid().ToString('N')+'.exe') |
| 75 | Copy-Item -LiteralPath $exe -Destination $rollback;Protect-ManagerPath $rollback |
| 76 | if($service.Status -ne 'Stopped'){Stop-Service -Name $name;$service.WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))} |
| 77 | } |
| 78 | Copy-Item -LiteralPath $payload.FullName -Destination $exe -Force;Protect-ManagerPath $exe |
| 79 | if((Get-FileHash $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'The copied manager checksum does not match.'} |
| 80 | if(!(Test-Path -LiteralPath $bindingPath)){[IO.File]::WriteAllText($bindingPath,($binding|ConvertTo-Json -Depth 4),[Text.UTF8Encoding]::new($false))} |
| 81 | Protect-ManagerPath $bindingPath |
| 82 | if(!$service){New-Service -Name $name -BinaryPathName $binary -StartupType Automatic -DisplayName ('Cage fixed VM manager '+$VMId.ToString('D')) -Description ('Cage protected local VM manager '+$VMId.ToString('D'))|Out-Null} |
| 83 | $sddl='O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;CCLCRP;;;'+$HostSID+')' |
| 84 | & ($env:windir+'\System32\sc.exe') sdset $name $sddl|Out-Null |
| 85 | if($LASTEXITCODE -ne 0){throw 'The manager service permission could not be protected.'} |
| 86 | & ($env:windir+'\System32\sc.exe') failure $name reset= 86400 actions= restart/5000/restart/15000/restart/60000|Out-Null |
| 87 | if($LASTEXITCODE -ne 0){throw 'The manager recovery policy could not be configured.'} |
| 88 | Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus('Running',[TimeSpan]::FromSeconds(30)) |
| 89 | $cleanupRollback=$true |
| 90 | }catch{ |
| 91 | if($rollback){ |
| 92 | Stop-Service -Name $name -ErrorAction SilentlyContinue |
| 93 | (Get-Service -Name $name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30)) |
| 94 | Copy-Item -LiteralPath $rollback -Destination $exe -Force;Protect-ManagerPath $exe |
| 95 | if($wasRunning){Start-Service -Name $name} |
| 96 | $cleanupRollback=$true |
| 97 | } |
| 98 | throw |
| 99 | }finally{if($rollback -and $cleanupRollback -and (Test-Path -LiteralPath $rollback)){Remove-Item -LiteralPath $rollback}} |
| 100 | [pscustomobject]@{Installed=$true;VMId=$VMId.ToString('D');HostSID=$HostSID;LocalPipeOnly=$true;VMDataPreserved=$true;HostGroupsUnchanged=$true;ServiceRunning=$true} |
| 101 | }finally{if(Test-Path -LiteralPath $prepare){Remove-Item -LiteralPath $prepare}} |