]> vilimpoc.org git repositories - dotfiles/blobdiff - setup-windows-with-uac.ps1
dotfiles: report Intel VTune rather than installing it
[dotfiles] / setup-windows-with-uac.ps1
index 254db14e59deeb03a19e68a3dcbca0bae28fa4ae..34bfa8b4cd7a272fad50c837c78bec4b7de8f799 100644 (file)
@@ -1,20 +1,51 @@
 #Requires -RunAsAdministrator\r
 <#\r
   setup-windows-with-uac.ps1\r
-  Elevated portion of BlockBox Windows provisioning. Invoked by setup-windows.bat\r
+  Elevated portion of the Windows provisioning. Invoked by setup-windows.bat\r
   via Start-Process -Verb RunAs, or run manually from an Administrator prompt.\r
 \r
   What this installs / configures:\r
+    - OpenSSH Client capability (the ssh.exe rsync shells out to, and the\r
+      System32 libcrypto.dll the release's own ssh.exe links against)\r
     - ssh-agent set to automatic + started\r
+    - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22\r
+    - rsync for Windows (nuket/rsync-windows) in C:\Tools\rsync, on the machine\r
+      PATH: rsync.exe plus the ssh.exe it runs, out of the release zip for this\r
+      architecture\r
     - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,\r
       Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)\r
     - Windows Driver Kit 10.0.26100\r
+    - Windows Performance Toolkit - xperf, wpr and Windows Performance Analyzer\r
+      (wpa.exe) - on the machine PATH\r
+    - ETW collection rights for one ordinary account: Performance Log Users\r
+      membership plus the "Profile system performance" user right, so xperf and\r
+      wpr run WITHOUT elevation\r
 \r
   Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r
     Professional : https://aka.ms/vs/17/release/vs_professional.exe\r
     Enterprise   : https://aka.ms/vs/17/release/vs_enterprise.exe\r
 #>\r
 \r
+param(\r
+    # Account to be granted non-elevated ETW collection rights (see the "ETW\r
+    # collection rights" step at the bottom). Defaults to the interactive\r
+    # console user, but setup-windows.bat passes it explicitly: with\r
+    # over-the-shoulder elevation THIS script runs as the administrator whose\r
+    # credentials went into the UAC prompt, not as the user who started the\r
+    # batch file, so $env:USERNAME here is the wrong answer.\r
+    #\r
+    # Pass an empty string to skip the group membership (the user right is still\r
+    # granted to the group, so adding an account later is one command).\r
+    [string] $TraceUser = '',\r
+\r
+    # Do the ETW rights step and nothing else. That step is seconds of registry\r
+    # and LSA work with no downloads, where a full run is dominated by the three\r
+    # Visual Studio passes, which take minutes even when they have nothing to do.\r
+    # It is why the ETW step runs FIRST: -EtwRightsOnly is then just an early\r
+    # exit rather than a set of guards down the rest of the script.\r
+    [switch] $EtwRightsOnly\r
+)\r
+\r
 $ErrorActionPreference = 'Stop'\r
 \r
 function Write-Step([string]$Msg) {\r
@@ -31,6 +62,220 @@ function Assert-ExitCode([int]$Code, [string]$Step) {
     }\r
 }\r
 \r
+# ---------------------------------------------------------------------------\r
+# User rights assignment (LSA account rights)\r
+#\r
+# Windows has no built-in cmdlet for "grant this SID this privilege". The two\r
+# ways to script it are secedit (export the whole USER_RIGHTS area to an INF,\r
+# edit one line, re-import) and the LSA API. The API is used here because it is\r
+# surgical: LsaAddAccountRights adds exactly one right to exactly one SID and is\r
+# a no-op when it is already held, where a secedit round-trip re-applies every\r
+# user right on the box to fix one of them. The GUI equivalent, for a human, is\r
+#     secpol.msc > Local Policies > User Rights Assignment\r
+#\r
+# The type is compiled on first use; C# 5 only, since Windows PowerShell 5.1's\r
+# Add-Type compiles with the in-box CodeDom compiler.\r
+# ---------------------------------------------------------------------------\r
+function Initialize-LsaRightsType {\r
+    if ('LsaRights' -as [type]) { return }\r
+    Add-Type -TypeDefinition @'\r
+using System;\r
+using System.ComponentModel;\r
+using System.Runtime.InteropServices;\r
+\r
+public static class LsaRights\r
+{\r
+    [StructLayout(LayoutKind.Sequential)]\r
+    private struct LSA_UNICODE_STRING\r
+    {\r
+        public ushort Length;\r
+        public ushort MaximumLength;\r
+        public IntPtr Buffer;\r
+    }\r
+\r
+    [StructLayout(LayoutKind.Sequential)]\r
+    private struct LSA_OBJECT_ATTRIBUTES\r
+    {\r
+        public int Length;\r
+        public IntPtr RootDirectory;\r
+        public IntPtr ObjectName;\r
+        public uint Attributes;\r
+        public IntPtr SecurityDescriptor;\r
+        public IntPtr SecurityQualityOfService;\r
+    }\r
+\r
+    [DllImport("advapi32.dll", SetLastError = true)]\r
+    private static extern uint LsaOpenPolicy(IntPtr systemName,\r
+        ref LSA_OBJECT_ATTRIBUTES objectAttributes, uint desiredAccess, out IntPtr policyHandle);\r
+\r
+    [DllImport("advapi32.dll", SetLastError = true)]\r
+    private static extern uint LsaAddAccountRights(IntPtr policyHandle, byte[] accountSid,\r
+        LSA_UNICODE_STRING[] userRights, uint countOfRights);\r
+\r
+    [DllImport("advapi32.dll", SetLastError = true)]\r
+    private static extern uint LsaEnumerateAccountRights(IntPtr policyHandle, byte[] accountSid,\r
+        out IntPtr userRights, out uint countOfRights);\r
+\r
+    [DllImport("advapi32.dll")]\r
+    private static extern uint LsaClose(IntPtr policyHandle);\r
+\r
+    [DllImport("advapi32.dll")]\r
+    private static extern uint LsaFreeMemory(IntPtr buffer);\r
+\r
+    [DllImport("advapi32.dll")]\r
+    private static extern int LsaNtStatusToWinError(uint status);\r
+\r
+    private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001;\r
+    private const uint POLICY_CREATE_ACCOUNT         = 0x00000010;\r
+    private const uint POLICY_LOOKUP_NAMES           = 0x00000800;\r
+\r
+    // Returned by LsaEnumerateAccountRights when the SID holds no rights at all,\r
+    // which is an empty list rather than an error.\r
+    private const uint STATUS_OBJECT_NAME_NOT_FOUND  = 0xC0000034;\r
+\r
+    private static IntPtr OpenPolicy()\r
+    {\r
+        LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES();\r
+        attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));\r
+        IntPtr handle;\r
+        uint status = LsaOpenPolicy(IntPtr.Zero, ref attrs,\r
+            POLICY_VIEW_LOCAL_INFORMATION | POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, out handle);\r
+        if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
+        return handle;\r
+    }\r
+\r
+    public static string[] Get(byte[] sid)\r
+    {\r
+        IntPtr policy = OpenPolicy();\r
+        try\r
+        {\r
+            IntPtr rights;\r
+            uint count;\r
+            uint status = LsaEnumerateAccountRights(policy, sid, out rights, out count);\r
+            if (status == STATUS_OBJECT_NAME_NOT_FOUND) { return new string[0]; }\r
+            if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
+            try\r
+            {\r
+                string[] result = new string[count];\r
+                int stride = Marshal.SizeOf(typeof(LSA_UNICODE_STRING));\r
+                for (int i = 0; i < count; i++)\r
+                {\r
+                    LSA_UNICODE_STRING s = (LSA_UNICODE_STRING)Marshal.PtrToStructure(\r
+                        new IntPtr(rights.ToInt64() + (long)i * stride), typeof(LSA_UNICODE_STRING));\r
+                    result[i] = Marshal.PtrToStringUni(s.Buffer, s.Length / 2);\r
+                }\r
+                return result;\r
+            }\r
+            finally { LsaFreeMemory(rights); }\r
+        }\r
+        finally { LsaClose(policy); }\r
+    }\r
+\r
+    public static void Add(byte[] sid, string right)\r
+    {\r
+        IntPtr policy = OpenPolicy();\r
+        try\r
+        {\r
+            LSA_UNICODE_STRING[] rights = new LSA_UNICODE_STRING[1];\r
+            rights[0].Buffer = Marshal.StringToHGlobalUni(right);\r
+            // Length counts BYTES and excludes the terminator; MaximumLength includes it.\r
+            rights[0].Length = (ushort)(right.Length * 2);\r
+            rights[0].MaximumLength = (ushort)(right.Length * 2 + 2);\r
+            try\r
+            {\r
+                uint status = LsaAddAccountRights(policy, sid, rights, 1);\r
+                if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); }\r
+            }\r
+            finally { Marshal.FreeHGlobal(rights[0].Buffer); }\r
+        }\r
+        finally { LsaClose(policy); }\r
+    }\r
+}\r
+'@\r
+}\r
+\r
+function Get-SidBytes([string]$Sid) {\r
+    $s = New-Object System.Security.Principal.SecurityIdentifier($Sid)\r
+    $bytes = New-Object byte[] $s.BinaryLength\r
+    $s.GetBinaryForm($bytes, 0)\r
+    return ,$bytes\r
+}\r
+\r
+function Get-AccountRight([string]$Sid) {\r
+    Initialize-LsaRightsType\r
+    return [LsaRights]::Get((Get-SidBytes $Sid))\r
+}\r
+\r
+function Grant-AccountRight([string]$Sid, [string]$Right) {\r
+    Initialize-LsaRightsType\r
+    [LsaRights]::Add((Get-SidBytes $Sid), $Right)\r
+}\r
+\r
+# ---------------------------------------------------------------------------\r
+# ETW provider-GUID access control\r
+#\r
+# ETW keeps a security descriptor per provider GUID under\r
+# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security, and EventAccessControl is\r
+# the documented way to edit one. Editing the registry value directly would work\r
+# too - it is a self-relative SD in a REG_BINARY - but the API takes the SID and\r
+# the rights mask and leaves the descriptor's shape to Windows.\r
+# ---------------------------------------------------------------------------\r
+function Initialize-EtwAclType {\r
+    if ('EtwAcl' -as [type]) { return }\r
+    Add-Type -TypeDefinition @'\r
+using System;\r
+using System.Runtime.InteropServices;\r
+\r
+public static class EtwAcl\r
+{\r
+    // ULONG EventAccessControl(LPGUID, ULONG Operation, PSID, ULONG Rights, BOOLEAN AllowOrDeny)\r
+    [DllImport("advapi32.dll", SetLastError = true)]\r
+    public static extern uint EventAccessControl(ref Guid guid, uint operation, byte[] sid,\r
+        uint rights, [MarshalAs(UnmanagedType.U1)] bool allowOrDeny);\r
+\r
+    // ULONG EventAccessQuery(LPGUID, PSECURITY_DESCRIPTOR, PULONG BufferSize)\r
+    [DllImport("advapi32.dll", SetLastError = true)]\r
+    public static extern uint EventAccessQuery(ref Guid guid, byte[] buffer, ref uint bufferSize);\r
+}\r
+'@\r
+}\r
+\r
+# The rights a session controller needs, from evntrace.h:\r
+#   0x0001 WMIGUID_QUERY               0x0100 TRACELOG_ACCESS_KERNEL_LOGGER\r
+#   0x0020 TRACELOG_CREATE_REALTIME    0x0200 TRACELOG_LOG_EVENT\r
+#   0x0040 TRACELOG_CREATE_ONDISK      0x0400 TRACELOG_ACCESS_REALTIME\r
+#   0x0080 TRACELOG_GUID_ENABLE        0x0800 TRACELOG_REGISTER_GUIDS\r
+# TRACELOG_ACCESS_KERNEL_LOGGER is the one that names the NT Kernel Logger\r
+# specifically; the rest are what any controller needs to create a session,\r
+# write it to disk and enable providers on it.\r
+#\r
+# READ_CONTROL (0x20000) and SYNCHRONIZE (0x100000) go with them - the SYSTEM and\r
+# Administrators entries on this GUID carry 0x120FFF. Without READ_CONTROL the\r
+# group cannot read the descriptor back, which makes EventAccessQuery useless as\r
+# a check on whether the grant landed: it answers "access denied" either way.\r
+$EtwControllerRights = 0x120FE1\r
+\r
+function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) {\r
+    Initialize-EtwAclType\r
+    $g = [Guid]$Guid\r
+    # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing\r
+    # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which\r
+    # on the kernel logger means removing the entries Windows itself relies on.\r
+    $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true)\r
+    if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) }\r
+}\r
+\r
+function Get-EtwGuidSddl([string]$Guid) {\r
+    Initialize-EtwAclType\r
+    $g = [Guid]$Guid\r
+    $size = [uint32]0\r
+    [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size)\r
+    if ($size -eq 0) { return $null }\r
+    $buf = New-Object byte[] $size\r
+    if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null }\r
+    return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access')\r
+}\r
+\r
 function Show-VsSetupLogs {\r
     # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because\r
     # this script runs elevated, that %TEMP% belongs to the elevated user and is\r
@@ -100,9 +345,217 @@ try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}
 \r
 try {\r
 \r
+# ---------------------------------------------------------------------------\r
+# ETW collection rights for an ordinary account\r
+#\r
+# Out of the box, xperf and wpr only work elevated. THREE separate things stand\r
+# in a standard user's way, and each has its own error:\r
+#\r
+#     xperf -on base         -> "NT Kernel Logger: Access is denied. (0x5)"\r
+#     wpr -start GeneralProfile\r
+#                            -> "Failed to enable the policy to profile system\r
+#                                performance."  (0xc5585011)\r
+#\r
+# 1. Creating or controlling ANY event tracing session - even a user-mode one\r
+#    naming a single provider - is checked against the security descriptor ETW\r
+#    keeps per provider GUID under\r
+#    HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor\r
+#    grants the session-control rights (TRACELOG_CREATE_ONDISK,\r
+#    TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to\r
+#    SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log\r
+#    Users - and to nobody else. That group is the supported hook; its own\r
+#    description says members "may ... enable trace providers, and collect event\r
+#    traces".\r
+#\r
+# 2. Switching on the kernel/system trace provider on top of that needs the\r
+#    SeSystemProfilePrivilege user right ("Profile system performance"), held by\r
+#    default only by Administrators and NT SERVICE\WdiServiceHost. That is the\r
+#    one wpr names in its error.\r
+#\r
+# 3. The kernel logger is not covered by that default descriptor. Its own GUID -\r
+#    SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries\r
+#    an explicit descriptor that does not mention Performance Log Users, so 1 and\r
+#    2 are not enough by themselves. Measured on this box with both in place: a\r
+#    user-mode session starts (exit 0) and the account holds the privilege, and\r
+#    `xperf -on base` still answers "NT Kernel Logger: Access is denied" while\r
+#    wpr's error changes from the policy message above to a bare 0x80070005.\r
+#    Even READING that descriptor comes back access-denied, which is the tell. So\r
+#    add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER\r
+#    is the right that names this particular session.\r
+#\r
+# The privilege and the ACE both go to the GROUP, and the account then goes into\r
+# the group: membership alone becomes the switch, and enabling the next account\r
+# is one `net localgroup` away with no policy or registry edit.\r
+#\r
+# What this costs, stated plainly: a member of that group can capture\r
+# system-wide kernel traces - process, image, file and registry activity across\r
+# every account on the box, paths and command lines included. That is what the\r
+# group is for, and it is the price of collecting a trace without a UAC prompt.\r
+#\r
+# Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU\r
+# sampling nor walking stacks in your own processes, and it is equivalent to\r
+# handing out administrator.\r
+#\r
+# THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership\r
+# are baked into the access token at LOGON, and UAC hands an administrator a\r
+# filtered token that keeps just five harmless privileges - so an admin's\r
+# ordinary shell still cannot trace, however the policy reads. Running as a\r
+# standard user is what makes this work.\r
+#\r
+# For the same reason 1 and 2 do not take effect in an already-open session: the\r
+# account has to sign out and back in. Any NEW logon does it - an ssh login into\r
+# this box is one, which is the quick way to check without dropping the desktop.\r
+# The ACE in 3 is machine state rather than token state, so a logon does nothing\r
+# for it. ETW reads these descriptors into a cache, so a REBOOT is what is\r
+# expected to put the change into effect: with the ACE written and readable in\r
+# the descriptor, xperf -on base was still answering "Access is denied" from a\r
+# fresh shell on the running system. So on a first run, plan on both - a new\r
+# logon for 1 and 2, a reboot for 3.\r
+#\r
+# Analysis never needed any of this: wpa.exe opens an existing .etl as a plain\r
+# user. This step is only about collection.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'ETW collection rights (non-elevated xperf / wpr)'\r
+$PerfLogUsersSid = 'S-1-5-32-559'   # BUILTIN\Performance Log Users\r
+# SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on\r
+# and wpr both drive. Fixed by contract, from evntrace.h.\r
+$SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939'\r
+try {\r
+    # --- The user right, granted to the group ---\r
+    $existing = Get-AccountRight $PerfLogUsersSid\r
+    if ($existing -contains 'SeSystemProfilePrivilege') {\r
+        Write-Host '    OK: Performance Log Users already holds SeSystemProfilePrivilege'\r
+    } else {\r
+        Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege'\r
+        Write-Host '    Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users'\r
+    }\r
+\r
+    # --- The kernel logger's own descriptor ---\r
+    # Safe to repeat: a second ACE for the same SID unions to the same access.\r
+    # Kept in its own try so that a failure here still leaves the group\r
+    # membership below to be done - user-mode sessions work without it.\r
+    #\r
+    # ETW reads these descriptors out of the registry into a cache, so a REBOOT\r
+    # is what puts a change here into effect - not a new logon, which is what the\r
+    # group membership and the privilege need. Both, on a first run.\r
+    try {\r
+        Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights\r
+        Write-Host ("    Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights)\r
+        $sddl = Get-EtwGuidSddl $SystemTraceControlGuid\r
+        if ($sddl) { Write-Host "    kernel logger DACL is now $sddl" -ForegroundColor DarkGray }\r
+    } catch {\r
+        Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)"\r
+        Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."'\r
+    }\r
+\r
+    # --- The membership ---\r
+    # Fall back to the console user when the caller did not name one: with\r
+    # over-the-shoulder elevation that is the person who started\r
+    # setup-windows.bat, which is who wants to trace.\r
+    $target = $TraceUser\r
+    if (-not $target) {\r
+        $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName\r
+        if ($target) { Write-Host "    No -TraceUser given; using the console user $target" }\r
+    }\r
+\r
+    if (-not $target) {\r
+        Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'\r
+        Write-Warning 'The user right is in place, so this is the only step left:'\r
+        Write-Warning '    net localgroup "Performance Log Users" DOMAIN\user /add'\r
+    } else {\r
+        # Resolve to a SID first: it validates the name, and it is what the\r
+        # membership check compares, so a member spelled ".\claude" in one place\r
+        # and "LATISLAB\claude" in another is still recognised as the same account.\r
+        $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(\r
+                        [System.Security.Principal.SecurityIdentifier])\r
+\r
+        # By SID, never by name: "Performance Log Users" is localised, and\r
+        # Get-LocalGroup -SID is how this stays correct on a non-English box.\r
+        $group = Get-LocalGroup -SID $PerfLogUsersSid\r
+\r
+        # Get-LocalGroupMember throws on a group holding a SID that no longer\r
+        # resolves (a known Windows 10 bug), so a failure to READ the membership\r
+        # must not stop us from writing it - fall through and let the add report.\r
+        $already = $false\r
+        try {\r
+            $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |\r
+                         Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0\r
+        } catch {\r
+            Write-Host "    (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray\r
+        }\r
+\r
+        if ($already) {\r
+            Write-Host "    OK: $target is already in $($group.Name)"\r
+        } else {\r
+            try {\r
+                Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value\r
+            } catch {\r
+                # "already a member" is only reachable when the enumeration above\r
+                # failed, and is not an error. Matched on the type NAME rather\r
+                # than in a typed catch clause: catch types are resolved when the\r
+                # script is PARSED, before the LocalAccounts module has been\r
+                # autoloaded, so naming the type there is a parse error that\r
+                # would take the whole script down.\r
+                if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }\r
+            }\r
+            Write-Host "    Added $target to $($group.Name)"\r
+        }\r
+\r
+        Write-Host ''\r
+        Write-Host "    $target must sign out and back in for the group and the privilege," -ForegroundColor Yellow\r
+        Write-Host '    and the box must be REBOOTED for the kernel logger ACE (ETW caches it).' -ForegroundColor Yellow\r
+        Write-Host '    Then, from that account (NOT elevated):' -ForegroundColor Yellow\r
+        Write-Host '        whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow\r
+        Write-Host '        xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow\r
+    }\r
+} catch {\r
+    Write-Warning "ETW rights setup failed: $($_.Exception.Message)"\r
+    Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >'\r
+    Write-Warning '"Profile system performance" > add Performance Log Users, then'\r
+    Write-Warning '    net localgroup "Performance Log Users" <user> /add'\r
+}\r
+\r
+if ($EtwRightsOnly) {\r
+    # `exit` inside the try still runs the finally below, so the transcript is\r
+    # stopped and the log is left readable by the non-elevated caller.\r
+    Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green\r
+    exit 0\r
+}\r
+\r
+\r
 # ---------------------------------------------------------------------------\r
 # Base tools via winget\r
 # ---------------------------------------------------------------------------\r
+\r
+# ---------------------------------------------------------------------------\r
+# OpenSSH Client\r
+#\r
+# Present by default on Windows 10 1809+ / Windows 11, but removable, and absent\r
+# from some Server images. Two things below want it: rsync does not speak ssh\r
+# itself, it execs an ssh binary, and the release's own ssh.exe links against the\r
+# libcrypto.dll this capability puts in System32. It also owns the ssh-agent\r
+# service configured next, so a missing client is why that step would fail.\r
+#\r
+# Non-fatal, like the server half below: a box that cannot have it should still\r
+# finish provisioning.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'OpenSSH Client'\r
+try {\r
+    $sshc = Get-WindowsCapability -Online -Name 'OpenSSH.Client*' |\r
+            Select-Object -First 1\r
+    if (-not $sshc) {\r
+        Write-Warning 'OpenSSH.Client capability not offered by this Windows image - skipping.'\r
+    } elseif ($sshc.State -eq 'Installed') {\r
+        Write-Host "    OK: $($sshc.Name) already installed"\r
+    } else {\r
+        Write-Host "    Installing $($sshc.Name) ..."\r
+        $r = Add-WindowsCapability -Online -Name $sshc.Name\r
+        if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Client]' -ForegroundColor Yellow }\r
+    }\r
+} catch {\r
+    Write-Warning "OpenSSH Client setup failed: $($_.Exception.Message)"\r
+}\r
+\r
 # ---------------------------------------------------------------------------\r
 # SSH agent\r
 # ---------------------------------------------------------------------------\r
@@ -110,6 +563,190 @@ Write-Step 'Enabling ssh-agent'
 Set-Service -Name ssh-agent -StartupType Automatic\r
 if ((Get-Service ssh-agent).Status -ne 'Running') { Start-Service ssh-agent }\r
 \r
+# ---------------------------------------------------------------------------\r
+# OpenSSH Server (sshd)\r
+#\r
+# Used to reach the test VMs (VirtualBox) from the host: remote shell plus the\r
+# transport rsync rides on when seeding test data in. Ships with Windows 10\r
+# 1809+ / Windows 11 as an on-demand capability, so no third-party install.\r
+#\r
+# The capability normally adds the "OpenSSH Server (sshd)" inbound firewall\r
+# rule; we verify and create it if missing (it is absent on some images).\r
+#\r
+# Non-fatal: a box that can't run sshd should still finish provisioning.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'OpenSSH Server (sshd)'\r
+try {\r
+    $sshd = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' |\r
+            Select-Object -First 1\r
+    if (-not $sshd) {\r
+        Write-Warning 'OpenSSH.Server capability not offered by this Windows image - skipping.'\r
+    } else {\r
+        if ($sshd.State -ne 'Installed') {\r
+            Write-Host "    Installing $($sshd.Name) ..."\r
+            $r = Add-WindowsCapability -Online -Name $sshd.Name\r
+            if ($r.RestartNeeded) { Write-Host '    [reboot required after OpenSSH Server]' -ForegroundColor Yellow }\r
+        } else {\r
+            Write-Host "    OK: $($sshd.Name) already installed"\r
+        }\r
+\r
+        Set-Service -Name sshd -StartupType Automatic\r
+        if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd }\r
+        Write-Host '    sshd: Automatic + running'\r
+\r
+        # Firewall: allow inbound 22 on all profiles. VirtualBox host-only and\r
+        # bridged adapters are frequently classified Public, and the capability's\r
+        # own rule is Private-only on some images, which is what leaves a plainly\r
+        # running sshd plainly unreachable.\r
+        #\r
+        # OpenSSH-Server-In-TCP is the name the capability itself uses, so this\r
+        # WIDENS that rule rather than adding a second one next to it. Creating\r
+        # our own under a different name would leave the narrow rule in place and\r
+        # the box still unreachable on a Public-classified adapter; creating one\r
+        # under the same name would collide. Adopt it if present, create it if not.\r
+        $ruleName = 'OpenSSH-Server-In-TCP'\r
+        if (Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue) {\r
+            Set-NetFirewallRule -Name $ruleName -Enabled True -Profile Any\r
+            Write-Host "    Widened firewall rule $ruleName to all profiles"\r
+        } else {\r
+            New-NetFirewallRule -Name $ruleName -DisplayName 'OpenSSH SSH Server (sshd)' `\r
+                -Enabled True -Direction Inbound -Protocol TCP -Action Allow `\r
+                -LocalPort 22 -Profile Any | Out-Null\r
+            Write-Host "    Added firewall rule $ruleName (TCP 22, all profiles)"\r
+        }\r
+    }\r
+} catch {\r
+    Write-Warning "OpenSSH Server setup failed: $($_.Exception.Message)"\r
+}\r
+\r
+# ---------------------------------------------------------------------------\r
+# rsync for Windows (github.com/nuket/rsync-windows)\r
+#\r
+# Windows' OpenSSH ships the transport only - no rsync - so pushing test data\r
+# from a Linux box needs an rsync.exe on the Windows side.\r
+#\r
+# The release is one zip per architecture - rsync-windows-x64.zip and\r
+# rsync-windows-x86.zip - each holding rsync.exe, the ssh.exe it runs, and the\r
+# licence texts under exactly those names. Both exes are installed, together:\r
+# rsync.exe prefers an ssh.exe in its own directory, and the release's build is\r
+# what makes a push FROM this box run at line rate. The ssh.exe Windows ships\r
+# reads its stdin 3KB at a time, which holds a send at ~17MB/s however fast the\r
+# link is. Nothing else about it differs - same ~/.ssh, same ssh-agent, same\r
+# known_hosts - and a bare `ssh` still resolves to the in-box client, which sits\r
+# ahead of C:\Tools\rsync on the machine PATH.\r
+#\r
+# That ssh.exe links against the libcrypto.dll the OpenSSH Client capability\r
+# above puts in System32: Windows' own LibreSSL, and the fast one, since it uses\r
+# AES-NI. No copy of it ships in the zip, so where the capability is missing we\r
+# unpack rsync alone rather than an ssh.exe that will not start.\r
+#\r
+# Installed to C:\Tools\rsync (NOT under "Program Files"): the remote end is\r
+# invoked as `rsync --server ...` through cmd.exe, and a path with spaces makes\r
+# the client-side --rsync-path escape hatch painful to quote. Added to the\r
+# MACHINE PATH so it resolves for every account, including the non-interactive\r
+# sshd session, which builds its environment from the machine + user registry\r
+# PATH rather than from a login shell.\r
+#\r
+# Non-fatal: a download failure only warns.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'rsync for Windows'\r
+$RsyncRepo  = 'nuket/rsync-windows'\r
+$RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' }\r
+# The /releases/latest/download/ redirect rather than the API: unauthenticated\r
+# API calls are rate-limited to 60/hour per IP, which a provisioning run behind a\r
+# shared NAT can genuinely exhaust, and the redirect costs none of that budget.\r
+# To hold a box on a known build, pin the tag instead:\r
+#     .../releases/download/v3.5.0-gABCDEF0/$RsyncAsset\r
+$RsyncUrl   = "https://github.com/$RsyncRepo/releases/latest/download/$RsyncAsset"\r
+$RsyncDir   = 'C:\Tools\rsync'\r
+try {\r
+    New-Item -ItemType Directory -Force -Path $RsyncDir | Out-Null\r
+    $RsyncExe = Join-Path $RsyncDir 'rsync.exe'\r
+\r
+    # Does the release's ssh.exe have the libcrypto it needs? Decided before the\r
+    # download so the answer can also gate what comes out of the zip.\r
+    $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll'\r
+    $WantSsh   = Test-Path $SysCrypto\r
+    if (-not $WantSsh) {\r
+        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
+    } else {\r
+        $v = (Get-Item $SysCrypto).VersionInfo.FileVersion\r
+        if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') {\r
+            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
+        }\r
+    }\r
+\r
+    # Download and unpack beside the targets, not over them, so an interrupted\r
+    # transfer can't leave a truncated rsync.exe sitting on the PATH. The scratch\r
+    # name still has to END in .zip: Windows PowerShell 5.1's Expand-Archive\r
+    # refuses any other extension outright ("*.download is not a supported\r
+    # archive file format"), where PowerShell 7 just reads the file.\r
+    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\r
+    $tmpZip = Join-Path $RsyncDir "download-$RsyncAsset"\r
+    Invoke-WebRequest -Uri $RsyncUrl -OutFile $tmpZip -UseBasicParsing\r
+    Write-Host "    Downloaded $RsyncAsset ($([math]::Round((Get-Item $tmpZip).Length / 1MB, 2)) MB)"\r
+\r
+    # Verify against the .sha256 published beside it. Same origin, so this is an\r
+    # integrity check on the transfer rather than a defence against a hostile\r
+    # release - but a truncated or proxy-mangled download is the failure that\r
+    # actually happens, and it fails here instead of mid-transfer later.\r
+    #\r
+    # -OutFile, not .Content: GitHub serves the .sha256 as\r
+    # application/octet-stream, and Invoke-WebRequest hands back a byte[] rather\r
+    # than a string for any non-text content type, so .Content would compare the\r
+    # first BYTE against the hash and fail on every correct download.\r
+    $tmpSha = "$tmpZip.sha256"\r
+    Invoke-WebRequest -Uri "$RsyncUrl.sha256" -OutFile $tmpSha -UseBasicParsing\r
+    $want = (((Get-Content $tmpSha -Raw) -split '\s+')[0]).Trim().ToLower()\r
+    Remove-Item $tmpSha -Force -ErrorAction SilentlyContinue\r
+    $got  = (Get-FileHash $tmpZip -Algorithm SHA256).Hash.ToLower()\r
+    if ($want -and $want -ne $got) {\r
+        Remove-Item $tmpZip -Force\r
+        throw "SHA-256 mismatch for ${RsyncAsset}: expected $want, got $got"\r
+    }\r
+    Write-Host "    SHA-256 verified: $got"\r
+\r
+    # Unpack to a scratch directory and move out the files we asked for, rather\r
+    # than expanding straight over the install directory: the zip is the unit\r
+    # that was checksummed, and this way a future release adding something to it\r
+    # cannot quietly drop that something onto the machine PATH.\r
+    $unpack = Join-Path $RsyncDir '.unpack'\r
+    if (Test-Path $unpack) { Remove-Item -Recurse -Force $unpack }\r
+    Expand-Archive -Path $tmpZip -DestinationPath $unpack -Force\r
+    Remove-Item $tmpZip -Force\r
+    foreach ($f in 'rsync.exe', 'ssh.exe', 'COPYING.txt', 'NOTICE-ssh.txt') {\r
+        $src = Join-Path $unpack $f\r
+        if (-not (Test-Path $src)) { continue }\r
+        if ($f -eq 'ssh.exe' -and -not $WantSsh) { continue }\r
+        Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force\r
+    }\r
+    Remove-Item -Recurse -Force $unpack\r
+    Write-Host "    Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })"\r
+\r
+    # Machine PATH (HKLM environment). Idempotent: only appends if absent.\r
+    $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
+    if (-not $m) { $m = '' }\r
+    if (($m -split ';') -notcontains $RsyncDir) {\r
+        $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $RsyncDir } else { $RsyncDir }\r
+        [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
+        Write-Host "    Added $RsyncDir to the machine PATH (restart shells / sshd to pick it up)."\r
+        # sshd caches the environment it was started with, so an already-running\r
+        # service would not see the new PATH until restarted.\r
+        if ((Get-Service sshd -ErrorAction SilentlyContinue).Status -eq 'Running') {\r
+            Restart-Service sshd\r
+            Write-Host '    Restarted sshd so it inherits the updated machine PATH.'\r
+        }\r
+    } else {\r
+        Write-Host "    OK: $RsyncDir already in the machine PATH"\r
+    }\r
+\r
+    & $RsyncExe --version | Select-Object -First 1\r
+} catch {\r
+    Write-Warning "rsync install failed: $($_.Exception.Message)"\r
+    Write-Warning "Download $RsyncAsset from https://github.com/$RsyncRepo/releases manually"\r
+    Write-Warning "and unpack it into $RsyncDir, keeping rsync.exe and ssh.exe together."\r
+}\r
+\r
 # ---------------------------------------------------------------------------\r
 # Visual Studio 2022 Community\r
 # ---------------------------------------------------------------------------\r
@@ -228,30 +865,48 @@ if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)
 }\r
 \r
 # ---------------------------------------------------------------------------\r
-# Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling,\r
-# used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature\r
-# that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it.\r
-# The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it\r
-# is the most reliable source. Idempotent (skips if xperf is already present in\r
-# either the SDK or ADK location) and non-fatal so it never aborts provisioning.\r
-# Lighter alternative if you don't want the full ADK: install the Windows SDK's\r
-# "Windows Performance Toolkit" optional feature via winsdksetup.exe /features\r
-# OptionId.WindowsPerformanceToolkit.\r
+# Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer\r
+# (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.\r
+#\r
+# WPA is NOT a Visual Studio component and has no relationship to VS's own\r
+# Performance Profiler (a separate, .diagsession-based tool that cannot open an\r
+# .etl). It ships in exactly two places: as an optional FEATURE of the Windows\r
+# SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and\r
+# in the Windows ADK, which bundles the same toolkit. Whether the SDK install\r
+# that Visual Studio performs happens to select that feature varies with the VS\r
+# and SDK version - when it does, WPT lands in\r
+# %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK\r
+# puts that directory on the machine PATH itself - so this step DETECTS first\r
+# and only falls back to installing the ADK (winget owns the versioned download\r
+# URL, which makes it the reliable source) when nothing is there. That fallback\r
+# is a large download; to install just the toolkit instead, run the standalone\r
+# SDK setup with\r
+#     winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q\r
+#\r
+# There is also a newer WPA in the Microsoft Store (`winget install --id\r
+# 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is\r
+# not installed here: the Store package needs an interactive, signed-in session,\r
+# which is exactly what this elevated, unattended half does not have.\r
+#\r
+# Idempotent and non-fatal - it never aborts provisioning.\r
 # ---------------------------------------------------------------------------\r
-Write-Step 'Windows Performance Toolkit (xperf / WPA)'\r
-$wptRoots = @(\r
-    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
-    (Join-Path $env:ProgramFiles          'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
-    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe')\r
+Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'\r
+$WptDirs = @(\r
+    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),\r
+    (Join-Path $env:ProgramFiles        'Windows Kits\10\Windows Performance Toolkit'),\r
+    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')\r
 )\r
-$xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1\r
-if ($xperf) {\r
-    Write-Host "    OK: WPT already present ($xperf)" -ForegroundColor Green\r
+function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }\r
+\r
+$WptDir = Find-WptDir\r
+if ($WptDir) {\r
+    Write-Host "    OK: WPT already present ($WptDir)" -ForegroundColor Green\r
 } else {\r
     try {\r
         winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r
             --accept-source-agreements --accept-package-agreements\r
         Write-Host '    Windows ADK (includes Windows Performance Toolkit) installed.'\r
+        $WptDir = Find-WptDir\r
     } catch {\r
         Write-Warning "WPT install failed: $($_.Exception.Message)"\r
         Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r
@@ -259,6 +914,78 @@ if ($xperf) {
     }\r
 }\r
 \r
+if ($WptDir) {\r
+    # Report what actually landed. wpa.exe is the piece people come looking for\r
+    # and it is the one that is absent if a trimmed toolkit ever shows up.\r
+    foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {\r
+        $p = Join-Path $WptDir $tool\r
+        if (Test-Path $p) {\r
+            Write-Host "    $tool $((Get-Item $p).VersionInfo.ProductVersion)"\r
+        } else {\r
+            Write-Warning "$tool is missing from $WptDir"\r
+        }\r
+    }\r
+\r
+    # The WPT installer normally adds this to the machine PATH itself (and the\r
+    # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for\r
+    # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user\r
+    # one so it also resolves for the non-interactive sshd sessions this box is\r
+    # driven through, which build their environment from the registry PATH.\r
+    # Compared trailing-backslash-insensitively - the installer's own entry has\r
+    # one, and adding a second spelling of the same directory is just noise.\r
+    $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
+    if (-not $m) { $m = '' }\r
+    $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }\r
+    if ($have) {\r
+        Write-Host "    OK: $WptDir already in the machine PATH"\r
+    } else {\r
+        $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }\r
+        [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
+        Write-Host "    Added $WptDir to the machine PATH (restart shells to pick it up)."\r
+    }\r
+}\r
+\r
+\r
+# ---------------------------------------------------------------------------\r
+# Intel VTune Profiler - reported, not installed\r
+#\r
+# Deliberately NOT automated, unlike everything above. The offline installer is\r
+# a ~750 MB download from a URL carrying a per-release GUID\r
+# (registrationcenter-download.intel.com/akdlm/IRC_NAS/<guid>/intel-vtune-<ver>_offline.exe)\r
+# with no "latest" redirect behind it, so every new build means editing a\r
+# hard-coded link in here - and it is only worth having on Intel silicon, since\r
+# hardware event-based sampling reads Intel PMU counters. Not a good trade for a\r
+# script that has to keep working unattended on any box.\r
+#\r
+# So this step only reports. To install it, take the Windows offline installer\r
+# from\r
+#     https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html\r
+# and run it elevated; it installs unattended with\r
+#     intel-vtune-<version>_offline.exe -a --silent --cli --eula accept\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'Intel VTune Profiler (status only)'\r
+$UninstallKeys = @(\r
+    'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'\r
+    'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'\r
+)\r
+$vtune = Get-ItemProperty $UninstallKeys -ErrorAction SilentlyContinue |\r
+         Where-Object { $_.DisplayName -match 'VTune' } |\r
+         Select-Object -First 1\r
+if ($vtune) {\r
+    Write-Host "    Installed: $($vtune.DisplayName.Trim()) $($vtune.DisplayVersion)" -ForegroundColor Green\r
+    # The oneAPI layout keeps a `latest` junction beside the versioned directory,\r
+    # so this path stays right across upgrades.\r
+    $VTuneCli = Join-Path $vtune.InstallLocation 'vtune\latest\bin64\vtune.exe'\r
+    if (Test-Path $VTuneCli) { Write-Host "    CLI: $VTuneCli" }\r
+} else {\r
+    Write-Host '    Not installed.' -ForegroundColor Yellow\r
+    Write-Host '    https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html' -ForegroundColor Yellow\r
+    $cpu = (Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1).Manufacturer\r
+    if ($cpu -and $cpu -notmatch 'Intel') {\r
+        Write-Host "    (This CPU reports itself as '$cpu' - VTune's hardware event-based sampling wants Intel silicon.)" -ForegroundColor Yellow\r
+    }\r
+}\r
+\r
 # ---------------------------------------------------------------------------\r
 Write-Host "`nAll done." -ForegroundColor Green\r
 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r