]>
| Commit | Line | Data |
|---|---|---|
| 3c096107 MV |
1 | #Requires -RunAsAdministrator\r |
| 2 | <#\r | |
| 3 | setup-windows-with-uac.ps1\r | |
| 452f525c | 4 | Elevated portion of the Windows provisioning. Invoked by setup-windows.bat\r |
| 3c096107 MV |
5 | via Start-Process -Verb RunAs, or run manually from an Administrator prompt.\r |
| 6 | \r | |
| 7 | What this installs / configures:\r | |
| b8144088 MV |
8 | - OpenSSH Client capability (the ssh.exe rsync shells out to, and the\r |
| 9 | System32 libcrypto.dll the release's own ssh.exe links against)\r | |
| 3c096107 | 10 | - ssh-agent set to automatic + started\r |
| 452f525c | 11 | - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22\r |
| b8144088 MV |
12 | - rsync for Windows (nuket/rsync-windows) in C:\Tools\rsync, on the machine\r |
| 13 | PATH: rsync.exe plus the ssh.exe it runs, out of the release zip for this\r | |
| 14 | architecture\r | |
| 3c096107 MV |
15 | - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,\r |
| 16 | Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)\r | |
| 17 | - Windows Driver Kit 10.0.26100\r | |
| 99725a30 MV |
18 | - Windows Performance Toolkit - xperf, wpr and Windows Performance Analyzer\r |
| 19 | (wpa.exe) - on the machine PATH\r | |
| 20 | - ETW collection rights for one ordinary account: Performance Log Users\r | |
| 21 | membership plus the "Profile system performance" user right, so xperf and\r | |
| 22 | wpr run WITHOUT elevation\r | |
| 3c096107 MV |
23 | \r |
| 24 | Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r | |
| 25 | Professional : https://aka.ms/vs/17/release/vs_professional.exe\r | |
| 26 | Enterprise : https://aka.ms/vs/17/release/vs_enterprise.exe\r | |
| 27 | #>\r | |
| 28 | \r | |
| 99725a30 MV |
29 | param(\r |
| 30 | # Account to be granted non-elevated ETW collection rights (see the "ETW\r | |
| 31 | # collection rights" step at the bottom). Defaults to the interactive\r | |
| 32 | # console user, but setup-windows.bat passes it explicitly: with\r | |
| 33 | # over-the-shoulder elevation THIS script runs as the administrator whose\r | |
| 34 | # credentials went into the UAC prompt, not as the user who started the\r | |
| 35 | # batch file, so $env:USERNAME here is the wrong answer.\r | |
| 36 | #\r | |
| 37 | # Pass an empty string to skip the group membership (the user right is still\r | |
| 38 | # granted to the group, so adding an account later is one command).\r | |
| 0aec6243 MV |
39 | [string] $TraceUser = '',\r |
| 40 | \r | |
| 41 | # Do the ETW rights step and nothing else. That step is seconds of registry\r | |
| 42 | # and LSA work with no downloads, where a full run is dominated by the three\r | |
| 43 | # Visual Studio passes, which take minutes even when they have nothing to do.\r | |
| 44 | # It is why the ETW step runs FIRST: -EtwRightsOnly is then just an early\r | |
| 45 | # exit rather than a set of guards down the rest of the script.\r | |
| 46 | [switch] $EtwRightsOnly\r | |
| 99725a30 MV |
47 | )\r |
| 48 | \r | |
| 3c096107 MV |
49 | $ErrorActionPreference = 'Stop'\r |
| 50 | \r | |
| 51 | function Write-Step([string]$Msg) {\r | |
| 52 | Write-Host "`n==> $Msg" -ForegroundColor Cyan\r | |
| 53 | }\r | |
| 54 | \r | |
| 55 | function Assert-ExitCode([int]$Code, [string]$Step) {\r | |
| 56 | # 0 = success, 3010 = success + reboot required\r | |
| 57 | if ($Code -notin @(0, 3010)) {\r | |
| 58 | throw "$Step failed with exit code $Code"\r | |
| 59 | }\r | |
| 60 | if ($Code -eq 3010) {\r | |
| 61 | Write-Host " [reboot required after $Step]" -ForegroundColor Yellow\r | |
| 62 | }\r | |
| 63 | }\r | |
| 64 | \r | |
| 99725a30 MV |
65 | # ---------------------------------------------------------------------------\r |
| 66 | # User rights assignment (LSA account rights)\r | |
| 67 | #\r | |
| 68 | # Windows has no built-in cmdlet for "grant this SID this privilege". The two\r | |
| 69 | # ways to script it are secedit (export the whole USER_RIGHTS area to an INF,\r | |
| 70 | # edit one line, re-import) and the LSA API. The API is used here because it is\r | |
| 71 | # surgical: LsaAddAccountRights adds exactly one right to exactly one SID and is\r | |
| 72 | # a no-op when it is already held, where a secedit round-trip re-applies every\r | |
| 73 | # user right on the box to fix one of them. The GUI equivalent, for a human, is\r | |
| 74 | # secpol.msc > Local Policies > User Rights Assignment\r | |
| 75 | #\r | |
| 76 | # The type is compiled on first use; C# 5 only, since Windows PowerShell 5.1's\r | |
| 77 | # Add-Type compiles with the in-box CodeDom compiler.\r | |
| 78 | # ---------------------------------------------------------------------------\r | |
| 79 | function Initialize-LsaRightsType {\r | |
| 80 | if ('LsaRights' -as [type]) { return }\r | |
| 81 | Add-Type -TypeDefinition @'\r | |
| 82 | using System;\r | |
| 83 | using System.ComponentModel;\r | |
| 84 | using System.Runtime.InteropServices;\r | |
| 85 | \r | |
| 86 | public static class LsaRights\r | |
| 87 | {\r | |
| 88 | [StructLayout(LayoutKind.Sequential)]\r | |
| 89 | private struct LSA_UNICODE_STRING\r | |
| 90 | {\r | |
| 91 | public ushort Length;\r | |
| 92 | public ushort MaximumLength;\r | |
| 93 | public IntPtr Buffer;\r | |
| 94 | }\r | |
| 95 | \r | |
| 96 | [StructLayout(LayoutKind.Sequential)]\r | |
| 97 | private struct LSA_OBJECT_ATTRIBUTES\r | |
| 98 | {\r | |
| 99 | public int Length;\r | |
| 100 | public IntPtr RootDirectory;\r | |
| 101 | public IntPtr ObjectName;\r | |
| 102 | public uint Attributes;\r | |
| 103 | public IntPtr SecurityDescriptor;\r | |
| 104 | public IntPtr SecurityQualityOfService;\r | |
| 105 | }\r | |
| 106 | \r | |
| 107 | [DllImport("advapi32.dll", SetLastError = true)]\r | |
| 108 | private static extern uint LsaOpenPolicy(IntPtr systemName,\r | |
| 109 | ref LSA_OBJECT_ATTRIBUTES objectAttributes, uint desiredAccess, out IntPtr policyHandle);\r | |
| 110 | \r | |
| 111 | [DllImport("advapi32.dll", SetLastError = true)]\r | |
| 112 | private static extern uint LsaAddAccountRights(IntPtr policyHandle, byte[] accountSid,\r | |
| 113 | LSA_UNICODE_STRING[] userRights, uint countOfRights);\r | |
| 114 | \r | |
| 115 | [DllImport("advapi32.dll", SetLastError = true)]\r | |
| 116 | private static extern uint LsaEnumerateAccountRights(IntPtr policyHandle, byte[] accountSid,\r | |
| 117 | out IntPtr userRights, out uint countOfRights);\r | |
| 118 | \r | |
| 119 | [DllImport("advapi32.dll")]\r | |
| 120 | private static extern uint LsaClose(IntPtr policyHandle);\r | |
| 121 | \r | |
| 122 | [DllImport("advapi32.dll")]\r | |
| 123 | private static extern uint LsaFreeMemory(IntPtr buffer);\r | |
| 124 | \r | |
| 125 | [DllImport("advapi32.dll")]\r | |
| 126 | private static extern int LsaNtStatusToWinError(uint status);\r | |
| 127 | \r | |
| 128 | private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001;\r | |
| 129 | private const uint POLICY_CREATE_ACCOUNT = 0x00000010;\r | |
| 130 | private const uint POLICY_LOOKUP_NAMES = 0x00000800;\r | |
| 131 | \r | |
| 132 | // Returned by LsaEnumerateAccountRights when the SID holds no rights at all,\r | |
| 133 | // which is an empty list rather than an error.\r | |
| 134 | private const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;\r | |
| 135 | \r | |
| 136 | private static IntPtr OpenPolicy()\r | |
| 137 | {\r | |
| 138 | LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES();\r | |
| 139 | attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));\r | |
| 140 | IntPtr handle;\r | |
| 141 | uint status = LsaOpenPolicy(IntPtr.Zero, ref attrs,\r | |
| 142 | POLICY_VIEW_LOCAL_INFORMATION | POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, out handle);\r | |
| 143 | if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r | |
| 144 | return handle;\r | |
| 145 | }\r | |
| 146 | \r | |
| 147 | public static string[] Get(byte[] sid)\r | |
| 148 | {\r | |
| 149 | IntPtr policy = OpenPolicy();\r | |
| 150 | try\r | |
| 151 | {\r | |
| 152 | IntPtr rights;\r | |
| 153 | uint count;\r | |
| 154 | uint status = LsaEnumerateAccountRights(policy, sid, out rights, out count);\r | |
| 155 | if (status == STATUS_OBJECT_NAME_NOT_FOUND) { return new string[0]; }\r | |
| 156 | if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r | |
| 157 | try\r | |
| 158 | {\r | |
| 159 | string[] result = new string[count];\r | |
| 160 | int stride = Marshal.SizeOf(typeof(LSA_UNICODE_STRING));\r | |
| 161 | for (int i = 0; i < count; i++)\r | |
| 162 | {\r | |
| 163 | LSA_UNICODE_STRING s = (LSA_UNICODE_STRING)Marshal.PtrToStructure(\r | |
| 164 | new IntPtr(rights.ToInt64() + (long)i * stride), typeof(LSA_UNICODE_STRING));\r | |
| 165 | result[i] = Marshal.PtrToStringUni(s.Buffer, s.Length / 2);\r | |
| 166 | }\r | |
| 167 | return result;\r | |
| 168 | }\r | |
| 169 | finally { LsaFreeMemory(rights); }\r | |
| 170 | }\r | |
| 171 | finally { LsaClose(policy); }\r | |
| 172 | }\r | |
| 173 | \r | |
| 174 | public static void Add(byte[] sid, string right)\r | |
| 175 | {\r | |
| 176 | IntPtr policy = OpenPolicy();\r | |
| 177 | try\r | |
| 178 | {\r | |
| 179 | LSA_UNICODE_STRING[] rights = new LSA_UNICODE_STRING[1];\r | |
| 180 | rights[0].Buffer = Marshal.StringToHGlobalUni(right);\r | |
| 181 | // Length counts BYTES and excludes the terminator; MaximumLength includes it.\r | |
| 182 | rights[0].Length = (ushort)(right.Length * 2);\r | |
| 183 | rights[0].MaximumLength = (ushort)(right.Length * 2 + 2);\r | |
| 184 | try\r | |
| 185 | {\r | |
| 186 | uint status = LsaAddAccountRights(policy, sid, rights, 1);\r | |
| 187 | if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r | |
| 188 | }\r | |
| 189 | finally { Marshal.FreeHGlobal(rights[0].Buffer); }\r | |
| 190 | }\r | |
| 191 | finally { LsaClose(policy); }\r | |
| 192 | }\r | |
| 193 | }\r | |
| 194 | '@\r | |
| 195 | }\r | |
| 196 | \r | |
| 197 | function Get-SidBytes([string]$Sid) {\r | |
| 198 | $s = New-Object System.Security.Principal.SecurityIdentifier($Sid)\r | |
| 199 | $bytes = New-Object byte[] $s.BinaryLength\r | |
| 200 | $s.GetBinaryForm($bytes, 0)\r | |
| 201 | return ,$bytes\r | |
| 202 | }\r | |
| 203 | \r | |
| 204 | function Get-AccountRight([string]$Sid) {\r | |
| 205 | Initialize-LsaRightsType\r | |
| 206 | return [LsaRights]::Get((Get-SidBytes $Sid))\r | |
| 207 | }\r | |
| 208 | \r | |
| 209 | function Grant-AccountRight([string]$Sid, [string]$Right) {\r | |
| 210 | Initialize-LsaRightsType\r | |
| 211 | [LsaRights]::Add((Get-SidBytes $Sid), $Right)\r | |
| 212 | }\r | |
| 213 | \r | |
| 0aec6243 MV |
214 | # ---------------------------------------------------------------------------\r |
| 215 | # ETW provider-GUID access control\r | |
| 216 | #\r | |
| 217 | # ETW keeps a security descriptor per provider GUID under\r | |
| 218 | # HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security, and EventAccessControl is\r | |
| 219 | # the documented way to edit one. Editing the registry value directly would work\r | |
| 220 | # too - it is a self-relative SD in a REG_BINARY - but the API takes the SID and\r | |
| 221 | # the rights mask and leaves the descriptor's shape to Windows.\r | |
| 222 | # ---------------------------------------------------------------------------\r | |
| 223 | function Initialize-EtwAclType {\r | |
| 224 | if ('EtwAcl' -as [type]) { return }\r | |
| 225 | Add-Type -TypeDefinition @'\r | |
| 226 | using System;\r | |
| 227 | using System.Runtime.InteropServices;\r | |
| 228 | \r | |
| 229 | public static class EtwAcl\r | |
| 230 | {\r | |
| 231 | // ULONG EventAccessControl(LPGUID, ULONG Operation, PSID, ULONG Rights, BOOLEAN AllowOrDeny)\r | |
| 232 | [DllImport("advapi32.dll", SetLastError = true)]\r | |
| 233 | public static extern uint EventAccessControl(ref Guid guid, uint operation, byte[] sid,\r | |
| 234 | uint rights, [MarshalAs(UnmanagedType.U1)] bool allowOrDeny);\r | |
| 235 | \r | |
| 236 | // ULONG EventAccessQuery(LPGUID, PSECURITY_DESCRIPTOR, PULONG BufferSize)\r | |
| 237 | [DllImport("advapi32.dll", SetLastError = true)]\r | |
| 238 | public static extern uint EventAccessQuery(ref Guid guid, byte[] buffer, ref uint bufferSize);\r | |
| 239 | }\r | |
| 240 | '@\r | |
| 241 | }\r | |
| 242 | \r | |
| 243 | # The rights a session controller needs, from evntrace.h:\r | |
| 244 | # 0x0001 WMIGUID_QUERY 0x0100 TRACELOG_ACCESS_KERNEL_LOGGER\r | |
| 245 | # 0x0020 TRACELOG_CREATE_REALTIME 0x0200 TRACELOG_LOG_EVENT\r | |
| 246 | # 0x0040 TRACELOG_CREATE_ONDISK 0x0400 TRACELOG_ACCESS_REALTIME\r | |
| 247 | # 0x0080 TRACELOG_GUID_ENABLE 0x0800 TRACELOG_REGISTER_GUIDS\r | |
| 248 | # TRACELOG_ACCESS_KERNEL_LOGGER is the one that names the NT Kernel Logger\r | |
| 249 | # specifically; the rest are what any controller needs to create a session,\r | |
| 250 | # write it to disk and enable providers on it.\r | |
| d52d6278 MV |
251 | #\r |
| 252 | # READ_CONTROL (0x20000) and SYNCHRONIZE (0x100000) go with them - the SYSTEM and\r | |
| 253 | # Administrators entries on this GUID carry 0x120FFF. Without READ_CONTROL the\r | |
| 254 | # group cannot read the descriptor back, which makes EventAccessQuery useless as\r | |
| 255 | # a check on whether the grant landed: it answers "access denied" either way.\r | |
| 256 | $EtwControllerRights = 0x120FE1\r | |
| 0aec6243 MV |
257 | \r |
| 258 | function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) {\r | |
| 259 | Initialize-EtwAclType\r | |
| 260 | $g = [Guid]$Guid\r | |
| 261 | # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing\r | |
| 262 | # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which\r | |
| 263 | # on the kernel logger means removing the entries Windows itself relies on.\r | |
| 264 | $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true)\r | |
| 265 | if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) }\r | |
| 266 | }\r | |
| 267 | \r | |
| 268 | function Get-EtwGuidSddl([string]$Guid) {\r | |
| 269 | Initialize-EtwAclType\r | |
| 270 | $g = [Guid]$Guid\r | |
| 271 | $size = [uint32]0\r | |
| 272 | [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size)\r | |
| 273 | if ($size -eq 0) { return $null }\r | |
| 274 | $buf = New-Object byte[] $size\r | |
| 275 | if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null }\r | |
| 276 | return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access')\r | |
| 277 | }\r | |
| 278 | \r | |
| 3c096107 MV |
279 | function Show-VsSetupLogs {\r |
| 280 | # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because\r | |
| 281 | # this script runs elevated, that %TEMP% belongs to the elevated user and is\r | |
| 282 | # readable here even when it is NOT readable by the non-elevated caller. Fold\r | |
| 283 | # only the NEWEST installer + bootstrapper log into the transcript (the setup\r | |
| 284 | # engine log is where per-component / product errors actually appear) and\r | |
| 285 | # keep it short so the transcript stays readable.\r | |
| 286 | Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan\r | |
| 287 | $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |\r | |
| 288 | Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }\r | |
| 289 | $picks = @()\r | |
| 290 | $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r | |
| 291 | $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1\r | |
| 292 | $picks = $picks | Where-Object { $_ }\r | |
| 293 | if (-not $picks) {\r | |
| 294 | Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow\r | |
| 295 | return\r | |
| 296 | }\r | |
| 297 | foreach ($l in $picks) {\r | |
| 298 | Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow\r | |
| 299 | Get-Content $l.FullName -Tail 40\r | |
| 300 | }\r | |
| 301 | }\r | |
| 302 | \r | |
| 303 | function Invoke-VsModify {\r | |
| 304 | # Run one VS install/modify pass for a named group of components. Splitting\r | |
| 305 | # the install into separate passes makes it obvious WHICH group fails: each\r | |
| 306 | # call prints its label and exit code before Assert-ExitCode throws.\r | |
| 307 | param(\r | |
| 308 | [string] $Label,\r | |
| 309 | [string[]] $Ids\r | |
| 310 | )\r | |
| 311 | Write-Step "VS2022: $Label"\r | |
| 312 | $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '\r | |
| 313 | # --installPath must be quoted: it contains spaces ("C:\Program Files\...").\r | |
| 314 | # Windows PowerShell 5.1's Start-Process does not quote array elements, so we\r | |
| 315 | # hand-build a single string. Component IDs / flags have no spaces.\r | |
| 316 | $common = '--includeRecommended --quiet --norestart --wait'\r | |
| 317 | if ($script:InstallPath) {\r | |
| 318 | $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"\r | |
| 319 | } else {\r | |
| 320 | # No existing install yet -> this first pass performs the base install.\r | |
| 321 | $argString = "$addStr $common"\r | |
| 322 | }\r | |
| 323 | Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray\r | |
| 324 | $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow\r | |
| 325 | Write-Host " exit code: $($p.ExitCode)"\r | |
| 326 | Assert-ExitCode $p.ExitCode "VS2022 ($Label)"\r | |
| 327 | \r | |
| 328 | # After the first (fresh) install, re-detect the install path so subsequent\r | |
| 329 | # passes use `modify`.\r | |
| 330 | if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {\r | |
| 331 | $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |\r | |
| 332 | Select-Object -First 1\r | |
| 333 | }\r | |
| 334 | }\r | |
| 335 | \r | |
| 336 | # ---------------------------------------------------------------------------\r | |
| 337 | # This runs in a separate elevated window that closes the moment it exits, so\r | |
| 338 | # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror\r | |
| 339 | # all output to a log next to the script and exit with a real code so the\r | |
| 340 | # caller can detect success/failure and show the log.\r | |
| 341 | # ---------------------------------------------------------------------------\r | |
| 342 | $LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log'\r | |
| 343 | $ExitCode = 0\r | |
| 344 | try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}\r | |
| 345 | \r | |
| 346 | try {\r | |
| 347 | \r | |
| 0aec6243 MV |
348 | # ---------------------------------------------------------------------------\r |
| 349 | # ETW collection rights for an ordinary account\r | |
| 350 | #\r | |
| 351 | # Out of the box, xperf and wpr only work elevated. THREE separate things stand\r | |
| 352 | # in a standard user's way, and each has its own error:\r | |
| 353 | #\r | |
| 354 | # xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)"\r | |
| 355 | # wpr -start GeneralProfile\r | |
| 356 | # -> "Failed to enable the policy to profile system\r | |
| 357 | # performance." (0xc5585011)\r | |
| 358 | #\r | |
| 359 | # 1. Creating or controlling ANY event tracing session - even a user-mode one\r | |
| 360 | # naming a single provider - is checked against the security descriptor ETW\r | |
| 361 | # keeps per provider GUID under\r | |
| 362 | # HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor\r | |
| 363 | # grants the session-control rights (TRACELOG_CREATE_ONDISK,\r | |
| 364 | # TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to\r | |
| 365 | # SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log\r | |
| 366 | # Users - and to nobody else. That group is the supported hook; its own\r | |
| 367 | # description says members "may ... enable trace providers, and collect event\r | |
| 368 | # traces".\r | |
| 369 | #\r | |
| 370 | # 2. Switching on the kernel/system trace provider on top of that needs the\r | |
| 371 | # SeSystemProfilePrivilege user right ("Profile system performance"), held by\r | |
| 372 | # default only by Administrators and NT SERVICE\WdiServiceHost. That is the\r | |
| 373 | # one wpr names in its error.\r | |
| 374 | #\r | |
| 375 | # 3. The kernel logger is not covered by that default descriptor. Its own GUID -\r | |
| 376 | # SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries\r | |
| 377 | # an explicit descriptor that does not mention Performance Log Users, so 1 and\r | |
| 378 | # 2 are not enough by themselves. Measured on this box with both in place: a\r | |
| 379 | # user-mode session starts (exit 0) and the account holds the privilege, and\r | |
| 380 | # `xperf -on base` still answers "NT Kernel Logger: Access is denied" while\r | |
| 381 | # wpr's error changes from the policy message above to a bare 0x80070005.\r | |
| 382 | # Even READING that descriptor comes back access-denied, which is the tell. So\r | |
| 383 | # add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER\r | |
| 384 | # is the right that names this particular session.\r | |
| 385 | #\r | |
| 386 | # The privilege and the ACE both go to the GROUP, and the account then goes into\r | |
| 387 | # the group: membership alone becomes the switch, and enabling the next account\r | |
| 388 | # is one `net localgroup` away with no policy or registry edit.\r | |
| 389 | #\r | |
| 390 | # What this costs, stated plainly: a member of that group can capture\r | |
| 391 | # system-wide kernel traces - process, image, file and registry activity across\r | |
| 392 | # every account on the box, paths and command lines included. That is what the\r | |
| 393 | # group is for, and it is the price of collecting a trace without a UAC prompt.\r | |
| 394 | #\r | |
| 395 | # Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU\r | |
| 396 | # sampling nor walking stacks in your own processes, and it is equivalent to\r | |
| 397 | # handing out administrator.\r | |
| 398 | #\r | |
| 399 | # THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership\r | |
| 400 | # are baked into the access token at LOGON, and UAC hands an administrator a\r | |
| 401 | # filtered token that keeps just five harmless privileges - so an admin's\r | |
| 402 | # ordinary shell still cannot trace, however the policy reads. Running as a\r | |
| 403 | # standard user is what makes this work.\r | |
| 404 | #\r | |
| 405 | # For the same reason 1 and 2 do not take effect in an already-open session: the\r | |
| 406 | # account has to sign out and back in. Any NEW logon does it - an ssh login into\r | |
| 407 | # this box is one, which is the quick way to check without dropping the desktop.\r | |
| d52d6278 MV |
408 | # The ACE in 3 is machine state rather than token state, so a logon does nothing\r |
| 409 | # for it. ETW reads these descriptors into a cache, so a REBOOT is what is\r | |
| 410 | # expected to put the change into effect: with the ACE written and readable in\r | |
| 411 | # the descriptor, xperf -on base was still answering "Access is denied" from a\r | |
| 412 | # fresh shell on the running system. So on a first run, plan on both - a new\r | |
| 413 | # logon for 1 and 2, a reboot for 3.\r | |
| 0aec6243 MV |
414 | #\r |
| 415 | # Analysis never needed any of this: wpa.exe opens an existing .etl as a plain\r | |
| 416 | # user. This step is only about collection.\r | |
| 417 | # ---------------------------------------------------------------------------\r | |
| 418 | Write-Step 'ETW collection rights (non-elevated xperf / wpr)'\r | |
| 419 | $PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users\r | |
| 420 | # SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on\r | |
| 421 | # and wpr both drive. Fixed by contract, from evntrace.h.\r | |
| 422 | $SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939'\r | |
| 423 | try {\r | |
| 424 | # --- The user right, granted to the group ---\r | |
| 425 | $existing = Get-AccountRight $PerfLogUsersSid\r | |
| 426 | if ($existing -contains 'SeSystemProfilePrivilege') {\r | |
| 427 | Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege'\r | |
| 428 | } else {\r | |
| 429 | Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'\r | |
| 430 | Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'\r | |
| 431 | }\r | |
| 432 | \r | |
| 433 | # --- The kernel logger's own descriptor ---\r | |
| d52d6278 MV |
434 | # Safe to repeat: a second ACE for the same SID unions to the same access.\r |
| 435 | # Kept in its own try so that a failure here still leaves the group\r | |
| 0aec6243 | 436 | # membership below to be done - user-mode sessions work without it.\r |
| d52d6278 MV |
437 | #\r |
| 438 | # ETW reads these descriptors out of the registry into a cache, so a REBOOT\r | |
| 439 | # is what puts a change here into effect - not a new logon, which is what the\r | |
| 440 | # group membership and the privilege need. Both, on a first run.\r | |
| 0aec6243 MV |
441 | try {\r |
| 442 | Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights\r | |
| 443 | Write-Host (" Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights)\r | |
| 444 | $sddl = Get-EtwGuidSddl $SystemTraceControlGuid\r | |
| 445 | if ($sddl) { Write-Host " kernel logger DACL is now $sddl" -ForegroundColor DarkGray }\r | |
| 446 | } catch {\r | |
| 447 | Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)"\r | |
| 448 | Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."'\r | |
| 449 | }\r | |
| 450 | \r | |
| 451 | # --- The membership ---\r | |
| 452 | # Fall back to the console user when the caller did not name one: with\r | |
| 453 | # over-the-shoulder elevation that is the person who started\r | |
| 454 | # setup-windows.bat, which is who wants to trace.\r | |
| 455 | $target = $TraceUser\r | |
| 456 | if (-not $target) {\r | |
| 457 | $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName\r | |
| 458 | if ($target) { Write-Host " No -TraceUser given; using the console user $target" }\r | |
| 459 | }\r | |
| 460 | \r | |
| 461 | if (-not $target) {\r | |
| 462 | Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'\r | |
| 463 | Write-Warning 'The user right is in place, so this is the only step left:'\r | |
| 464 | Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add'\r | |
| 465 | } else {\r | |
| 466 | # Resolve to a SID first: it validates the name, and it is what the\r | |
| 467 | # membership check compares, so a member spelled ".\claude" in one place\r | |
| 468 | # and "LATISLAB\claude" in another is still recognised as the same account.\r | |
| 469 | $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(\r | |
| 470 | [System.Security.Principal.SecurityIdentifier])\r | |
| 471 | \r | |
| 472 | # By SID, never by name: "Performance Log Users" is localised, and\r | |
| 473 | # Get-LocalGroup -SID is how this stays correct on a non-English box.\r | |
| 474 | $group = Get-LocalGroup -SID $PerfLogUsersSid\r | |
| 475 | \r | |
| 476 | # Get-LocalGroupMember throws on a group holding a SID that no longer\r | |
| 477 | # resolves (a known Windows 10 bug), so a failure to READ the membership\r | |
| 478 | # must not stop us from writing it - fall through and let the add report.\r | |
| 479 | $already = $false\r | |
| 480 | try {\r | |
| 481 | $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |\r | |
| 482 | Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0\r | |
| 483 | } catch {\r | |
| 484 | Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray\r | |
| 485 | }\r | |
| 486 | \r | |
| 487 | if ($already) {\r | |
| 488 | Write-Host " OK: $target is already in $($group.Name)"\r | |
| 489 | } else {\r | |
| 490 | try {\r | |
| 491 | Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value\r | |
| 492 | } catch {\r | |
| 493 | # "already a member" is only reachable when the enumeration above\r | |
| 494 | # failed, and is not an error. Matched on the type NAME rather\r | |
| 495 | # than in a typed catch clause: catch types are resolved when the\r | |
| 496 | # script is PARSED, before the LocalAccounts module has been\r | |
| 497 | # autoloaded, so naming the type there is a parse error that\r | |
| 498 | # would take the whole script down.\r | |
| 499 | if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }\r | |
| 500 | }\r | |
| 501 | Write-Host " Added $target to $($group.Name)"\r | |
| 502 | }\r | |
| 503 | \r | |
| 504 | Write-Host ''\r | |
| d52d6278 MV |
505 | Write-Host " $target must sign out and back in for the group and the privilege," -ForegroundColor Yellow\r |
| 506 | Write-Host ' and the box must be REBOOTED for the kernel logger ACE (ETW caches it).' -ForegroundColor Yellow\r | |
| 0aec6243 MV |
507 | Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow\r |
| 508 | Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow\r | |
| 509 | Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow\r | |
| 510 | }\r | |
| 511 | } catch {\r | |
| 512 | Write-Warning "ETW rights setup failed: $($_.Exception.Message)"\r | |
| 513 | Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'\r | |
| 514 | Write-Warning '"Profile system performance" > add Performance Log Users, then'\r | |
| 515 | Write-Warning ' net localgroup "Performance Log Users" <user> /add'\r | |
| 516 | }\r | |
| 517 | \r | |
| 518 | if ($EtwRightsOnly) {\r | |
| 519 | # `exit` inside the try still runs the finally below, so the transcript is\r | |
| 520 | # stopped and the log is left readable by the non-elevated caller.\r | |
| 521 | Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green\r | |
| 522 | exit 0\r | |
| 523 | }\r | |
| 524 | \r | |
| 525 | \r | |
| 3c096107 MV |
526 | # ---------------------------------------------------------------------------\r |
| 527 | # Base tools via winget\r | |
| 528 | # ---------------------------------------------------------------------------\r | |
| b8144088 MV |
529 | \r |
| 530 | # ---------------------------------------------------------------------------\r | |
| 531 | # OpenSSH Client\r | |
| 532 | #\r | |
| 533 | # Present by default on Windows 10 1809+ / Windows 11, but removable, and absent\r | |
| 534 | # from some Server images. Two things below want it: rsync does not speak ssh\r | |
| 535 | # itself, it execs an ssh binary, and the release's own ssh.exe links against the\r | |
| 536 | # libcrypto.dll this capability puts in System32. It also owns the ssh-agent\r | |
| 537 | # service configured next, so a missing client is why that step would fail.\r | |
| 538 | #\r | |
| 539 | # Non-fatal, like the server half below: a box that cannot have it should still\r | |
| 540 | # finish provisioning.\r | |
| 541 | # ---------------------------------------------------------------------------\r | |
| 542 | Write-Step 'OpenSSH Client'\r | |
| 543 | try {\r | |
| 544 | $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |\r | |
| 545 | Select-Object -First 1\r | |
| 546 | if (-not $sshc) {\r | |
| 547 | Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'\r | |
| 548 | } elseif ($sshc.State -eq 'Installed') {\r | |
| 549 | Write-Host " OK: $($sshc.Name) already installed"\r | |
| 550 | } else {\r | |
| 551 | Write-Host " Installing $($sshc.Name) ..."\r | |
| 552 | $r = Add-WindowsCapability -Online -Name $sshc.Name\r | |
| 553 | if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Client]' -ForegroundColor Yellow }\r | |
| 554 | }\r | |
| 555 | } catch {\r | |
| 556 | Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"\r | |
| 557 | }\r | |
| 558 | \r | |
| 3c096107 MV |
559 | # ---------------------------------------------------------------------------\r |
| 560 | # SSH agent\r | |
| 561 | # ---------------------------------------------------------------------------\r | |
| 562 | Write-Step 'Enabling ssh-agent'\r | |
| 563 | Set-Service -Name ssh-agent -StartupType Automatic\r | |
| 564 | if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }\r | |
| 565 | \r | |
| 452f525c MV |
566 | # ---------------------------------------------------------------------------\r |
| 567 | # OpenSSH Server (sshd)\r | |
| 568 | #\r | |
| 569 | # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the\r | |
| 570 | # transport rsync rides on when seeding test data in. Ships with Windows 10\r | |
| 571 | # 1809+ / Windows 11 as an on-demand capability, so no third-party install.\r | |
| 572 | #\r | |
| 573 | # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall\r | |
| 574 | # rule; we verify and create it if missing (it is absent on some images).\r | |
| 575 | #\r | |
| 576 | # Non-fatal: a box that can't run sshd should still finish provisioning.\r | |
| 577 | # ---------------------------------------------------------------------------\r | |
| 578 | Write-Step 'OpenSSH Server (sshd)'\r | |
| 579 | try {\r | |
| 580 | $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |\r | |
| 581 | Select-Object -First 1\r | |
| 582 | if (-not $sshd) {\r | |
| 583 | Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'\r | |
| 584 | } else {\r | |
| 585 | if ($sshd.State -ne 'Installed') {\r | |
| 586 | Write-Host " Installing $($sshd.Name) ..."\r | |
| 587 | $r = Add-WindowsCapability -Online -Name $sshd.Name\r | |
| 588 | if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Server]' -ForegroundColor Yellow }\r | |
| 589 | } else {\r | |
| 590 | Write-Host " OK: $($sshd.Name) already installed"\r | |
| 591 | }\r | |
| 592 | \r | |
| 593 | Set-Service -Name sshd -StartupType Automatic\r | |
| 594 | if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }\r | |
| 595 | Write-Host ' sshd: Automatic + running'\r | |
| 596 | \r | |
| 597 | # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and\r | |
| 598 | # bridged adapters are frequently classified Public, and the capability's\r | |
| 599 | # own rule is Private-only on some images, which is what leaves a plainly\r | |
| 600 | # running sshd plainly unreachable.\r | |
| 601 | #\r | |
| 602 | # OpenSSH-Server-In-TCP is the name the capability itself uses, so this\r | |
| 603 | # WIDENS that rule rather than adding a second one next to it. Creating\r | |
| 604 | # our own under a different name would leave the narrow rule in place and\r | |
| 605 | # the box still unreachable on a Public-classified adapter; creating one\r | |
| 606 | # under the same name would collide. Adopt it if present, create it if not.\r | |
| 607 | $ruleName = 'OpenSSH-Server-In-TCP'\r | |
| 608 | if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {\r | |
| 609 | Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any\r | |
| 610 | Write-Host " Widened firewall rule $ruleName to all profiles"\r | |
| 611 | } else {\r | |
| 612 | New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `\r | |
| 613 | -Enabled True -Direction Inbound -Protocol TCP -Action Allow `\r | |
| 614 | -LocalPort 22 -Profile Any | Out-Null\r | |
| 615 | Write-Host " Added firewall rule $ruleName (TCP 22, all profiles)"\r | |
| 616 | }\r | |
| 617 | }\r | |
| 618 | } catch {\r | |
| 619 | Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"\r | |
| 620 | }\r | |
| 621 | \r | |
| 622 | # ---------------------------------------------------------------------------\r | |
| 623 | # rsync for Windows (github.com/nuket/rsync-windows)\r | |
| 624 | #\r | |
| 625 | # Windows' OpenSSH ships the transport only - no rsync - so pushing test data\r | |
| 626 | # from a Linux box needs an rsync.exe on the Windows side.\r | |
| 627 | #\r | |
| b8144088 MV |
628 | # The release is one zip per architecture - rsync-windows-x64.zip and\r |
| 629 | # rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the\r | |
| 630 | # licence texts under exactly those names. Both exes are installed, together:\r | |
| 631 | # rsync.exe prefers an ssh.exe in its own directory, and the release's build is\r | |
| 632 | # what makes a push FROM this box run at line rate. The ssh.exe Windows ships\r | |
| 633 | # reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the\r | |
| 634 | # link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same\r | |
| 635 | # known_hosts - and a bare `ssh` still resolves to the in-box client, which sits\r | |
| 636 | # ahead of C:\Tools\rsync on the machine PATH.\r | |
| 637 | #\r | |
| 638 | # That ssh.exe links against the libcrypto.dll the OpenSSH Client capability\r | |
| 639 | # above puts in System32: Windows' own LibreSSL, and the fast one, since it uses\r | |
| 640 | # AES-NI. No copy of it ships in the zip, so where the capability is missing we\r | |
| 641 | # unpack rsync alone rather than an ssh.exe that will not start.\r | |
| 642 | #\r | |
| 452f525c MV |
643 | # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is\r |
| 644 | # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes\r | |
| 645 | # the client-side --rsync-path escape hatch painful to quote. Added to the\r | |
| 646 | # MACHINE PATH so it resolves for every account, including the non-interactive\r | |
| 647 | # sshd session, which builds its environment from the machine + user registry\r | |
| 648 | # PATH rather than from a login shell.\r | |
| 649 | #\r | |
| 650 | # Non-fatal: a download failure only warns.\r | |
| 651 | # ---------------------------------------------------------------------------\r | |
| 652 | Write-Step 'rsync for Windows'\r | |
| b8144088 MV |
653 | $RsyncRepo = 'nuket/rsync-windows'\r |
| 654 | $RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }\r | |
| 655 | # The /releases/latest/download/ redirect rather than the API: unauthenticated\r | |
| 656 | # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a\r | |
| 657 | # shared NAT can genuinely exhaust, and the redirect costs none of that budget.\r | |
| 658 | # To hold a box on a known build, pin the tag instead:\r | |
| 659 | # .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset\r | |
| 660 | $RsyncUrl = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"\r | |
| 661 | $RsyncDir = 'C:\Tools\rsync'\r | |
| 452f525c MV |
662 | try {\r |
| 663 | New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null\r | |
| 664 | $RsyncExe = Join-Path $RsyncDir 'rsync.exe'\r | |
| b8144088 MV |
665 | \r |
| 666 | # Does the release's ssh.exe have the libcrypto it needs? Decided before the\r | |
| 667 | # download so the answer can also gate what comes out of the zip.\r | |
| 668 | $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'\r | |
| 669 | $WantSsh = Test-Path $SysCrypto\r | |
| 670 | if (-not $WantSsh) {\r | |
| 671 | Write-Warning "$SysCrypto is missing - the OpenSSH Client capability is not installed - and the release's ssh.exe needs it. Installing rsync.exe only; rsync will use the ssh on the PATH."\r | |
| 672 | } else {\r | |
| 673 | $v = (Get-Item $SysCrypto).VersionInfo.FileVersion\r | |
| 674 | if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {\r | |
| 675 | Write-Warning "$SysCrypto is LibreSSL $v; the release's ssh.exe is built against 3.8.2 (Windows OpenSSH Client 9.5). Update Windows, or expect ssh.exe not to start."\r | |
| 676 | }\r | |
| 677 | }\r | |
| 678 | \r | |
| 679 | # Download and unpack beside the targets, not over them, so an interrupted\r | |
| 680 | # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch\r | |
| 681 | # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive\r | |
| 682 | # refuses any other extension outright ("*.download is not a supported\r | |
| 683 | # archive file format"), where PowerShell 7 just reads the file.\r | |
| 452f525c | 684 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\r |
| b8144088 MV |
685 | $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"\r |
| 686 | Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing\r | |
| 687 | Write-Host " Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"\r | |
| 688 | \r | |
| 689 | # Verify against the .sha256 published beside it. Same origin, so this is an\r | |
| 690 | # integrity check on the transfer rather than a defence against a hostile\r | |
| 691 | # release - but a truncated or proxy-mangled download is the failure that\r | |
| 692 | # actually happens, and it fails here instead of mid-transfer later.\r | |
| 693 | #\r | |
| 694 | # -OutFile, not .Content: GitHub serves the .sha256 as\r | |
| 695 | # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather\r | |
| 696 | # than a string for any non-text content type, so .Content would compare the\r | |
| 697 | # first BYTE against the hash and fail on every correct download.\r | |
| 698 | $tmpSha = "$tmpZip.sha256"\r | |
| 699 | Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing\r | |
| 700 | $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()\r | |
| 701 | Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue\r | |
| 702 | $got = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()\r | |
| 703 | if ($want -and $want -ne $got) {\r | |
| 704 | Remove-Item $tmpZip -Force\r | |
| 705 | throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"\r | |
| 706 | }\r | |
| 707 | Write-Host " SHA-256 verified: $got"\r | |
| 708 | \r | |
| 709 | # Unpack to a scratch directory and move out the files we asked for, rather\r | |
| 710 | # than expanding straight over the install directory: the zip is the unit\r | |
| 711 | # that was checksummed, and this way a future release adding something to it\r | |
| 712 | # cannot quietly drop that something onto the machine PATH.\r | |
| 713 | $unpack = Join-Path $RsyncDir '.unpack'\r | |
| 714 | if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }\r | |
| 715 | Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force\r | |
| 716 | Remove-Item $tmpZip -Force\r | |
| 717 | foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {\r | |
| 718 | $src = Join-Path $unpack $f\r | |
| 719 | if (-not (Test-Path $src)) { continue }\r | |
| 720 | if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }\r | |
| 721 | Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force\r | |
| 722 | }\r | |
| 723 | Remove-Item -Recurse -Force $unpack\r | |
| 724 | Write-Host " Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"\r | |
| 452f525c MV |
725 | \r |
| 726 | # Machine PATH (HKLM environment). Idempotent: only appends if absent.\r | |
| 727 | $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r | |
| 728 | if (-not $m) { $m = '' }\r | |
| 729 | if (($m -split ';') -notcontains $RsyncDir) {\r | |
| 730 | $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }\r | |
| 731 | [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r | |
| 732 | Write-Host " Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."\r | |
| 733 | # sshd caches the environment it was started with, so an already-running\r | |
| 734 | # service would not see the new PATH until restarted.\r | |
| 735 | if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {\r | |
| 736 | Restart-Service sshd\r | |
| 737 | Write-Host ' Restarted sshd so it inherits the updated machine PATH.'\r | |
| 738 | }\r | |
| 739 | } else {\r | |
| 740 | Write-Host " OK: $RsyncDir already in the machine PATH"\r | |
| 741 | }\r | |
| 742 | \r | |
| 743 | & $RsyncExe --version | Select-Object -First 1\r | |
| 744 | } catch {\r | |
| 745 | Write-Warning "rsync install failed: $($_.Exception.Message)"\r | |
| b8144088 MV |
746 | Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"\r |
| 747 | Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."\r | |
| 452f525c MV |
748 | }\r |
| 749 | \r | |
| 3c096107 MV |
750 | # ---------------------------------------------------------------------------\r |
| 751 | # Visual Studio 2022 Community\r | |
| 752 | # ---------------------------------------------------------------------------\r | |
| 753 | $TempDir = Join-Path $env:TEMP 'dev_install'\r | |
| 754 | New-Item -ItemType Directory -Force -Path $TempDir | Out-Null\r | |
| 755 | \r | |
| 756 | # Component IDs split into independent groups so each can be installed in its\r | |
| 757 | # own pass. The base group is the known-good set; Clang and the Windows XP\r | |
| 758 | # toolset are layered on afterwards so a failure clearly identifies the culprit.\r | |
| 759 | # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community\r | |
| 760 | $BaseComponents = @(\r | |
| 761 | # Core C++ desktop workload\r | |
| 762 | 'Microsoft.VisualStudio.Workload.NativeDesktop'\r | |
| 763 | \r | |
| 764 | # Spectre-mitigated MSVC runtime libs\r | |
| 765 | 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'\r | |
| 766 | 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'\r | |
| 767 | \r | |
| 768 | # Spectre-mitigated ATL (needed for many driver/COM projects)\r | |
| 769 | 'Microsoft.VisualStudio.Component.VC.ATL.Spectre'\r | |
| 770 | \r | |
| 771 | # Windows 11 SDK — build number must match the WDK below\r | |
| 772 | 'Microsoft.VisualStudio.Component.Windows11SDK.26100'\r | |
| 773 | \r | |
| 774 | # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT\r | |
| 775 | # install this (it only prompts interactively), so it must be added here.\r | |
| 776 | 'Component.Microsoft.Windows.DriverKit'\r | |
| 777 | )\r | |
| 778 | \r | |
| 779 | # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang\r | |
| 780 | # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.\r | |
| 781 | $ClangComponents = @(\r | |
| 782 | 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'\r | |
| 783 | 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'\r | |
| 784 | )\r | |
| 785 | \r | |
| 786 | # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141\r | |
| 787 | # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;\r | |
| 788 | # WinXP layers the XP-compatible CRT/SDK on top of it.\r | |
| 789 | $XpComponents = @(\r | |
| 790 | 'Microsoft.VisualStudio.Component.VC.v141.x86.x64'\r | |
| 791 | 'Microsoft.VisualStudio.Component.WinXP'\r | |
| 792 | )\r | |
| 793 | \r | |
| 794 | # Detect an existing VS install via vswhere (ships with the VS Installer).\r | |
| 795 | # These are referenced by Invoke-VsModify via $script: scope.\r | |
| 796 | $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'\r | |
| 797 | $InstallPath = $null\r | |
| 798 | if (Test-Path $VsWhere) {\r | |
| 799 | $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r | |
| 800 | Select-Object -First 1\r | |
| 801 | }\r | |
| 802 | \r | |
| 803 | Write-Step 'Downloading VS2022 Community bootstrapper'\r | |
| 804 | $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'\r | |
| 805 | $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'\r | |
| 806 | Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing\r | |
| 807 | \r | |
| 808 | # Install in three sequential passes. The base set is installed first (this is\r | |
| 809 | # the configuration that previously worked); Clang and the XP toolset are added\r | |
| 810 | # afterwards. If one fails, its label pinpoints which group is responsible.\r | |
| 811 | Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents\r | |
| 812 | Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents\r | |
| 813 | Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents\r | |
| 814 | \r | |
| 815 | # ---------------------------------------------------------------------------\r | |
| 816 | # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped\r | |
| 817 | # it and the failure only surfaced at build time, so check on disk and fail\r | |
| 818 | # loudly here instead.\r | |
| 819 | # ---------------------------------------------------------------------------\r | |
| 820 | Write-Step 'Verifying v141 / XP toolset'\r | |
| 821 | $InstallPath = & $VsWhere -products '*' -property installationPath -format value |\r | |
| 822 | Select-Object -First 1\r | |
| 823 | $V141 = if ($InstallPath) {\r | |
| 824 | Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |\r | |
| 825 | Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1\r | |
| 826 | }\r | |
| 827 | if ($V141) {\r | |
| 828 | Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green\r | |
| 829 | } else {\r | |
| 830 | Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'\r | |
| 831 | Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'\r | |
| 832 | Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'\r | |
| 833 | Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools'\r | |
| 834 | }\r | |
| 835 | \r | |
| 836 | # ---------------------------------------------------------------------------\r | |
| 837 | # Windows Driver Kit (WDK 10.0.26100)\r | |
| 838 | # Build 26100 matches the Windows 11 SDK installed above.\r | |
| 839 | # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.\r | |
| 840 | # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").\r | |
| 841 | # ---------------------------------------------------------------------------\r | |
| 842 | $WdkVersion = '10.0.26100'\r | |
| 843 | $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `\r | |
| 844 | -ErrorAction SilentlyContinue).WdkBinRootVersioned\r | |
| 845 | \r | |
| 846 | if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {\r | |
| 847 | # Re-running wdksetup.exe for an already-present version returns exit code\r | |
| 848 | # 2008 (maintenance mode / nothing to do), which is not a real failure.\r | |
| 849 | Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"\r | |
| 850 | } else {\r | |
| 851 | Write-Step 'Downloading WDK installer'\r | |
| 852 | $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869'\r | |
| 853 | $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'\r | |
| 854 | Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing\r | |
| 855 | \r | |
| 856 | Write-Step 'Installing WDK'\r | |
| 857 | $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow\r | |
| 858 | Write-Host " WDK installer exit code: $($proc.ExitCode)"\r | |
| 859 | if ($proc.ExitCode -eq 2008) {\r | |
| 860 | # 2008 = the WDK is already present; the installer has nothing to do.\r | |
| 861 | Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow\r | |
| 862 | } else {\r | |
| 863 | Assert-ExitCode $proc.ExitCode 'WDK'\r | |
| 864 | }\r | |
| 865 | }\r | |
| 866 | \r | |
| 867 | # ---------------------------------------------------------------------------\r | |
| 99725a30 MV |
868 | # Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer\r |
| 869 | # (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.\r | |
| 870 | #\r | |
| 871 | # WPA is NOT a Visual Studio component and has no relationship to VS's own\r | |
| 872 | # Performance Profiler (a separate, .diagsession-based tool that cannot open an\r | |
| 873 | # .etl). It ships in exactly two places: as an optional FEATURE of the Windows\r | |
| 874 | # SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and\r | |
| 875 | # in the Windows ADK, which bundles the same toolkit. Whether the SDK install\r | |
| 876 | # that Visual Studio performs happens to select that feature varies with the VS\r | |
| 877 | # and SDK version - when it does, WPT lands in\r | |
| 878 | # %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK\r | |
| 879 | # puts that directory on the machine PATH itself - so this step DETECTS first\r | |
| 880 | # and only falls back to installing the ADK (winget owns the versioned download\r | |
| 881 | # URL, which makes it the reliable source) when nothing is there. That fallback\r | |
| 882 | # is a large download; to install just the toolkit instead, run the standalone\r | |
| 883 | # SDK setup with\r | |
| 884 | # winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q\r | |
| 885 | #\r | |
| 886 | # There is also a newer WPA in the Microsoft Store (`winget install --id\r | |
| 887 | # 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is\r | |
| 888 | # not installed here: the Store package needs an interactive, signed-in session,\r | |
| 889 | # which is exactly what this elevated, unattended half does not have.\r | |
| 890 | #\r | |
| 891 | # Idempotent and non-fatal - it never aborts provisioning.\r | |
| 3c096107 | 892 | # ---------------------------------------------------------------------------\r |
| 99725a30 MV |
893 | Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'\r |
| 894 | $WptDirs = @(\r | |
| 895 | (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),\r | |
| 896 | (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit'),\r | |
| 897 | (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')\r | |
| 3c096107 | 898 | )\r |
| 99725a30 MV |
899 | function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }\r |
| 900 | \r | |
| 901 | $WptDir = Find-WptDir\r | |
| 902 | if ($WptDir) {\r | |
| 903 | Write-Host " OK: WPT already present ($WptDir)" -ForegroundColor Green\r | |
| 3c096107 MV |
904 | } else {\r |
| 905 | try {\r | |
| 906 | winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r | |
| 907 | --accept-source-agreements --accept-package-agreements\r | |
| 908 | Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.'\r | |
| 99725a30 | 909 | $WptDir = Find-WptDir\r |
| 3c096107 MV |
910 | } catch {\r |
| 911 | Write-Warning "WPT install failed: $($_.Exception.Message)"\r | |
| 912 | Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r | |
| 913 | Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'\r | |
| 914 | }\r | |
| 915 | }\r | |
| 916 | \r | |
| 99725a30 MV |
917 | if ($WptDir) {\r |
| 918 | # Report what actually landed. wpa.exe is the piece people come looking for\r | |
| 919 | # and it is the one that is absent if a trimmed toolkit ever shows up.\r | |
| 920 | foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {\r | |
| 921 | $p = Join-Path $WptDir $tool\r | |
| 922 | if (Test-Path $p) {\r | |
| 923 | Write-Host " $tool $((Get-Item $p).VersionInfo.ProductVersion)"\r | |
| 924 | } else {\r | |
| 925 | Write-Warning "$tool is missing from $WptDir"\r | |
| 926 | }\r | |
| 927 | }\r | |
| 928 | \r | |
| 929 | # The WPT installer normally adds this to the machine PATH itself (and the\r | |
| 930 | # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for\r | |
| 931 | # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user\r | |
| 932 | # one so it also resolves for the non-interactive sshd sessions this box is\r | |
| 933 | # driven through, which build their environment from the registry PATH.\r | |
| 934 | # Compared trailing-backslash-insensitively - the installer's own entry has\r | |
| 935 | # one, and adding a second spelling of the same directory is just noise.\r | |
| 936 | $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r | |
| 937 | if (-not $m) { $m = '' }\r | |
| 938 | $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }\r | |
| 939 | if ($have) {\r | |
| 940 | Write-Host " OK: $WptDir already in the machine PATH"\r | |
| 941 | } else {\r | |
| 942 | $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }\r | |
| 943 | [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r | |
| 944 | Write-Host " Added $WptDir to the machine PATH (restart shells to pick it up)."\r | |
| 945 | }\r | |
| 946 | }\r | |
| 947 | \r | |
| 99725a30 | 948 | \r |
| 3c096107 MV |
949 | # ---------------------------------------------------------------------------\r |
| 950 | Write-Host "`nAll done." -ForegroundColor Green\r | |
| 951 | Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r | |
| 952 | \r | |
| 953 | }\r | |
| 954 | catch {\r | |
| 955 | $ExitCode = 1\r | |
| 956 | Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red\r | |
| 957 | if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }\r | |
| 958 | # Only fold in the VS Installer logs when a VS step actually failed; for other\r | |
| 959 | # steps (e.g. WDK) those logs are stale and misleading, so the message above\r | |
| 960 | # is what matters.\r | |
| 961 | if ($_.Exception.Message -match 'VS2022') {\r | |
| 962 | try { Show-VsSetupLogs } catch {}\r | |
| 963 | }\r | |
| 964 | }\r | |
| 965 | finally {\r | |
| 966 | try { Stop-Transcript | Out-Null } catch {}\r | |
| 967 | \r | |
| 968 | # This log was created by the elevated (admin) process, so by default the\r | |
| 969 | # non-elevated caller can't delete it (their token has Administrators marked\r | |
| 970 | # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs\r | |
| 971 | # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known\r | |
| 972 | # Users SID, used here so this is locale-independent.\r | |
| 973 | try {\r | |
| 974 | if (Test-Path $LogFile) {\r | |
| 975 | $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')\r | |
| 976 | $acl = Get-Acl -Path $LogFile\r | |
| 977 | $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(\r | |
| 978 | $usersSid, 'Modify', 'Allow')\r | |
| 979 | $acl.AddAccessRule($rule)\r | |
| 980 | Set-Acl -Path $LogFile -AclObject $acl\r | |
| 981 | }\r | |
| 982 | } catch {\r | |
| 983 | Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow\r | |
| 984 | }\r | |
| 985 | }\r | |
| 986 | \r | |
| 987 | exit $ExitCode\r |