+# ---------------------------------------------------------------------------\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