| 1 | #requires -Version 5.1 |
| 2 | #requires -RunAsAdministrator |
| 3 | <# |
| 4 | .SYNOPSIS |
| 5 | Bind one existing offline Hyper-V guest and its existing interactive user. |
| 6 | .DESCRIPTION |
| 7 | PowerShell Direct is only the authenticated management transport. The agent is |
| 8 | registered as an InteractiveToken, Limited task for the supplied SID; it cannot |
| 9 | use a management/Session0 clipboard. This script does not log a user in, create |
| 10 | accounts, change VM networking, accept licenses or replace a running agent. |
| 11 | Supply a new protected host profile directory. The returned binding contains |
| 12 | only paths and identities; its separate pairing is DPAPI CurrentUser protected. |
| 13 | #> |
| 14 | [CmdletBinding(SupportsShouldProcess)] |
| 15 | param( |
| 16 | [Parameter(Mandatory)][guid]$VMId, |
| 17 | [Parameter(Mandatory)][string]$InstanceDirectory, |
| 18 | [Parameter(Mandatory)][ValidatePattern('^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$')][string]$GUIUserSID, |
| 19 | [Parameter(Mandatory)][pscredential]$GuestAdministrator, |
| 20 | [Parameter(Mandatory)][string]$PayloadDirectory, |
| 21 | [Parameter(Mandatory)][string]$HostProfileDirectory, |
| 22 | [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value), |
| 23 | [object]$HostEnrollment |
| 24 | ) |
| 25 | $ErrorActionPreference='Stop' |
| 26 | $ProgressPreference='SilentlyContinue' |
| 27 | if($HostUserSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$' -or |
| 28 | ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment)){throw 'Another host user requires the original enrollment process.'} |
| 29 | if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId)){throw 'Original host enrollment does not match this bridge.'} |
| 30 | $service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa' |
| 31 | function Assert-LocalAncestors([string]$Path){ |
| 32 | if(![IO.Path]::IsPathRooted($Path) -or $Path.StartsWith('\\') -or [IO.DriveInfo]::new([IO.Path]::GetPathRoot($Path)).DriveType -ne 'Fixed'){throw 'A local fixed-disk path is required.'} |
| 33 | $current=$Path |
| 34 | while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)} |
| 35 | } |
| 36 | $vm=Get-VM -Id $VMId |
| 37 | $instance=Get-Item -LiteralPath $InstanceDirectory |
| 38 | $payload=Get-Item -LiteralPath $PayloadDirectory |
| 39 | if ($VMId -eq [guid]::Empty -or $vm.State -ne 'Running' -or $instance -isnot [IO.DirectoryInfo] -or |
| 40 | $payload -isnot [IO.DirectoryInfo] -or $instance.Attributes -band [IO.FileAttributes]::ReparsePoint -or |
| 41 | !($vm.ConfigurationLocation -eq $instance.FullName -or $vm.ConfigurationLocation.StartsWith($instance.FullName.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or |
| 42 | @(Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Supply the exact running, retained zero-NIC guest and its private instance directory.' } |
| 43 | $profile=$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($HostProfileDirectory) |
| 44 | foreach($path in @($profile,$instance.FullName,$payload.FullName)){Assert-LocalAncestors $path} |
| 45 | if (!(Test-Path -LiteralPath ([IO.Path]::GetDirectoryName($profile))) -or (Test-Path -LiteralPath $profile)) { throw 'Supply a new host profile directory under an existing local parent.' } |
| 46 | foreach($file in @('Cage.GuestClipboard.exe','cage-guest-files.exe')) { |
| 47 | $entry=Get-Item -LiteralPath (Join-Path $payload.FullName $file) |
| 48 | if($entry -isnot [IO.FileInfo] -or $entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'The fixed GUI agent and file helper payloads are required.'} |
| 49 | } |
| 50 | if(!$PSCmdlet.ShouldProcess($VMId,'Install a protected GUI clipboard bridge and bind this host user')){return} |
| 51 | $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator |
| 52 | try { |
| 53 | $checked=Invoke-Command -Session $session -ArgumentList $VMId,$GUIUserSID -ScriptBlock { |
| 54 | param($expected,$sid) |
| 55 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 56 | $kvp=Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId |
| 57 | if([guid]$kvp.VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} |
| 58 | $users=@(Get-LocalUser | Where-Object {$_.SID.Value -eq $sid -and $_.Enabled}) |
| 59 | if($users.Count -ne 1){throw 'The independently selected GUI SID is not an enabled existing local user.'} |
| 60 | $name="Cage-GUI-Bridge-$expected-$sid" |
| 61 | if(Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue){throw 'A bridge task already exists; preserve the running user session and use its existing binding.'} |
| 62 | $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected) |
| 63 | $data=Join-Path $env:ProgramData ("Cage\GuestBridge\"+$expected) |
| 64 | foreach($directory in @($program,$data)){$current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)}} |
| 65 | if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data)){throw 'A guest bridge deployment already exists; preserve it.'} |
| 66 | foreach($directory in @($program,$data)){ |
| 67 | $null=New-Item -ItemType Directory -Path $directory -Force |
| 68 | $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false) |
| 69 | foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','ContainerInherit,ObjectInherit','None','Allow'))} |
| 70 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')) |
| 71 | Set-Acl -LiteralPath $directory -AclObject $acl |
| 72 | } |
| 73 | [pscustomobject]@{Program=$program;Data=$data;Task=$name;User=$users[0].Name} |
| 74 | } |
| 75 | # Copy only the caller-selected payload directory. Optional Node/browser |
| 76 | # dependencies remain local to this deployment and never need a guest NIC. |
| 77 | Get-ChildItem -LiteralPath $payload.FullName -File|ForEach-Object { |
| 78 | if($_.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'} |
| 79 | Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $checked.Program $_.Name) -ToSession $session |
| 80 | } |
| 81 | $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose() |
| 82 | try { |
| 83 | Invoke-Command -Session $session -ArgumentList $checked.Data,$secret,$GUIUserSID -ScriptBlock { |
| 84 | param($data,[byte[]]$secret,$sid) |
| 85 | $file=Join-Path $data 'pairing.bin';[IO.File]::WriteAllBytes($file,$secret) |
| 86 | $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false) |
| 87 | foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','Allow'))} |
| 88 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'Read','Allow'));Set-Acl -LiteralPath $file -AclObject $acl |
| 89 | } |
| 90 | $hostSID=[Security.Principal.SecurityIdentifier]::new($HostUserSID) |
| 91 | $hostOwner=if($HostEnrollment){[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')}else{$hostSID} |
| 92 | $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($hostOwner) |
| 93 | foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))} |
| 94 | $null=New-Item -ItemType Directory -Path $profile;Set-Acl -LiteralPath $profile -AclObject $acl |
| 95 | foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -File)){Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $profile $entry.Name)} |
| 96 | Add-Type -AssemblyName System.Security |
| 97 | $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($VMId.ToString('D')):$GUIUserSID")) |
| 98 | $pairing=Join-Path $profile 'pairing.dpapi' |
| 99 | # The relay verifies protected file ACLs independently before decrypting. |
| 100 | $fileACL=[Security.AccessControl.FileSecurity]::new();$fileACL.SetAccessRuleProtection($true,$false);$fileACL.SetOwner($hostOwner) |
| 101 | foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$fileACL.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow'))} |
| 102 | if(!$HostEnrollment){[IO.File]::WriteAllBytes($pairing,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pairing -AclObject $fileACL} |
| 103 | $key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service" |
| 104 | if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage GUI Guest Bridge v1'){throw 'The fixed service GUID is owned by another application.'}} |
| 105 | else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage GUI Guest Bridge v1' -PropertyType String|Out-Null} |
| 106 | $task=Invoke-Command -Session $session -ArgumentList $checked.Program,$checked.Data,$checked.Task,$GUIUserSID,$VMId -ScriptBlock { |
| 107 | param($program,$data,$name,$sid,$vm) |
| 108 | $executable=Join-Path $program 'Cage.GuestClipboard.exe';$token=Join-Path $data 'pairing.bin' |
| 109 | $action=New-ScheduledTaskAction -Execute $executable -Argument "serve --vm-id $vm --sid $sid --token-file `"$token`"" |
| 110 | $trigger=New-ScheduledTaskTrigger -AtLogOn -User $sid |
| 111 | $principal=New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited |
| 112 | $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew |
| 113 | $null=Register-ScheduledTask -TaskName $name -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Cage protected GUI bridge $vm $sid" |
| 114 | $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 |
| 115 | if($gui){Start-ScheduledTask -TaskName $name} |
| 116 | [pscustomobject]@{Registered=$true;GUIAlreadyLoggedIn=$gui} |
| 117 | } |
| 118 | $binding=[ordered]@{version=1;vm_id=$VMId.ToString('D');gui_user_sid=$GUIUserSID;gui_user=$checked.User;instance_directory=$instance.FullName;relay_executable=(Join-Path $profile 'Cage.GuestClipboard.exe');pairing_file=$pairing} |
| 119 | $path=Join-Path $profile 'windows-guest.json';[IO.File]::WriteAllText($path,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $path -AclObject $fileACL |
| 120 | if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'gui' $GUIUserSID $secret} |
| 121 | if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $VMId)).Count -ne 0){throw 'VM networking changed during deployment.'} |
| 122 | [pscustomobject]@{Profile=$path;VMId=$VMId;GUIUserSID=$GUIUserSID;TaskRegistered=$task.Registered;RequiresGUILogin=(!$task.GUIAlreadyLoggedIn)} |
| 123 | } finally { [Array]::Clear($secret,0,$secret.Length) } |
| 124 | } finally { Remove-PSSession $session } |