| 1 | #requires -Version 5.1 |
| 2 | #requires -RunAsAdministrator |
| 3 | [CmdletBinding(SupportsShouldProcess)] |
| 4 | param( |
| 5 | [Parameter(Mandatory)][string]$ProfilePath, |
| 6 | [Parameter(Mandatory)][pscredential]$GuestAdministrator, |
| 7 | [Parameter(Mandatory)][string]$AgentPath, |
| 8 | [Parameter(Mandatory)][string]$WintunPath, |
| 9 | [Parameter(Mandatory)][string]$WintunLicense, |
| 10 | [object]$HostEnrollment |
| 11 | ) |
| 12 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 13 | $binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json |
| 14 | if($HostEnrollment -and [guid]$HostEnrollment.VMID -ne [guid]$binding.vm_id){throw 'Original host enrollment does not match this packet bridge.'} |
| 15 | $vm=Get-VM -Id ([guid]$binding.vm_id) |
| 16 | if($binding.version -ne 1 -or $vm.State -ne 'Running' -or $binding.gui_user_sid -notmatch '^S-1-5-21-' -or |
| 17 | @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or $binding.network_pairing_file){throw 'Use the existing running zero-NIC guest binding without a prior packet pairing.'} |
| 18 | if((Get-FileHash -LiteralPath $WintunPath -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Unexpected pinned Wintun payload.'} |
| 19 | if((Get-AuthenticodeSignature -LiteralPath $WintunPath).Status -ne 'Valid'){throw 'Windows did not validate the official Wintun signature.'} |
| 20 | if(!$PSCmdlet.ShouldProcess($vm.Id,'Install the separate SYSTEM packet bridge without adding a Hyper-V NIC')){return} |
| 21 | $session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator |
| 22 | try { |
| 23 | $target=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock { |
| 24 | param($id,$sid) |
| 25 | $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' |
| 26 | if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $id){throw 'guest_identity_mismatch'} |
| 27 | $program=Join-Path $env:ProgramFiles ("Cage Guest Network\"+$id);$data=Join-Path $env:ProgramData ("Cage\PacketBridge\"+$id);$name="Cage-Packet-Bridge-$id" |
| 28 | if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data) -or (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue)){throw 'A packet deployment already exists; preserve its key and interface.'} |
| 29 | foreach($directory in @($program,$data)){ |
| 30 | $current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Packet deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)} |
| 31 | $null=New-Item -ItemType Directory -Path $directory -Force |
| 32 | $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) |
| 33 | 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'))} |
| 34 | if($directory -eq $program){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))} |
| 35 | Set-Acl -LiteralPath $directory -AclObject $acl |
| 36 | } |
| 37 | [pscustomobject]@{Program=$program;Data=$data;Task=$name} |
| 38 | } |
| 39 | Copy-Item -LiteralPath $AgentPath -Destination (Join-Path $target.Program 'Cage.GuestNetwork.exe') -ToSession $session |
| 40 | Copy-Item -LiteralPath $WintunPath -Destination (Join-Path $target.Program 'wintun.dll') -ToSession $session |
| 41 | Copy-Item -LiteralPath $WintunLicense -Destination (Join-Path $target.Program 'WINTUN-LICENSE.txt') -ToSession $session |
| 42 | $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose() |
| 43 | try { |
| 44 | Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$secret -ScriptBlock { |
| 45 | param($program,$data,[byte[]]$secret) |
| 46 | $ErrorActionPreference='Stop';$admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') |
| 47 | foreach($entry in (Get-ChildItem -LiteralPath $program -File)){$acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($admin);Set-Acl -LiteralPath $entry.FullName -AclObject $acl} |
| 48 | $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($admin) |
| 49 | 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'))} |
| 50 | $stream=[IO.FileStream]::new((Join-Path $data 'packet.bin'),[IO.FileMode]::CreateNew,[Security.AccessControl.FileSystemRights]::Write,[IO.FileShare]::None,4096,[IO.FileOptions]::None,$acl) |
| 51 | try{$stream.Write($secret,0,$secret.Length);$stream.Flush($true)}finally{$stream.Dispose()} |
| 52 | if((Get-FileHash -LiteralPath (Join-Path $program 'wintun.dll') -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Guest Wintun transfer digest differs.'} |
| 53 | } |
| 54 | Add-Type -AssemblyName System.Security |
| 55 | $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($vm.Id.ToString('D')):$($binding.gui_user_sid)")) |
| 56 | $pair=Join-Path ([IO.Path]::GetDirectoryName($ProfilePath)) 'packet.dpapi';if(Test-Path -LiteralPath $pair){throw 'A host packet pairing already exists.'} |
| 57 | if(!$HostEnrollment){[IO.File]::WriteAllBytes($pair,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pair -AclObject (Get-Acl -LiteralPath $binding.pairing_file)} |
| 58 | $service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb';$key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service" |
| 59 | if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage Packet Guest Bridge v1'){throw 'The packet service GUID is owned by another application.'}} |
| 60 | else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage Packet Guest Bridge v1' -PropertyType String|Out-Null} |
| 61 | Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$target.Task,$vm.Id,$binding.gui_user_sid -ScriptBlock { |
| 62 | param($program,$data,$name,$vm,$sid) |
| 63 | $exe=Join-Path $program 'Cage.GuestNetwork.exe';$key=Join-Path $data 'packet.bin' |
| 64 | $action=New-ScheduledTaskAction -Execute $exe -Argument "serve-network --vm-id $vm --sid $sid --token-file `"$key`"" |
| 65 | $principal=New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest |
| 66 | $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew |
| 67 | $null=Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger (New-ScheduledTaskTrigger -AtStartup) -Settings $settings -Description "Cage protected packet bridge $vm $sid" |
| 68 | } |
| 69 | $binding|Add-Member -NotePropertyName network_pairing_file -NotePropertyValue $pair |
| 70 | $stage=$ProfilePath+'.packet-stage';[IO.File]::WriteAllText($stage,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $stage -AclObject (Get-Acl -LiteralPath $ProfilePath);[IO.File]::Replace($stage,$ProfilePath,[Management.Automation.Language.NullString]::Value) |
| 71 | Invoke-Command -Session $session -ArgumentList $target.Task -ScriptBlock {param($name);Start-ScheduledTask -TaskName $name} |
| 72 | if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'packet' $binding.gui_user_sid $secret} |
| 73 | if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'Hyper-V networking changed during packet setup.'} |
| 74 | [pscustomobject]@{PacketTaskRegistered=$true;SystemKeyProtected=$true;IndependentHostPairing=$true;HyperVAdapters=0;NetworkConfigured=$false} |
| 75 | }finally{[Array]::Clear($secret,0,$secret.Length)} |
| 76 | }finally{Remove-PSSession $session} |