X-Git-Url: https://vilimpoc.org/repos/dotfiles/blobdiff_plain/99725a30bdb3eee44c38e1fd9a28c060341aa058..1e91b38f9f50d0f6e706c8f710ad6a77c974799e:/setup-windows-with-uac.ps1?ds=inline diff --git a/setup-windows-with-uac.ps1 b/setup-windows-with-uac.ps1 index ff947c6..34bfa8b 100644 --- a/setup-windows-with-uac.ps1 +++ b/setup-windows-with-uac.ps1 @@ -36,7 +36,14 @@ param( # # Pass an empty string to skip the group membership (the user right is still # granted to the group, so adding an account later is one command). - [string] $TraceUser = '' + [string] $TraceUser = '', + + # Do the ETW rights step and nothing else. That step is seconds of registry + # and LSA work with no downloads, where a full run is dominated by the three + # Visual Studio passes, which take minutes even when they have nothing to do. + # It is why the ETW step runs FIRST: -EtwRightsOnly is then just an early + # exit rather than a set of guards down the rest of the script. + [switch] $EtwRightsOnly ) $ErrorActionPreference = 'Stop' @@ -204,6 +211,71 @@ function Grant-AccountRight([string]$Sid, [string]$Right) { [LsaRights]::Add((Get-SidBytes $Sid), $Right) } +# --------------------------------------------------------------------------- +# ETW provider-GUID access control +# +# ETW keeps a security descriptor per provider GUID under +# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security, and EventAccessControl is +# the documented way to edit one. Editing the registry value directly would work +# too - it is a self-relative SD in a REG_BINARY - but the API takes the SID and +# the rights mask and leaves the descriptor's shape to Windows. +# --------------------------------------------------------------------------- +function Initialize-EtwAclType { + if ('EtwAcl' -as [type]) { return } + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +public static class EtwAcl +{ + // ULONG EventAccessControl(LPGUID, ULONG Operation, PSID, ULONG Rights, BOOLEAN AllowOrDeny) + [DllImport("advapi32.dll", SetLastError = true)] + public static extern uint EventAccessControl(ref Guid guid, uint operation, byte[] sid, + uint rights, [MarshalAs(UnmanagedType.U1)] bool allowOrDeny); + + // ULONG EventAccessQuery(LPGUID, PSECURITY_DESCRIPTOR, PULONG BufferSize) + [DllImport("advapi32.dll", SetLastError = true)] + public static extern uint EventAccessQuery(ref Guid guid, byte[] buffer, ref uint bufferSize); +} +'@ +} + +# The rights a session controller needs, from evntrace.h: +# 0x0001 WMIGUID_QUERY 0x0100 TRACELOG_ACCESS_KERNEL_LOGGER +# 0x0020 TRACELOG_CREATE_REALTIME 0x0200 TRACELOG_LOG_EVENT +# 0x0040 TRACELOG_CREATE_ONDISK 0x0400 TRACELOG_ACCESS_REALTIME +# 0x0080 TRACELOG_GUID_ENABLE 0x0800 TRACELOG_REGISTER_GUIDS +# TRACELOG_ACCESS_KERNEL_LOGGER is the one that names the NT Kernel Logger +# specifically; the rest are what any controller needs to create a session, +# write it to disk and enable providers on it. +# +# READ_CONTROL (0x20000) and SYNCHRONIZE (0x100000) go with them - the SYSTEM and +# Administrators entries on this GUID carry 0x120FFF. Without READ_CONTROL the +# group cannot read the descriptor back, which makes EventAccessQuery useless as +# a check on whether the grant landed: it answers "access denied" either way. +$EtwControllerRights = 0x120FE1 + +function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) { + Initialize-EtwAclType + $g = [Guid]$Guid + # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing + # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which + # on the kernel logger means removing the entries Windows itself relies on. + $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true) + if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) } +} + +function Get-EtwGuidSddl([string]$Guid) { + Initialize-EtwAclType + $g = [Guid]$Guid + $size = [uint32]0 + [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size) + if ($size -eq 0) { return $null } + $buf = New-Object byte[] $size + if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null } + return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access') +} + function Show-VsSetupLogs { # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because # this script runs elevated, that %TEMP% belongs to the elevated user and is @@ -273,6 +345,184 @@ try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {} try { +# --------------------------------------------------------------------------- +# ETW collection rights for an ordinary account +# +# Out of the box, xperf and wpr only work elevated. THREE separate things stand +# in a standard user's way, and each has its own error: +# +# xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)" +# wpr -start GeneralProfile +# -> "Failed to enable the policy to profile system +# performance." (0xc5585011) +# +# 1. Creating or controlling ANY event tracing session - even a user-mode one +# naming a single provider - is checked against the security descriptor ETW +# keeps per provider GUID under +# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor +# grants the session-control rights (TRACELOG_CREATE_ONDISK, +# TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to +# SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log +# Users - and to nobody else. That group is the supported hook; its own +# description says members "may ... enable trace providers, and collect event +# traces". +# +# 2. Switching on the kernel/system trace provider on top of that needs the +# SeSystemProfilePrivilege user right ("Profile system performance"), held by +# default only by Administrators and NT SERVICE\WdiServiceHost. That is the +# one wpr names in its error. +# +# 3. The kernel logger is not covered by that default descriptor. Its own GUID - +# SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries +# an explicit descriptor that does not mention Performance Log Users, so 1 and +# 2 are not enough by themselves. Measured on this box with both in place: a +# user-mode session starts (exit 0) and the account holds the privilege, and +# `xperf -on base` still answers "NT Kernel Logger: Access is denied" while +# wpr's error changes from the policy message above to a bare 0x80070005. +# Even READING that descriptor comes back access-denied, which is the tell. So +# add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER +# is the right that names this particular session. +# +# The privilege and the ACE both go to the GROUP, and the account then goes into +# the group: membership alone becomes the switch, and enabling the next account +# is one `net localgroup` away with no policy or registry edit. +# +# What this costs, stated plainly: a member of that group can capture +# system-wide kernel traces - process, image, file and registry activity across +# every account on the box, paths and command lines included. That is what the +# group is for, and it is the price of collecting a trace without a UAC prompt. +# +# Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU +# sampling nor walking stacks in your own processes, and it is equivalent to +# handing out administrator. +# +# THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership +# are baked into the access token at LOGON, and UAC hands an administrator a +# filtered token that keeps just five harmless privileges - so an admin's +# ordinary shell still cannot trace, however the policy reads. Running as a +# standard user is what makes this work. +# +# For the same reason 1 and 2 do not take effect in an already-open session: the +# account has to sign out and back in. Any NEW logon does it - an ssh login into +# this box is one, which is the quick way to check without dropping the desktop. +# The ACE in 3 is machine state rather than token state, so a logon does nothing +# for it. ETW reads these descriptors into a cache, so a REBOOT is what is +# expected to put the change into effect: with the ACE written and readable in +# the descriptor, xperf -on base was still answering "Access is denied" from a +# fresh shell on the running system. So on a first run, plan on both - a new +# logon for 1 and 2, a reboot for 3. +# +# Analysis never needed any of this: wpa.exe opens an existing .etl as a plain +# user. This step is only about collection. +# --------------------------------------------------------------------------- +Write-Step 'ETW collection rights (non-elevated xperf / wpr)' +$PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users +# SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on +# and wpr both drive. Fixed by contract, from evntrace.h. +$SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939' +try { + # --- The user right, granted to the group --- + $existing = Get-AccountRight $PerfLogUsersSid + if ($existing -contains 'SeSystemProfilePrivilege') { + Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege' + } else { + Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege' + Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users' + } + + # --- The kernel logger's own descriptor --- + # Safe to repeat: a second ACE for the same SID unions to the same access. + # Kept in its own try so that a failure here still leaves the group + # membership below to be done - user-mode sessions work without it. + # + # ETW reads these descriptors out of the registry into a cache, so a REBOOT + # is what puts a change here into effect - not a new logon, which is what the + # group membership and the privilege need. Both, on a first run. + try { + Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights + Write-Host (" Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights) + $sddl = Get-EtwGuidSddl $SystemTraceControlGuid + if ($sddl) { Write-Host " kernel logger DACL is now $sddl" -ForegroundColor DarkGray } + } catch { + Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)" + Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."' + } + + # --- The membership --- + # Fall back to the console user when the caller did not name one: with + # over-the-shoulder elevation that is the person who started + # setup-windows.bat, which is who wants to trace. + $target = $TraceUser + if (-not $target) { + $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName + if ($target) { Write-Host " No -TraceUser given; using the console user $target" } + } + + if (-not $target) { + Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).' + Write-Warning 'The user right is in place, so this is the only step left:' + Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add' + } else { + # Resolve to a SID first: it validates the name, and it is what the + # membership check compares, so a member spelled ".\claude" in one place + # and "LATISLAB\claude" in another is still recognised as the same account. + $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate( + [System.Security.Principal.SecurityIdentifier]) + + # By SID, never by name: "Performance Log Users" is localised, and + # Get-LocalGroup -SID is how this stays correct on a non-English box. + $group = Get-LocalGroup -SID $PerfLogUsersSid + + # Get-LocalGroupMember throws on a group holding a SID that no longer + # resolves (a known Windows 10 bug), so a failure to READ the membership + # must not stop us from writing it - fall through and let the add report. + $already = $false + try { + $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid | + Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0 + } catch { + Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray + } + + if ($already) { + Write-Host " OK: $target is already in $($group.Name)" + } else { + try { + Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value + } catch { + # "already a member" is only reachable when the enumeration above + # failed, and is not an error. Matched on the type NAME rather + # than in a typed catch clause: catch types are resolved when the + # script is PARSED, before the LocalAccounts module has been + # autoloaded, so naming the type there is a parse error that + # would take the whole script down. + if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw } + } + Write-Host " Added $target to $($group.Name)" + } + + Write-Host '' + Write-Host " $target must sign out and back in for the group and the privilege," -ForegroundColor Yellow + Write-Host ' and the box must be REBOOTED for the kernel logger ACE (ETW caches it).' -ForegroundColor Yellow + Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow + Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow + Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow + } +} catch { + Write-Warning "ETW rights setup failed: $($_.Exception.Message)" + Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >' + Write-Warning '"Profile system performance" > add Performance Log Users, then' + Write-Warning ' net localgroup "Performance Log Users" /add' +} + +if ($EtwRightsOnly) { + # `exit` inside the try still runs the finally below, so the transcript is + # stopped and the log is left readable by the non-elevated caller. + Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green + exit 0 +} + + # --------------------------------------------------------------------------- # Base tools via winget # --------------------------------------------------------------------------- @@ -695,129 +945,45 @@ if ($WptDir) { } } + # --------------------------------------------------------------------------- -# ETW collection rights for an ordinary account -# -# Out of the box, xperf and wpr only work elevated, and they fail in two -# different ways for a standard user - because two different things are missing: -# -# xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)" -# wpr -start GeneralProfile -# -> "Failed to enable the policy to profile system -# performance." (0xc5585011) -# -# 1. Creating or controlling ANY event tracing session - even a user-mode one -# naming a single provider - is checked against the security descriptor ETW -# keeps per provider GUID under -# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The default grants the -# session-control rights (TRACELOG_CREATE_ONDISK, TRACELOG_CREATE_REALTIME, -# TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to SYSTEM, Administrators, the -# service accounts, and BUILTIN\Performance Log Users - and to nobody else. -# That group is the supported hook; its own description says members "may -# ... enable trace providers, and collect event traces". -# -# 2. Switching on the kernel/system trace provider on top of that needs the -# SeSystemProfilePrivilege user right ("Profile system performance"), held by -# default only by Administrators and NT SERVICE\WdiServiceHost. That is the -# one wpr names in its error, and the one xperf trips over for -on base. -# -# So grant the privilege to the GROUP and then put the account in the group: -# membership alone becomes the switch, and enabling the next account is one -# `net localgroup` away with no policy edit. -# -# Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU -# sampling nor walking stacks in your own processes, and it is equivalent to -# handing out administrator. -# -# THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership -# are baked into the access token at LOGON, and UAC hands an administrator a -# filtered token that keeps just five harmless privileges - so an admin's -# ordinary shell still cannot trace, however the policy reads. Running as a -# standard user is what makes this work. +# Intel VTune Profiler - reported, not installed # -# For the same reason nothing here takes effect in an already-open session: the -# account has to sign out and back in. Any NEW logon does it - an ssh login into -# this box is one, which is the quick way to check without dropping the desktop. +# Deliberately NOT automated, unlike everything above. The offline installer is +# a ~750 MB download from a URL carrying a per-release GUID +# (registrationcenter-download.intel.com/akdlm/IRC_NAS//intel-vtune-_offline.exe) +# with no "latest" redirect behind it, so every new build means editing a +# hard-coded link in here - and it is only worth having on Intel silicon, since +# hardware event-based sampling reads Intel PMU counters. Not a good trade for a +# script that has to keep working unattended on any box. # -# Analysis never needed any of this: wpa.exe opens an existing .etl as a plain -# user. This step is only about collection. +# So this step only reports. To install it, take the Windows offline installer +# from +# https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html +# and run it elevated; it installs unattended with +# intel-vtune-_offline.exe -a --silent --cli --eula accept # --------------------------------------------------------------------------- -Write-Step 'ETW collection rights (non-elevated xperf / wpr)' -$PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users -try { - # --- The user right, granted to the group --- - $existing = Get-AccountRight $PerfLogUsersSid - if ($existing -contains 'SeSystemProfilePrivilege') { - Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege' - } else { - Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege' - Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users' - } - - # --- The membership --- - # Fall back to the console user when the caller did not name one: with - # over-the-shoulder elevation that is the person who started - # setup-windows.bat, which is who wants to trace. - $target = $TraceUser - if (-not $target) { - $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName - if ($target) { Write-Host " No -TraceUser given; using the console user $target" } - } - - if (-not $target) { - Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).' - Write-Warning 'The user right is in place, so this is the only step left:' - Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add' - } else { - # Resolve to a SID first: it validates the name, and it is what the - # membership check compares, so a member spelled ".\claude" in one place - # and "LATISLAB\claude" in another is still recognised as the same account. - $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate( - [System.Security.Principal.SecurityIdentifier]) - - # By SID, never by name: "Performance Log Users" is localised, and - # Get-LocalGroup -SID is how this stays correct on a non-English box. - $group = Get-LocalGroup -SID $PerfLogUsersSid - - # Get-LocalGroupMember throws on a group holding a SID that no longer - # resolves (a known Windows 10 bug), so a failure to READ the membership - # must not stop us from writing it - fall through and let the add report. - $already = $false - try { - $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid | - Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0 - } catch { - Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray - } - - if ($already) { - Write-Host " OK: $target is already in $($group.Name)" - } else { - try { - Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value - } catch { - # "already a member" is only reachable when the enumeration above - # failed, and is not an error. Matched on the type NAME rather - # than in a typed catch clause: catch types are resolved when the - # script is PARSED, before the LocalAccounts module has been - # autoloaded, so naming the type there is a parse error that - # would take the whole script down. - if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw } - } - Write-Host " Added $target to $($group.Name)" - } - - Write-Host '' - Write-Host " $target must sign out and back in before this takes effect." -ForegroundColor Yellow - Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow - Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow - Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow +Write-Step 'Intel VTune Profiler (status only)' +$UninstallKeys = @( + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' +) +$vtune = Get-ItemProperty $UninstallKeys -ErrorAction SilentlyContinue | + Where-Object { $_.DisplayName -match 'VTune' } | + Select-Object -First 1 +if ($vtune) { + Write-Host " Installed: $($vtune.DisplayName.Trim()) $($vtune.DisplayVersion)" -ForegroundColor Green + # The oneAPI layout keeps a `latest` junction beside the versioned directory, + # so this path stays right across upgrades. + $VTuneCli = Join-Path $vtune.InstallLocation 'vtune\latest\bin64\vtune.exe' + if (Test-Path $VTuneCli) { Write-Host " CLI: $VTuneCli" } +} else { + Write-Host ' Not installed.' -ForegroundColor Yellow + Write-Host ' https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html' -ForegroundColor Yellow + $cpu = (Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1).Manufacturer + if ($cpu -and $cpu -notmatch 'Intel') { + Write-Host " (This CPU reports itself as '$cpu' - VTune's hardware event-based sampling wants Intel silicon.)" -ForegroundColor Yellow } -} catch { - Write-Warning "ETW rights setup failed: $($_.Exception.Message)" - Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >' - Write-Warning '"Profile system performance" > add Performance Log Users, then' - Write-Warning ' net localgroup "Performance Log Users" /add' } # ---------------------------------------------------------------------------