| 1 | #requires -Version 5.1 |
| 2 | # This module is dot-sourced by the fixed setup scripts. It exposes no general |
| 3 | # command, path or service RPC; raw pairing bytes stay inside the private pipe. |
| 4 | if(-not ('Cage.HostEnrollment.Native' -as [type])) { |
| 5 | Add-Type -TypeDefinition @' |
| 6 | using System; |
| 7 | using System.Runtime.InteropServices; |
| 8 | using System.Security.Principal; |
| 9 | using System.Text; |
| 10 | using Microsoft.Win32.SafeHandles; |
| 11 | namespace Cage.HostEnrollment { |
| 12 | public static class Native { |
| 13 | [StructLayout(LayoutKind.Sequential)] struct FileTime {public uint Low,High;} |
| 14 | [StructLayout(LayoutKind.Sequential)] struct Basic {public IntPtr Exit,Peb,Affinity,Priority,Pid,Parent;} |
| 15 | [DllImport("kernel32.dll",SetLastError=true)] public static extern IntPtr OpenProcess(uint access,bool inherit,uint pid); |
| 16 | [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle); |
| 17 | [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess(); |
| 18 | [DllImport("kernel32.dll",SetLastError=true)] public static extern bool DuplicateHandle(IntPtr sourceProcess,IntPtr source,IntPtr targetProcess,out IntPtr target,uint access,bool inherit,uint options); |
| 19 | [DllImport("kernel32.dll",SetLastError=true)] public static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe,out uint pid); |
| 20 | [DllImport("kernel32.dll",SetLastError=true)] static extern bool GetProcessTimes(IntPtr process,out FileTime created,out FileTime exited,out FileTime kernel,out FileTime user); |
| 21 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] static extern bool QueryFullProcessImageNameW(IntPtr process,uint flags,StringBuilder image,ref uint size); |
| 22 | [DllImport("kernel32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] static extern uint GetLongPathNameW(string path,StringBuilder expanded,uint capacity); |
| 23 | [DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token); |
| 24 | [DllImport("advapi32.dll",SetLastError=true)] static extern bool GetTokenInformation(IntPtr token,int kind,IntPtr data,uint bytes,out uint needed); |
| 25 | [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr process,int kind,out Basic basic,uint bytes,out uint needed); |
| 26 | public static long Started(uint pid) { |
| 27 | var p=OpenProcess(0x1000,false,pid);if(p==IntPtr.Zero)throw new InvalidOperationException("enrollment_peer_invalid"); |
| 28 | try {FileTime c,e,k,u;if(!GetProcessTimes(p,out c,out e,out k,out u))throw new InvalidOperationException("enrollment_peer_invalid");return (long)(((ulong)c.High<<32)|c.Low);}finally{CloseHandle(p);} |
| 29 | } |
| 30 | public static string Image(uint pid) { |
| 31 | var p=OpenProcess(0x1000,false,pid);if(p==IntPtr.Zero)throw new InvalidOperationException("enrollment_peer_invalid"); |
| 32 | try {var value=new StringBuilder(32768);uint n=(uint)value.Capacity;if(!QueryFullProcessImageNameW(p,0,value,ref n))throw new InvalidOperationException("enrollment_peer_invalid");return value.ToString();}finally{CloseHandle(p);} |
| 33 | } |
| 34 | static string LongPath(string path) { |
| 35 | var expanded=new StringBuilder(32768); |
| 36 | uint n=GetLongPathNameW(path,expanded,(uint)expanded.Capacity); |
| 37 | if(n==0||n>=expanded.Capacity)throw new InvalidOperationException("enrollment_image_path_unavailable"); |
| 38 | return expanded.ToString(); |
| 39 | } |
| 40 | public static bool SameImagePath(string actual,string expected) { |
| 41 | if(string.Equals(actual,expected,StringComparison.OrdinalIgnoreCase))return true; |
| 42 | // The kernel may report an 8.3 path for a process started by a long path. |
| 43 | return string.Equals(LongPath(actual),LongPath(expected),StringComparison.OrdinalIgnoreCase); |
| 44 | } |
| 45 | public static uint Parent(uint pid) { |
| 46 | var p=OpenProcess(0x1000,false,pid);if(p==IntPtr.Zero)throw new InvalidOperationException("enrollment_peer_invalid"); |
| 47 | try {Basic value;uint n;if(NtQueryInformationProcess(p,0,out value,(uint)Marshal.SizeOf(typeof(Basic)),out n)!=0)throw new InvalidOperationException("enrollment_peer_invalid");return checked((uint)value.Parent.ToInt64());}finally{CloseHandle(p);} |
| 48 | } |
| 49 | public static string UserSID(uint pid) { |
| 50 | var p=OpenProcess(0x1000,false,pid);if(p==IntPtr.Zero)throw new InvalidOperationException("enrollment_peer_invalid"); |
| 51 | IntPtr token=IntPtr.Zero,data=IntPtr.Zero; |
| 52 | try {uint n;if(!OpenProcessToken(p,8,out token))throw new InvalidOperationException("enrollment_peer_invalid");GetTokenInformation(token,1,IntPtr.Zero,0,out n);if(n==0||n>65536)throw new InvalidOperationException("enrollment_peer_invalid");data=Marshal.AllocHGlobal((int)n);if(!GetTokenInformation(token,1,data,n,out n))throw new InvalidOperationException("enrollment_peer_invalid");return new SecurityIdentifier(Marshal.ReadIntPtr(data)).Value;} |
| 53 | finally{if(data!=IntPtr.Zero)Marshal.FreeHGlobal(data);if(token!=IntPtr.Zero)CloseHandle(token);CloseHandle(p);} |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | '@ |
| 58 | } |
| 59 | |
| 60 | function Assert-CageHostEnrollmentPeer($Context,$Stream) { |
| 61 | [uint32]$serverPID=0 |
| 62 | if(![Cage.HostEnrollment.Native]::GetNamedPipeServerProcessId($Stream.SafePipeHandle,[ref]$serverPID) -or $serverPID -ne $Context.WorkerPID){throw 'The original host enrollment peer could not be verified.'} |
| 63 | if([Cage.HostEnrollment.Native]::Started($serverPID) -ne [long]$Context.WorkerStarted -or |
| 64 | ![Cage.HostEnrollment.Native]::SameImagePath([Cage.HostEnrollment.Native]::Image($serverPID),$Context.WorkerExe) -or |
| 65 | [Cage.HostEnrollment.Native]::UserSID($serverPID) -cne $Context.HostSID -or |
| 66 | [Cage.HostEnrollment.Native]::Parent($serverPID) -ne $Context.OwnerPID -or |
| 67 | [Cage.HostEnrollment.Native]::Started([uint32]$Context.OwnerPID) -ne [long]$Context.OwnerStarted -or |
| 68 | [Cage.HostEnrollment.Native]::UserSID([uint32]$Context.OwnerPID) -cne $Context.HostSID){throw 'The original host enrollment process changed.'} |
| 69 | } |
| 70 | |
| 71 | function Invoke-CageHostEnrollment($Context,[hashtable]$Request,[byte[]]$Secret) { |
| 72 | $deadline=[DateTime]::UtcNow.AddSeconds(12) |
| 73 | do { |
| 74 | $stream=[IO.Pipes.NamedPipeClientStream]::new('.',$Context.Pipe,[IO.Pipes.PipeDirection]::InOut,[IO.Pipes.PipeOptions]::Asynchronous,[Security.Principal.TokenImpersonationLevel]::Identification) |
| 75 | $reader=$null;$writer=$null |
| 76 | try { |
| 77 | $stream.Connect(3000);Assert-CageHostEnrollmentPeer $Context $stream |
| 78 | $reader=[IO.StreamReader]::new($stream,[Text.UTF8Encoding]::new($false),$false,4096,$true) |
| 79 | $writer=[IO.StreamWriter]::new($stream,[Text.UTF8Encoding]::new($false),4096,$true);$writer.NewLine="`n";$writer.AutoFlush=$true |
| 80 | $helloTask=$reader.ReadLineAsync();if(!$helloTask.Wait(10000)){throw 'Original host enrollment handshake timed out.'} |
| 81 | $line=$helloTask.Result;if(!$line -or $line.Length -gt 16384){throw 'Invalid original host enrollment handshake.'};$hello=$line|ConvertFrom-Json |
| 82 | if($hello.version -ne 1){throw 'Invalid original host enrollment handshake.'} |
| 83 | if(!$hello.authorized){Start-Sleep -Milliseconds 100;continue} |
| 84 | $Request.version=1;$Request.challenge=$hello.challenge;$Request.vm_id=$Context.VMID |
| 85 | $writer.WriteLine(($Request|ConvertTo-Json -Compress)) |
| 86 | if($Secret){if($Secret.Length -ne 32){throw 'Invalid new pairing key.'};$stream.Write($Secret,0,$Secret.Length);$stream.Flush()} |
| 87 | $timeout=if($Request.action -ceq 'finalize'){45000}else{10000} |
| 88 | $replyTask=$reader.ReadLineAsync();if(!$replyTask.Wait($timeout)){throw 'Original host enrollment response timed out.'} |
| 89 | $line=$replyTask.Result;if(!$line -or $line.Length -gt 16384){throw 'Invalid original host enrollment response.'};$reply=$line|ConvertFrom-Json |
| 90 | Assert-CageHostEnrollmentPeer $Context $stream |
| 91 | if($reply.version -ne 1 -or !$reply.ok){throw 'Original host enrollment did not complete; retained files were preserved.'} |
| 92 | return $reply |
| 93 | }finally{if($writer){$writer.Dispose()};if($reader){$reader.Dispose()};$stream.Dispose()} |
| 94 | }while([DateTime]::UtcNow -lt $deadline) |
| 95 | throw 'The administrator was not registered by the original host process.' |
| 96 | } |
| 97 | |
| 98 | function Set-CageHostEnrollmentAdmin($Context,$Process) { |
| 99 | $target=[Cage.HostEnrollment.Native]::OpenProcess(0x40,$false,[uint32]$Context.WorkerPID) |
| 100 | if($target -eq [IntPtr]::Zero){throw 'The original enrollment worker is unavailable.'} |
| 101 | $duplicate=[IntPtr]::Zero |
| 102 | try { |
| 103 | if(![Cage.HostEnrollment.Native]::DuplicateHandle([Cage.HostEnrollment.Native]::GetCurrentProcess(),$Process.Handle,$target,[ref]$duplicate,0,$false,2)){throw 'The authorized administrator process handle could not be retained.'} |
| 104 | $null=Invoke-CageHostEnrollment $Context @{action='allow-admin';pid=[uint32]$Process.Id;process_handle=[uint64]$duplicate.ToInt64()} $null |
| 105 | }finally{ |
| 106 | # On an ambiguous reply the worker is stopped by its original parent. |
| 107 | # Closing a numeric handle again here could target a reused handle. |
| 108 | [void][Cage.HostEnrollment.Native]::CloseHandle($target) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | function Send-CageHostEnrollmentKey($Context,[string]$Kind,[string]$GuestSID,[byte[]]$Secret) { |
| 113 | if($Kind -notin @('gui','packet')){throw 'Invalid original host pairing kind.'} |
| 114 | $null=Invoke-CageHostEnrollment $Context @{action=('deliver-'+$Kind);gui_user_sid=$GuestSID} $Secret |
| 115 | } |
| 116 | |
| 117 | function Complete-CageHostEnrollment($Context,[string]$GuestSID) { |
| 118 | $null=Invoke-CageHostEnrollment $Context @{action='finalize';gui_user_sid=$GuestSID} $null |
| 119 | } |
| 120 | |
| 121 | function Stop-CageHostEnrollment($Context) { |
| 122 | $null=Invoke-CageHostEnrollment $Context @{action='stop'} $null |
| 123 | } |
| 124 | |
| 125 | function Wait-CageHostEnrollment($Context, $Worker) { |
| 126 | $deadline=[DateTime]::UtcNow.AddSeconds(10) |
| 127 | do { |
| 128 | if ($Worker -and $Worker.HasExited) { |
| 129 | throw "enrollment_worker_exited (exit=$($Worker.ExitCode)). Check the enrollment error code in operation details, then continue installation." |
| 130 | } |
| 131 | try { $null=Invoke-CageHostEnrollment $Context @{action='ready'} $null; return } |
| 132 | catch { Start-Sleep -Milliseconds 100 } |
| 133 | } while ([DateTime]::UtcNow -lt $deadline) |
| 134 | throw 'The original user enrollment worker did not become available.' |
| 135 | } |