| 1 | # Invoked by the first-run installer inside its own VM through PowerShell Direct. |
| 2 | # No password is serialized, passed on a command line, or returned to the host. |
| 3 | param([Parameter(Mandatory)][guid]$VMId) |
| 4 | $ErrorActionPreference='Stop' |
| 5 | $machine=Get-CimInstance Win32_ComputerSystem |
| 6 | if ($VMId -eq [guid]::Empty -or $machine.Manufacturer -ne 'Microsoft Corporation' -or $machine.Model -ne 'Virtual Machine' -or |
| 7 | [guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId) { throw 'This operation requires the exact fresh Cage guest.' } |
| 8 | $userName='Cage-'+$VMId.ToString('N').Substring(0,10) |
| 9 | $description='Cage '+$VMId.ToString('D') |
| 10 | $key='HKLM:\SOFTWARE\Cage\WorkbenchBoot\'+$VMId.ToString('D') |
| 11 | $logon='HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' |
| 12 | $win=Get-Item -LiteralPath $logon |
| 13 | $user=Get-LocalUser -Name $userName -ErrorAction SilentlyContinue |
| 14 | $record=if(Test-Path -LiteralPath $key){Get-ItemProperty -LiteralPath $key} |
| 15 | if ($record -and ($record.VM -ne $VMId.ToString('D') -or $record.User -ne $userName)) { throw 'An existing boot-account registration was preserved.' } |
| 16 | if ($user -and (!$record -or $user.Description -cne $description -or ($record.SID -and $record.SID -ne $user.SID.Value))) { throw 'An existing Windows account cannot be used for automatic logon.' } |
| 17 | if ($win.GetValueNames() -contains 'DefaultPassword' -or $win.GetValue('ForceAutoLogon','0') -ne '0' -or |
| 18 | ($win.GetValue('AutoAdminLogon','0') -eq '1' -and (!$record -or $win.GetValue('DefaultUserName','') -ne $userName))) { |
| 19 | throw 'An existing Windows logon policy was preserved.' |
| 20 | } |
| 21 | if (!$record -or $record.Stage -ne 'ready') { |
| 22 | if (!$user -and $record -and $record.SID) { throw 'The dedicated account was removed. No replacement was created.' } |
| 23 | # Microsoft's Winlogon LSA API. Only the fixed DefaultPassword object may |
| 24 | # be tested for existence or created. Its contents cannot be read here. |
| 25 | if (!('CageWorkbenchBootSecret' -as [type])) { |
| 26 | Add-Type -TypeDefinition @' |
| 27 | using System; |
| 28 | using System.Runtime.InteropServices; |
| 29 | using System.Security; |
| 30 | using System.ComponentModel; |
| 31 | public static class CageWorkbenchBootSecret { |
| 32 | [StructLayout(LayoutKind.Sequential)] |
| 33 | struct Attributes { public uint length; public IntPtr root, name; public uint flags; public IntPtr descriptor, quality; } |
| 34 | [StructLayout(LayoutKind.Sequential)] |
| 35 | struct Unicode { public ushort length, maximum; public IntPtr text; } |
| 36 | [DllImport("advapi32.dll")] static extern int LsaOpenPolicy(IntPtr system,ref Attributes attr,uint access,out IntPtr policy); |
| 37 | [DllImport("advapi32.dll")] static extern int LsaOpenSecret(IntPtr policy,ref Unicode name,uint access,out IntPtr secret); |
| 38 | [DllImport("advapi32.dll")] static extern int LsaQuerySecret(IntPtr secret,out IntPtr current,IntPtr setTime,IntPtr previous,IntPtr previousSetTime); |
| 39 | [DllImport("advapi32.dll")] static extern int LsaFreeMemory(IntPtr memory); |
| 40 | [DllImport("advapi32.dll")] static extern int LsaStorePrivateData(IntPtr policy,ref Unicode name,ref Unicode data); |
| 41 | [DllImport("advapi32.dll")] static extern int LsaNtStatusToWinError(int code); |
| 42 | [DllImport("advapi32.dll")] static extern int LsaClose(IntPtr handle); |
| 43 | static bool CheckOrStore(SecureString password) { |
| 44 | var attr=new Attributes(); attr.length=(uint)Marshal.SizeOf(typeof(Attributes)); |
| 45 | IntPtr policy; int code=LsaOpenPolicy(IntPtr.Zero,ref attr,0x24,out policy); |
| 46 | if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code)); |
| 47 | const string fixedName="DefaultPassword"; var name=new Unicode(); |
| 48 | name.length=(ushort)(fixedName.Length*2);name.maximum=(ushort)(name.length+2);name.text=Marshal.StringToHGlobalUni(fixedName); |
| 49 | try { |
| 50 | IntPtr existing; code=LsaOpenSecret(policy,ref name,2,out existing); |
| 51 | if(code==0){ |
| 52 | // Fresh Windows can create the LSA object without assigning it |
| 53 | // a password. Inspect only the length field, never its buffer. |
| 54 | IntPtr valueHeader=IntPtr.Zero; |
| 55 | try { |
| 56 | code=LsaQuerySecret(existing,out valueHeader,IntPtr.Zero,IntPtr.Zero,IntPtr.Zero); |
| 57 | if(code!=0 && unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code)); |
| 58 | if(valueHeader!=IntPtr.Zero && Marshal.ReadInt16(valueHeader)!=0){ |
| 59 | if(password==null)return true; |
| 60 | throw new InvalidOperationException("An existing Winlogon LSA secret was preserved."); |
| 61 | } |
| 62 | } finally {if(valueHeader!=IntPtr.Zero)LsaFreeMemory(valueHeader);LsaClose(existing);} |
| 63 | } else if(unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code)); |
| 64 | if(password==null)return false; |
| 65 | var value=new Unicode(); value.length=checked((ushort)(password.Length*2));value.maximum=(ushort)(value.length+2); |
| 66 | value.text=Marshal.SecureStringToGlobalAllocUnicode(password); |
| 67 | try {code=LsaStorePrivateData(policy,ref name,ref value);if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code));} |
| 68 | finally {Marshal.ZeroFreeGlobalAllocUnicode(value.text);} |
| 69 | return true; |
| 70 | } finally {Marshal.FreeHGlobal(name.text);LsaClose(policy);} |
| 71 | } |
| 72 | public static bool Exists() { return CheckOrStore(null); } |
| 73 | public static void StoreNew(SecureString password) { if(password==null)throw new ArgumentNullException();CheckOrStore(password); } |
| 74 | } |
| 75 | '@ |
| 76 | } |
| 77 | $hasSecret=[CageWorkbenchBootSecret]::Exists() |
| 78 | if ($hasSecret -and (!$record -or $record.Stage -ne 'storing' -or !$user -or $record.SID -ne $user.SID.Value -or $user.LastLogon)) { |
| 79 | throw 'An existing Winlogon secret was preserved.' |
| 80 | } |
| 81 | if (!$record) { |
| 82 | $null=New-Item -Path $key -Force |
| 83 | $null=New-ItemProperty -LiteralPath $key -Name VM -Value $VMId.ToString('D') -PropertyType String |
| 84 | $null=New-ItemProperty -LiteralPath $key -Name User -Value $userName -PropertyType String |
| 85 | } |
| 86 | if (!$hasSecret) { |
| 87 | if ($user -and ($user.Enabled -or $user.LastLogon)) {throw 'The partially prepared user has already been used. Its password was preserved.'} |
| 88 | $random=[Security.Cryptography.RandomNumberGenerator]::Create() |
| 89 | $bytes=New-Object byte[] 48 |
| 90 | $password=[Security.SecureString]::new() |
| 91 | try { |
| 92 | $random.GetBytes($bytes) |
| 93 | $alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' |
| 94 | foreach ($b in $bytes) { $password.AppendChar($alphabet[[int]$b -band 63]) } |
| 95 | foreach ($c in 'a9Q!'.ToCharArray()) { $password.AppendChar($c) } |
| 96 | $password.MakeReadOnly() |
| 97 | if (!$user) { |
| 98 | $user=New-LocalUser -Name $userName -Password $password -Disabled -Description $description -PasswordNeverExpires -UserMayNotChangePassword |
| 99 | } else { |
| 100 | # Only our disabled, never-used account can reach this interrupted |
| 101 | # initial transaction. An enabled account never has its password reset. |
| 102 | Set-LocalUser -InputObject $user -Password $password |
| 103 | } |
| 104 | $null=New-ItemProperty -LiteralPath $key -Name SID -Value $user.SID.Value -PropertyType String -Force |
| 105 | $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'storing' -PropertyType String -Force |
| 106 | [CageWorkbenchBootSecret]::StoreNew($password) |
| 107 | } finally { $password.Dispose();$random.Dispose();[Array]::Clear($bytes,0,$bytes.Length) } |
| 108 | } |
| 109 | if (!$user.Enabled) { Enable-LocalUser -InputObject $user } |
| 110 | $user=Get-LocalUser -SID $user.SID |
| 111 | $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'ready' -PropertyType String -Force |
| 112 | } |
| 113 | if (!$user) {throw 'The dedicated workbench account was removed. No replacement was created.'} |
| 114 | if (!$user.Enabled -or $user.PrincipalSource -ne 'Local' -or $user.Description -cne $description) { throw 'The dedicated local account is unavailable.' } |
| 115 | $sid=$user.SID.Value |
| 116 | foreach ($group in Get-LocalGroup) { |
| 117 | $member=@(Get-LocalGroupMember -Group $group -ErrorAction Stop | Where-Object { $_.SID.Value -eq $sid }) |
| 118 | if ($member.Count -and $group.SID.Value -ne 'S-1-5-32-545') { throw 'The workbench account belongs to a privileged or unexpected group.' } |
| 119 | } |
| 120 | $users=Get-LocalGroup -SID 'S-1-5-32-545' |
| 121 | if (!@(Get-LocalGroupMember -Group $users | Where-Object {$_.SID.Value -eq $sid}).Count) { Add-LocalGroupMember -Group $users -Member $user } |
| 122 | $null=New-ItemProperty -LiteralPath $key -Name SID -Value $sid -PropertyType String -Force |
| 123 | |
| 124 | # First boot is armed by the separate boot service only during a real shutdown. |
| 125 | # Windows logon UI is never sent a broad keyboard event or a cleartext value. |
| 126 | [pscustomobject]@{ SID=$sid; Name=$userName; BootID=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o'); Program=(Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)); AlreadySignedIn=($machine.UserName -eq ($env:COMPUTERNAME+'\'+$userName)) } |