| 1 | #requires -Version 5.1 |
| 2 | #requires -RunAsAdministrator |
| 3 | [CmdletBinding(SupportsShouldProcess)] |
| 4 | param( |
| 5 | [Parameter(Mandatory)][string]$ProfilePath, |
| 6 | [Parameter(Mandatory)][string]$PayloadDirectory, |
| 7 | [Parameter(Mandatory)][pscredential]$GuestAdministrator, |
| 8 | [switch]$RestartActiveBridge, |
| 9 | [switch]$GuestOnly |
| 10 | ) |
| 11 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 12 | $profile=Get-Item -LiteralPath $ProfilePath |
| 13 | if($profile -isnot [IO.FileInfo] -or $profile.Length -gt 16384 -or $profile.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Invalid protected guest binding.'} |
| 14 | $binding=Get-Content -LiteralPath $profile.FullName -Raw|ConvertFrom-Json |
| 15 | $vm=Get-VM -Id ([guid]$binding.vm_id) |
| 16 | if($binding.version -ne 1 -or $vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or |
| 17 | $profile.Directory.FullName -ne [IO.Path]::GetDirectoryName($binding.relay_executable) -or |
| 18 | !(Test-Path -LiteralPath $binding.pairing_file)){throw 'The existing VM/profile binding is not usable.'} |
| 19 | $payload=Get-Item -LiteralPath $PayloadDirectory |
| 20 | if($payload -isnot [IO.DirectoryInfo] -or $payload.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Select a local payload directory.'} |
| 21 | foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Recurse -Force)){if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'}} |
| 22 | foreach($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe')){if(!(Test-Path -LiteralPath (Join-Path $payload.FullName $name))){throw 'The fixed bridge payloads are required.'}} |
| 23 | if(!$GuestOnly){ |
| 24 | # A running packet or clipboard relay maps this host executable. Detect |
| 25 | # that conflict before stopping the independent guest GUI agent. |
| 26 | $image=[IO.Path]::GetFileNameWithoutExtension($binding.relay_executable) |
| 27 | foreach($process in [Diagnostics.Process]::GetProcessesByName($image)){ |
| 28 | try { if($process.MainModule.FileName -ieq $binding.relay_executable){throw 'The bound host relay is active. Close its associated workbench before a full update, or use GuestOnly with a compatible host relay.'} } |
| 29 | finally { $process.Dispose() } |
| 30 | } |
| 31 | } |
| 32 | if(!$PSCmdlet.ShouldProcess($vm.Id,'Update only the independently bound guest bridge application files')){return} |
| 33 | $session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator |
| 34 | $deployment=$null |
| 35 | try { |
| 36 | $deployment=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid,[bool]$RestartActiveBridge -ScriptBlock { |
| 37 | param($expected,$sid,$restart) |
| 38 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 39 | if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} |
| 40 | $name="Cage-GUI-Bridge-$expected-$sid";$task=Get-ScheduledTask -TaskName $name |
| 41 | $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected) |
| 42 | $actualSID=([Security.Principal.NTAccount]::new($task.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value |
| 43 | if($task.Description -cne "Cage protected GUI bridge $expected $sid" -or $actualSID -ne $sid -or |
| 44 | $task.Principal.RunLevel -ne 'Limited' -or $task.Principal.LogonType -ne 'Interactive' -or |
| 45 | $task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ine (Join-Path $program 'Cage.GuestClipboard.exe')){throw 'The GUI task does not match the owned deployment.'} |
| 46 | $active=$task.State -eq 'Running' |
| 47 | if($active -and !$restart){throw 'The bridge is active. Close its workbench before updating, or explicitly request RestartActiveBridge.'} |
| 48 | if($active){ |
| 49 | Stop-ScheduledTask -InputObject $task |
| 50 | $until=[DateTime]::UtcNow.AddSeconds(10) |
| 51 | while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100} |
| 52 | if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned bridge did not stop; preserved its application files.'} |
| 53 | } |
| 54 | [pscustomobject]@{Program=$program;Task=$name;WasActive=$active} |
| 55 | } |
| 56 | foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $deployment.Program -Recurse -ToSession $session -Force} |
| 57 | if(!$GuestOnly){foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $profile.Directory.FullName -Recurse -Force}} |
| 58 | $started=Invoke-Command -Session $session -ArgumentList $deployment.Task,$binding.gui_user_sid,$deployment.Program -ScriptBlock { |
| 59 | param($name,$sid,$program) |
| 60 | $administrators=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') |
| 61 | foreach($entry in @((Get-Item -LiteralPath $program)) + @(Get-ChildItem -LiteralPath $program -Recurse -Force)){ |
| 62 | if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest application files must not traverse links.'} |
| 63 | $acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($administrators);Set-Acl -LiteralPath $entry.FullName -AclObject $acl |
| 64 | } |
| 65 | $gui=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'"|Where-Object {$_.SessionId -gt 0}|ForEach-Object{Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid}|Where-Object {$_.Sid -eq $sid}).Count -gt 0 |
| 66 | if($gui){Start-ScheduledTask -TaskName $name};$gui |
| 67 | } |
| 68 | if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'VM networking changed during update.'} |
| 69 | [pscustomobject]@{Updated=$true;HostRelayUpdated=(!$GuestOnly);RequiresGUILogin=(!$started);PairingPreserved=$true;PersonalDataPreserved=$true} |
| 70 | } catch { |
| 71 | $failure=$_ |
| 72 | if($deployment -and $deployment.WasActive -and $session.State -eq 'Opened'){ |
| 73 | try { |
| 74 | Invoke-Command -Session $session -ArgumentList $deployment.Task,$deployment.Program -ScriptBlock { |
| 75 | param($name,$program) |
| 76 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 77 | $exe=Join-Path $program 'Cage.GuestClipboard.exe' |
| 78 | if((Get-Item -LiteralPath $exe).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Bridge executable changed to a link.'} |
| 79 | # Do not launch a truncated executable after a failed copy. |
| 80 | & $exe self-test | Out-Null |
| 81 | if($LASTEXITCODE -ne 0){throw 'The copied bridge failed its self-test.'} |
| 82 | Start-ScheduledTask -TaskName $name |
| 83 | } | Out-Null |
| 84 | } catch { throw 'The bridge update failed and its GUI task could not be restored; preserve the binding and application files for recovery.' } |
| 85 | } |
| 86 | throw $failure |
| 87 | } finally { Remove-PSSession $session } |