1 #Requires -RunAsAdministrator
\r
3 setup-windows-with-uac.ps1
\r
4 Elevated portion of the Windows provisioning. Invoked by setup-windows.bat
\r
5 via Start-Process -Verb RunAs, or run manually from an Administrator prompt.
\r
7 What this installs / configures:
\r
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
10 - ssh-agent set to automatic + started
\r
11 - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22
\r
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
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
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
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
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
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
39 [string] $TraceUser = ''
\r
42 $ErrorActionPreference = 'Stop'
\r
44 function Write-Step([string]$Msg) {
\r
45 Write-Host "`n==> $Msg" -ForegroundColor Cyan
\r
48 function Assert-ExitCode([int]$Code, [string]$Step) {
\r
49 # 0 = success, 3010 = success + reboot required
\r
50 if ($Code -notin @(0, 3010)) {
\r
51 throw "$Step failed with exit code $Code"
\r
53 if ($Code -eq 3010) {
\r
54 Write-Host " [reboot required after $Step]" -ForegroundColor Yellow
\r
58 # ---------------------------------------------------------------------------
\r
59 # User rights assignment (LSA account rights)
\r
61 # Windows has no built-in cmdlet for "grant this SID this privilege". The two
\r
62 # ways to script it are secedit (export the whole USER_RIGHTS area to an INF,
\r
63 # edit one line, re-import) and the LSA API. The API is used here because it is
\r
64 # surgical: LsaAddAccountRights adds exactly one right to exactly one SID and is
\r
65 # a no-op when it is already held, where a secedit round-trip re-applies every
\r
66 # user right on the box to fix one of them. The GUI equivalent, for a human, is
\r
67 # secpol.msc > Local Policies > User Rights Assignment
\r
69 # The type is compiled on first use; C# 5 only, since Windows PowerShell 5.1's
\r
70 # Add-Type compiles with the in-box CodeDom compiler.
\r
71 # ---------------------------------------------------------------------------
\r
72 function Initialize-LsaRightsType {
\r
73 if ('LsaRights' -as [type]) { return }
\r
74 Add-Type -TypeDefinition @'
\r
76 using System.ComponentModel;
\r
77 using System.Runtime.InteropServices;
\r
79 public static class LsaRights
\r
81 [StructLayout(LayoutKind.Sequential)]
\r
82 private struct LSA_UNICODE_STRING
\r
84 public ushort Length;
\r
85 public ushort MaximumLength;
\r
86 public IntPtr Buffer;
\r
89 [StructLayout(LayoutKind.Sequential)]
\r
90 private struct LSA_OBJECT_ATTRIBUTES
\r
93 public IntPtr RootDirectory;
\r
94 public IntPtr ObjectName;
\r
95 public uint Attributes;
\r
96 public IntPtr SecurityDescriptor;
\r
97 public IntPtr SecurityQualityOfService;
\r
100 [DllImport("advapi32.dll", SetLastError = true)]
\r
101 private static extern uint LsaOpenPolicy(IntPtr systemName,
\r
102 ref LSA_OBJECT_ATTRIBUTES objectAttributes, uint desiredAccess, out IntPtr policyHandle);
\r
104 [DllImport("advapi32.dll", SetLastError = true)]
\r
105 private static extern uint LsaAddAccountRights(IntPtr policyHandle, byte[] accountSid,
\r
106 LSA_UNICODE_STRING[] userRights, uint countOfRights);
\r
108 [DllImport("advapi32.dll", SetLastError = true)]
\r
109 private static extern uint LsaEnumerateAccountRights(IntPtr policyHandle, byte[] accountSid,
\r
110 out IntPtr userRights, out uint countOfRights);
\r
112 [DllImport("advapi32.dll")]
\r
113 private static extern uint LsaClose(IntPtr policyHandle);
\r
115 [DllImport("advapi32.dll")]
\r
116 private static extern uint LsaFreeMemory(IntPtr buffer);
\r
118 [DllImport("advapi32.dll")]
\r
119 private static extern int LsaNtStatusToWinError(uint status);
\r
121 private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001;
\r
122 private const uint POLICY_CREATE_ACCOUNT = 0x00000010;
\r
123 private const uint POLICY_LOOKUP_NAMES = 0x00000800;
\r
125 // Returned by LsaEnumerateAccountRights when the SID holds no rights at all,
\r
126 // which is an empty list rather than an error.
\r
127 private const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
\r
129 private static IntPtr OpenPolicy()
\r
131 LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES();
\r
132 attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
\r
134 uint status = LsaOpenPolicy(IntPtr.Zero, ref attrs,
\r
135 POLICY_VIEW_LOCAL_INFORMATION | POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, out handle);
\r
136 if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }
\r
140 public static string[] Get(byte[] sid)
\r
142 IntPtr policy = OpenPolicy();
\r
147 uint status = LsaEnumerateAccountRights(policy, sid, out rights, out count);
\r
148 if (status == STATUS_OBJECT_NAME_NOT_FOUND) { return new string[0]; }
\r
149 if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }
\r
152 string[] result = new string[count];
\r
153 int stride = Marshal.SizeOf(typeof(LSA_UNICODE_STRING));
\r
154 for (int i = 0; i < count; i++)
\r
156 LSA_UNICODE_STRING s = (LSA_UNICODE_STRING)Marshal.PtrToStructure(
\r
157 new IntPtr(rights.ToInt64() + (long)i * stride), typeof(LSA_UNICODE_STRING));
\r
158 result[i] = Marshal.PtrToStringUni(s.Buffer, s.Length / 2);
\r
162 finally { LsaFreeMemory(rights); }
\r
164 finally { LsaClose(policy); }
\r
167 public static void Add(byte[] sid, string right)
\r
169 IntPtr policy = OpenPolicy();
\r
172 LSA_UNICODE_STRING[] rights = new LSA_UNICODE_STRING[1];
\r
173 rights[0].Buffer = Marshal.StringToHGlobalUni(right);
\r
174 // Length counts BYTES and excludes the terminator; MaximumLength includes it.
\r
175 rights[0].Length = (ushort)(right.Length * 2);
\r
176 rights[0].MaximumLength = (ushort)(right.Length * 2 + 2);
\r
179 uint status = LsaAddAccountRights(policy, sid, rights, 1);
\r
180 if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }
\r
182 finally { Marshal.FreeHGlobal(rights[0].Buffer); }
\r
184 finally { LsaClose(policy); }
\r
190 function Get-SidBytes([string]$Sid) {
\r
191 $s = New-Object System.Security.Principal.SecurityIdentifier($Sid)
\r
192 $bytes = New-Object byte[] $s.BinaryLength
\r
193 $s.GetBinaryForm($bytes, 0)
\r
197 function Get-AccountRight([string]$Sid) {
\r
198 Initialize-LsaRightsType
\r
199 return [LsaRights]::Get((Get-SidBytes $Sid))
\r
202 function Grant-AccountRight([string]$Sid, [string]$Right) {
\r
203 Initialize-LsaRightsType
\r
204 [LsaRights]::Add((Get-SidBytes $Sid), $Right)
\r
207 function Show-VsSetupLogs {
\r
208 # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because
\r
209 # this script runs elevated, that %TEMP% belongs to the elevated user and is
\r
210 # readable here even when it is NOT readable by the non-elevated caller. Fold
\r
211 # only the NEWEST installer + bootstrapper log into the transcript (the setup
\r
212 # engine log is where per-component / product errors actually appear) and
\r
213 # keep it short so the transcript stays readable.
\r
214 Write-Host "`n==> Collecting VS Installer logs from $env:TEMP" -ForegroundColor Cyan
\r
215 $recent = Get-ChildItem $env:TEMP -Filter 'dd_*.log' -ErrorAction SilentlyContinue |
\r
216 Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-15) }
\r
218 $picks += $recent | Where-Object { $_.Name -like 'dd_installer_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
219 $picks += $recent | Where-Object { $_.Name -like 'dd_bootstrapper_*' } | Sort-Object LastWriteTime | Select-Object -Last 1
\r
220 $picks = $picks | Where-Object { $_ }
\r
222 Write-Host ' (no VS Installer logs modified in the last 15 minutes)' -ForegroundColor Yellow
\r
225 foreach ($l in $picks) {
\r
226 Write-Host "`n----- $($l.Name) (tail) -----" -ForegroundColor Yellow
\r
227 Get-Content $l.FullName -Tail 40
\r
231 function Invoke-VsModify {
\r
232 # Run one VS install/modify pass for a named group of components. Splitting
\r
233 # the install into separate passes makes it obvious WHICH group fails: each
\r
234 # call prints its label and exit code before Assert-ExitCode throws.
\r
239 Write-Step "VS2022: $Label"
\r
240 $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' '
\r
241 # --installPath must be quoted: it contains spaces ("C:\Program Files\...").
\r
242 # Windows PowerShell 5.1's Start-Process does not quote array elements, so we
\r
243 # hand-build a single string. Component IDs / flags have no spaces.
\r
244 $common = '--includeRecommended --quiet --norestart --wait'
\r
245 if ($script:InstallPath) {
\r
246 $argString = "modify --installPath `"$script:InstallPath`" $addStr $common --force"
\r
248 # No existing install yet -> this first pass performs the base install.
\r
249 $argString = "$addStr $common"
\r
251 Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray
\r
252 $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow
\r
253 Write-Host " exit code: $($p.ExitCode)"
\r
254 Assert-ExitCode $p.ExitCode "VS2022 ($Label)"
\r
256 # After the first (fresh) install, re-detect the install path so subsequent
\r
257 # passes use `modify`.
\r
258 if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) {
\r
259 $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value |
\r
260 Select-Object -First 1
\r
264 # ---------------------------------------------------------------------------
\r
265 # This runs in a separate elevated window that closes the moment it exits, so
\r
266 # the non-elevated caller (setup-windows.bat) can't see what happened. Mirror
\r
267 # all output to a log next to the script and exit with a real code so the
\r
268 # caller can detect success/failure and show the log.
\r
269 # ---------------------------------------------------------------------------
\r
270 $LogFile = Join-Path $PSScriptRoot 'setup-windows-uac.log'
\r
272 try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}
\r
276 # ---------------------------------------------------------------------------
\r
277 # Base tools via winget
\r
278 # ---------------------------------------------------------------------------
\r
280 # ---------------------------------------------------------------------------
\r
283 # Present by default on Windows 10 1809+ / Windows 11, but removable, and absent
\r
284 # from some Server images. Two things below want it: rsync does not speak ssh
\r
285 # itself, it execs an ssh binary, and the release's own ssh.exe links against the
\r
286 # libcrypto.dll this capability puts in System32. It also owns the ssh-agent
\r
287 # service configured next, so a missing client is why that step would fail.
\r
289 # Non-fatal, like the server half below: a box that cannot have it should still
\r
290 # finish provisioning.
\r
291 # ---------------------------------------------------------------------------
\r
292 Write-Step 'OpenSSH Client'
\r
294 $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |
\r
295 Select-Object -First 1
\r
297 Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'
\r
298 } elseif ($sshc.State -eq 'Installed') {
\r
299 Write-Host " OK: $($sshc.Name) already installed"
\r
301 Write-Host " Installing $($sshc.Name) ..."
\r
302 $r = Add-WindowsCapability -Online -Name $sshc.Name
\r
303 if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Client]' -ForegroundColor Yellow }
\r
306 Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"
\r
309 # ---------------------------------------------------------------------------
\r
311 # ---------------------------------------------------------------------------
\r
312 Write-Step 'Enabling ssh-agent'
\r
313 Set-Service -Name ssh-agent -StartupType Automatic
\r
314 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }
\r
316 # ---------------------------------------------------------------------------
\r
317 # OpenSSH Server (sshd)
\r
319 # Used to reach the test VMs (VirtualBox) from the host: remote shell plus the
\r
320 # transport rsync rides on when seeding test data in. Ships with Windows 10
\r
321 # 1809+ / Windows 11 as an on-demand capability, so no third-party install.
\r
323 # The capability normally adds the "OpenSSH Server (sshd)" inbound firewall
\r
324 # rule; we verify and create it if missing (it is absent on some images).
\r
326 # Non-fatal: a box that can't run sshd should still finish provisioning.
\r
327 # ---------------------------------------------------------------------------
\r
328 Write-Step 'OpenSSH Server (sshd)'
\r
330 $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |
\r
331 Select-Object -First 1
\r
333 Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'
\r
335 if ($sshd.State -ne 'Installed') {
\r
336 Write-Host " Installing $($sshd.Name) ..."
\r
337 $r = Add-WindowsCapability -Online -Name $sshd.Name
\r
338 if ($r.RestartNeeded) { Write-Host ' [reboot required after OpenSSH Server]' -ForegroundColor Yellow }
\r
340 Write-Host " OK: $($sshd.Name) already installed"
\r
343 Set-Service -Name sshd -StartupType Automatic
\r
344 if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }
\r
345 Write-Host ' sshd: Automatic + running'
\r
347 # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and
\r
348 # bridged adapters are frequently classified Public, and the capability's
\r
349 # own rule is Private-only on some images, which is what leaves a plainly
\r
350 # running sshd plainly unreachable.
\r
352 # OpenSSH-Server-In-TCP is the name the capability itself uses, so this
\r
353 # WIDENS that rule rather than adding a second one next to it. Creating
\r
354 # our own under a different name would leave the narrow rule in place and
\r
355 # the box still unreachable on a Public-classified adapter; creating one
\r
356 # under the same name would collide. Adopt it if present, create it if not.
\r
357 $ruleName = 'OpenSSH-Server-In-TCP'
\r
358 if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {
\r
359 Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any
\r
360 Write-Host " Widened firewall rule $ruleName to all profiles"
\r
362 New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `
\r
363 -Enabled True -Direction Inbound -Protocol TCP -Action Allow `
\r
364 -LocalPort 22 -Profile Any | Out-Null
\r
365 Write-Host " Added firewall rule $ruleName (TCP 22, all profiles)"
\r
369 Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"
\r
372 # ---------------------------------------------------------------------------
\r
373 # rsync for Windows (github.com/nuket/rsync-windows)
\r
375 # Windows' OpenSSH ships the transport only - no rsync - so pushing test data
\r
376 # from a Linux box needs an rsync.exe on the Windows side.
\r
378 # The release is one zip per architecture - rsync-windows-x64.zip and
\r
379 # rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the
\r
380 # licence texts under exactly those names. Both exes are installed, together:
\r
381 # rsync.exe prefers an ssh.exe in its own directory, and the release's build is
\r
382 # what makes a push FROM this box run at line rate. The ssh.exe Windows ships
\r
383 # reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the
\r
384 # link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same
\r
385 # known_hosts - and a bare `ssh` still resolves to the in-box client, which sits
\r
386 # ahead of C:\Tools\rsync on the machine PATH.
\r
388 # That ssh.exe links against the libcrypto.dll the OpenSSH Client capability
\r
389 # above puts in System32: Windows' own LibreSSL, and the fast one, since it uses
\r
390 # AES-NI. No copy of it ships in the zip, so where the capability is missing we
\r
391 # unpack rsync alone rather than an ssh.exe that will not start.
\r
393 # Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is
\r
394 # invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes
\r
395 # the client-side --rsync-path escape hatch painful to quote. Added to the
\r
396 # MACHINE PATH so it resolves for every account, including the non-interactive
\r
397 # sshd session, which builds its environment from the machine + user registry
\r
398 # PATH rather than from a login shell.
\r
400 # Non-fatal: a download failure only warns.
\r
401 # ---------------------------------------------------------------------------
\r
402 Write-Step 'rsync for Windows'
\r
403 $RsyncRepo = 'nuket/rsync-windows'
\r
404 $RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }
\r
405 # The /releases/latest/download/ redirect rather than the API: unauthenticated
\r
406 # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a
\r
407 # shared NAT can genuinely exhaust, and the redirect costs none of that budget.
\r
408 # To hold a box on a known build, pin the tag instead:
\r
409 # .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset
\r
410 $RsyncUrl = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"
\r
411 $RsyncDir = 'C:\Tools\rsync'
\r
413 New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null
\r
414 $RsyncExe = Join-Path $RsyncDir 'rsync.exe'
\r
416 # Does the release's ssh.exe have the libcrypto it needs? Decided before the
\r
417 # download so the answer can also gate what comes out of the zip.
\r
418 $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'
\r
419 $WantSsh = Test-Path $SysCrypto
\r
420 if (-not $WantSsh) {
\r
421 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
423 $v = (Get-Item $SysCrypto).VersionInfo.FileVersion
\r
424 if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {
\r
425 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
429 # Download and unpack beside the targets, not over them, so an interrupted
\r
430 # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch
\r
431 # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive
\r
432 # refuses any other extension outright ("*.download is not a supported
\r
433 # archive file format"), where PowerShell 7 just reads the file.
\r
434 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
\r
435 $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"
\r
436 Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing
\r
437 Write-Host " Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"
\r
439 # Verify against the .sha256 published beside it. Same origin, so this is an
\r
440 # integrity check on the transfer rather than a defence against a hostile
\r
441 # release - but a truncated or proxy-mangled download is the failure that
\r
442 # actually happens, and it fails here instead of mid-transfer later.
\r
444 # -OutFile, not .Content: GitHub serves the .sha256 as
\r
445 # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather
\r
446 # than a string for any non-text content type, so .Content would compare the
\r
447 # first BYTE against the hash and fail on every correct download.
\r
448 $tmpSha = "$tmpZip.sha256"
\r
449 Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing
\r
450 $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()
\r
451 Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue
\r
452 $got = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()
\r
453 if ($want -and $want -ne $got) {
\r
454 Remove-Item $tmpZip -Force
\r
455 throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"
\r
457 Write-Host " SHA-256 verified: $got"
\r
459 # Unpack to a scratch directory and move out the files we asked for, rather
\r
460 # than expanding straight over the install directory: the zip is the unit
\r
461 # that was checksummed, and this way a future release adding something to it
\r
462 # cannot quietly drop that something onto the machine PATH.
\r
463 $unpack = Join-Path $RsyncDir '.unpack'
\r
464 if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }
\r
465 Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force
\r
466 Remove-Item $tmpZip -Force
\r
467 foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {
\r
468 $src = Join-Path $unpack $f
\r
469 if (-not (Test-Path $src)) { continue }
\r
470 if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }
\r
471 Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force
\r
473 Remove-Item -Recurse -Force $unpack
\r
474 Write-Host " Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"
\r
476 # Machine PATH (HKLM environment). Idempotent: only appends if absent.
\r
477 $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')
\r
478 if (-not $m) { $m = '' }
\r
479 if (($m -split ';') -notcontains $RsyncDir) {
\r
480 $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }
\r
481 [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')
\r
482 Write-Host " Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."
\r
483 # sshd caches the environment it was started with, so an already-running
\r
484 # service would not see the new PATH until restarted.
\r
485 if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {
\r
486 Restart-Service sshd
\r
487 Write-Host ' Restarted sshd so it inherits the updated machine PATH.'
\r
490 Write-Host " OK: $RsyncDir already in the machine PATH"
\r
493 & $RsyncExe --version | Select-Object -First 1
\r
495 Write-Warning "rsync install failed: $($_.Exception.Message)"
\r
496 Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"
\r
497 Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."
\r
500 # ---------------------------------------------------------------------------
\r
501 # Visual Studio 2022 Community
\r
502 # ---------------------------------------------------------------------------
\r
503 $TempDir = Join-Path $env:TEMP 'dev_install'
\r
504 New-Item -ItemType Directory -Force -Path $TempDir | Out-Null
\r
506 # Component IDs split into independent groups so each can be installed in its
\r
507 # own pass. The base group is the known-good set; Clang and the Windows XP
\r
508 # toolset are layered on afterwards so a failure clearly identifies the culprit.
\r
509 # Component reference: https://learn.microsoft.com/visualstudio/install/workload-component-id-vs-community
\r
510 $BaseComponents = @(
\r
511 # Core C++ desktop workload
\r
512 'Microsoft.VisualStudio.Workload.NativeDesktop'
\r
514 # Spectre-mitigated MSVC runtime libs
\r
515 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre'
\r
516 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre'
\r
518 # Spectre-mitigated ATL (needed for many driver/COM projects)
\r
519 'Microsoft.VisualStudio.Component.VC.ATL.Spectre'
\r
521 # Windows 11 SDK — build number must match the WDK below
\r
522 'Microsoft.VisualStudio.Component.Windows11SDK.26100'
\r
524 # WDK Visual Studio extension (VSIX). The silent wdksetup.exe /quiet does NOT
\r
525 # install this (it only prompts interactively), so it must be added here.
\r
526 'Component.Microsoft.Windows.DriverKit'
\r
529 # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang
\r
530 # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset.
\r
531 $ClangComponents = @(
\r
532 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'
\r
533 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset'
\r
536 # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141
\r
537 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps;
\r
538 # WinXP layers the XP-compatible CRT/SDK on top of it.
\r
540 'Microsoft.VisualStudio.Component.VC.v141.x86.x64'
\r
541 'Microsoft.VisualStudio.Component.WinXP'
\r
544 # Detect an existing VS install via vswhere (ships with the VS Installer).
\r
545 # These are referenced by Invoke-VsModify via $script: scope.
\r
546 $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
\r
547 $InstallPath = $null
\r
548 if (Test-Path $VsWhere) {
\r
549 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
550 Select-Object -First 1
\r
553 Write-Step 'Downloading VS2022 Community bootstrapper'
\r
554 $VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe'
\r
555 $VsBootstrapper = Join-Path $TempDir 'vs_community.exe'
\r
556 Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing
\r
558 # Install in three sequential passes. The base set is installed first (this is
\r
559 # the configuration that previously worked); Clang and the XP toolset are added
\r
560 # afterwards. If one fails, its label pinpoints which group is responsible.
\r
561 Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents
\r
562 Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents
\r
563 Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents
\r
565 # ---------------------------------------------------------------------------
\r
566 # Verify the v141 / XP toolset actually landed. Earlier runs silently skipped
\r
567 # it and the failure only surfaced at build time, so check on disk and fail
\r
568 # loudly here instead.
\r
569 # ---------------------------------------------------------------------------
\r
570 Write-Step 'Verifying v141 / XP toolset'
\r
571 $InstallPath = & $VsWhere -products '*' -property installationPath -format value |
\r
572 Select-Object -First 1
\r
573 $V141 = if ($InstallPath) {
\r
574 Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
\r
575 Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1
\r
578 Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green
\r
580 Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.'
\r
581 Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:'
\r
582 Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)'
\r
583 Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools'
\r
586 # ---------------------------------------------------------------------------
\r
587 # Windows Driver Kit (WDK 10.0.26100)
\r
588 # Build 26100 matches the Windows 11 SDK installed above.
\r
589 # Provides IddCx (iddcx.h / iddcx.lib) and UMDF 2.x for Indirect Display Drivers.
\r
590 # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads").
\r
591 # ---------------------------------------------------------------------------
\r
592 $WdkVersion = '10.0.26100'
\r
593 $WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' `
\r
594 -ErrorAction SilentlyContinue).WdkBinRootVersioned
\r
596 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) {
\r
597 # Re-running wdksetup.exe for an already-present version returns exit code
\r
598 # 2008 (maintenance mode / nothing to do), which is not a real failure.
\r
599 Write-Step "WDK $WdkVersion already installed - skipping ($WdkInstalledRoot)"
\r
601 Write-Step 'Downloading WDK installer'
\r
602 $WdkUrl = 'https://go.microsoft.com/fwlink/?linkid=2335869'
\r
603 $WdkInstaller = Join-Path $TempDir 'wdksetup.exe'
\r
604 Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing
\r
606 Write-Step 'Installing WDK'
\r
607 $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow
\r
608 Write-Host " WDK installer exit code: $($proc.ExitCode)"
\r
609 if ($proc.ExitCode -eq 2008) {
\r
610 # 2008 = the WDK is already present; the installer has nothing to do.
\r
611 Write-Host ' [WDK already installed (exit 2008) - treating as success]' -ForegroundColor Yellow
\r
613 Assert-ExitCode $proc.ExitCode 'WDK'
\r
617 # ---------------------------------------------------------------------------
\r
618 # Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer
\r
619 # (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.
\r
621 # WPA is NOT a Visual Studio component and has no relationship to VS's own
\r
622 # Performance Profiler (a separate, .diagsession-based tool that cannot open an
\r
623 # .etl). It ships in exactly two places: as an optional FEATURE of the Windows
\r
624 # SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and
\r
625 # in the Windows ADK, which bundles the same toolkit. Whether the SDK install
\r
626 # that Visual Studio performs happens to select that feature varies with the VS
\r
627 # and SDK version - when it does, WPT lands in
\r
628 # %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK
\r
629 # puts that directory on the machine PATH itself - so this step DETECTS first
\r
630 # and only falls back to installing the ADK (winget owns the versioned download
\r
631 # URL, which makes it the reliable source) when nothing is there. That fallback
\r
632 # is a large download; to install just the toolkit instead, run the standalone
\r
634 # winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q
\r
636 # There is also a newer WPA in the Microsoft Store (`winget install --id
\r
637 # 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is
\r
638 # not installed here: the Store package needs an interactive, signed-in session,
\r
639 # which is exactly what this elevated, unattended half does not have.
\r
641 # Idempotent and non-fatal - it never aborts provisioning.
\r
642 # ---------------------------------------------------------------------------
\r
643 Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'
\r
645 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),
\r
646 (Join-Path $env:ProgramFiles 'Windows Kits\10\Windows Performance Toolkit'),
\r
647 (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')
\r
649 function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }
\r
651 $WptDir = Find-WptDir
\r
653 Write-Host " OK: WPT already present ($WptDir)" -ForegroundColor Green
\r
656 winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `
\r
657 --accept-source-agreements --accept-package-agreements
\r
658 Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.'
\r
659 $WptDir = Find-WptDir
\r
661 Write-Warning "WPT install failed: $($_.Exception.Message)"
\r
662 Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'
\r
663 Write-Warning 'Windows SDK "Windows Performance Toolkit" optional feature.'
\r
668 # Report what actually landed. wpa.exe is the piece people come looking for
\r
669 # and it is the one that is absent if a trimmed toolkit ever shows up.
\r
670 foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {
\r
671 $p = Join-Path $WptDir $tool
\r
672 if (Test-Path $p) {
\r
673 Write-Host " $tool $((Get-Item $p).VersionInfo.ProductVersion)"
\r
675 Write-Warning "$tool is missing from $WptDir"
\r
679 # The WPT installer normally adds this to the machine PATH itself (and the
\r
680 # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for
\r
681 # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user
\r
682 # one so it also resolves for the non-interactive sshd sessions this box is
\r
683 # driven through, which build their environment from the registry PATH.
\r
684 # Compared trailing-backslash-insensitively - the installer's own entry has
\r
685 # one, and adding a second spelling of the same directory is just noise.
\r
686 $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')
\r
687 if (-not $m) { $m = '' }
\r
688 $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }
\r
690 Write-Host " OK: $WptDir already in the machine PATH"
\r
692 $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }
\r
693 [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')
\r
694 Write-Host " Added $WptDir to the machine PATH (restart shells to pick it up)."
\r
698 # ---------------------------------------------------------------------------
\r
699 # ETW collection rights for an ordinary account
\r
701 # Out of the box, xperf and wpr only work elevated, and they fail in two
\r
702 # different ways for a standard user - because two different things are missing:
\r
704 # xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)"
\r
705 # wpr -start GeneralProfile
\r
706 # -> "Failed to enable the policy to profile system
\r
707 # performance." (0xc5585011)
\r
709 # 1. Creating or controlling ANY event tracing session - even a user-mode one
\r
710 # naming a single provider - is checked against the security descriptor ETW
\r
711 # keeps per provider GUID under
\r
712 # HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The default grants the
\r
713 # session-control rights (TRACELOG_CREATE_ONDISK, TRACELOG_CREATE_REALTIME,
\r
714 # TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to SYSTEM, Administrators, the
\r
715 # service accounts, and BUILTIN\Performance Log Users - and to nobody else.
\r
716 # That group is the supported hook; its own description says members "may
\r
717 # ... enable trace providers, and collect event traces".
\r
719 # 2. Switching on the kernel/system trace provider on top of that needs the
\r
720 # SeSystemProfilePrivilege user right ("Profile system performance"), held by
\r
721 # default only by Administrators and NT SERVICE\WdiServiceHost. That is the
\r
722 # one wpr names in its error, and the one xperf trips over for -on base.
\r
724 # So grant the privilege to the GROUP and then put the account in the group:
\r
725 # membership alone becomes the switch, and enabling the next account is one
\r
726 # `net localgroup` away with no policy edit.
\r
728 # Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU
\r
729 # sampling nor walking stacks in your own processes, and it is equivalent to
\r
730 # handing out administrator.
\r
732 # THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership
\r
733 # are baked into the access token at LOGON, and UAC hands an administrator a
\r
734 # filtered token that keeps just five harmless privileges - so an admin's
\r
735 # ordinary shell still cannot trace, however the policy reads. Running as a
\r
736 # standard user is what makes this work.
\r
738 # For the same reason nothing here takes effect in an already-open session: the
\r
739 # account has to sign out and back in. Any NEW logon does it - an ssh login into
\r
740 # this box is one, which is the quick way to check without dropping the desktop.
\r
742 # Analysis never needed any of this: wpa.exe opens an existing .etl as a plain
\r
743 # user. This step is only about collection.
\r
744 # ---------------------------------------------------------------------------
\r
745 Write-Step 'ETW collection rights (non-elevated xperf / wpr)'
\r
746 $PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users
\r
748 # --- The user right, granted to the group ---
\r
749 $existing = Get-AccountRight $PerfLogUsersSid
\r
750 if ($existing -contains 'SeSystemProfilePrivilege') {
\r
751 Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege'
\r
753 Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'
\r
754 Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'
\r
757 # --- The membership ---
\r
758 # Fall back to the console user when the caller did not name one: with
\r
759 # over-the-shoulder elevation that is the person who started
\r
760 # setup-windows.bat, which is who wants to trace.
\r
761 $target = $TraceUser
\r
762 if (-not $target) {
\r
763 $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName
\r
764 if ($target) { Write-Host " No -TraceUser given; using the console user $target" }
\r
767 if (-not $target) {
\r
768 Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'
\r
769 Write-Warning 'The user right is in place, so this is the only step left:'
\r
770 Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add'
\r
772 # Resolve to a SID first: it validates the name, and it is what the
\r
773 # membership check compares, so a member spelled ".\claude" in one place
\r
774 # and "LATISLAB\claude" in another is still recognised as the same account.
\r
775 $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(
\r
776 [System.Security.Principal.SecurityIdentifier])
\r
778 # By SID, never by name: "Performance Log Users" is localised, and
\r
779 # Get-LocalGroup -SID is how this stays correct on a non-English box.
\r
780 $group = Get-LocalGroup -SID $PerfLogUsersSid
\r
782 # Get-LocalGroupMember throws on a group holding a SID that no longer
\r
783 # resolves (a known Windows 10 bug), so a failure to READ the membership
\r
784 # must not stop us from writing it - fall through and let the add report.
\r
787 $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |
\r
788 Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0
\r
790 Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray
\r
794 Write-Host " OK: $target is already in $($group.Name)"
\r
797 Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value
\r
799 # "already a member" is only reachable when the enumeration above
\r
800 # failed, and is not an error. Matched on the type NAME rather
\r
801 # than in a typed catch clause: catch types are resolved when the
\r
802 # script is PARSED, before the LocalAccounts module has been
\r
803 # autoloaded, so naming the type there is a parse error that
\r
804 # would take the whole script down.
\r
805 if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }
\r
807 Write-Host " Added $target to $($group.Name)"
\r
811 Write-Host " $target must sign out and back in before this takes effect." -ForegroundColor Yellow
\r
812 Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow
\r
813 Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow
\r
814 Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow
\r
817 Write-Warning "ETW rights setup failed: $($_.Exception.Message)"
\r
818 Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'
\r
819 Write-Warning '"Profile system performance" > add Performance Log Users, then'
\r
820 Write-Warning ' net localgroup "Performance Log Users" <user> /add'
\r
823 # ---------------------------------------------------------------------------
\r
824 Write-Host "`nAll done." -ForegroundColor Green
\r
825 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'
\r
830 Write-Host "`n==> SETUP FAILED: $($_.Exception.Message)" -ForegroundColor Red
\r
831 if ($_.ScriptStackTrace) { Write-Host $_.ScriptStackTrace -ForegroundColor DarkGray }
\r
832 # Only fold in the VS Installer logs when a VS step actually failed; for other
\r
833 # steps (e.g. WDK) those logs are stale and misleading, so the message above
\r
835 if ($_.Exception.Message -match 'VS2022') {
\r
836 try { Show-VsSetupLogs } catch {}
\r
840 try { Stop-Transcript | Out-Null } catch {}
\r
842 # This log was created by the elevated (admin) process, so by default the
\r
843 # non-elevated caller can't delete it (their token has Administrators marked
\r
844 # deny-only). Grant BUILTIN\Users Modify rights so the user account that runs
\r
845 # setup-windows.bat can remove the log later. S-1-5-32-545 is the well-known
\r
846 # Users SID, used here so this is locale-independent.
\r
848 if (Test-Path $LogFile) {
\r
849 $usersSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-545')
\r
850 $acl = Get-Acl -Path $LogFile
\r
851 $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
\r
852 $usersSid, 'Modify', 'Allow')
\r
853 $acl.AddAccessRule($rule)
\r
854 Set-Acl -Path $LogFile -AclObject $acl
\r
857 Write-Host " [warning] could not relax ACL on $LogFile : $($_.Exception.Message)" -ForegroundColor Yellow
\r