]> vilimpoc.org git repositories - dotfiles/blame - setup-windows-no-uac.ps1
dotfiles: drop the non-elevated ETW tracing, it never worked
[dotfiles] / setup-windows-no-uac.ps1
CommitLineData
2e281421
MV
1<#
2 setup-windows-no-uac.ps1
3 Non-elevated portion of the Windows provisioning. Invoked by setup-windows.bat
4 after its winget installs, or run directly from an ordinary (NOT elevated)
5 prompt:
6
7 powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1
8
9 Run it non-elevated on purpose. Every step here writes per-user state - the
10 HKCU PATH and the global .gitconfig under $env:USERPROFILE - so running it
11 elevated would configure the *administrator's* profile instead of yours.
12
13 What this installs / configures:
14 - WinMerge on the user PATH
7d4887fe
MV
15 - vswhere.exe on the user PATH: the Visual Studio installer puts it in
16 %ProgramFiles(x86)%\Microsoft Visual Studio\Installer, which nothing adds
17 to the PATH, so build scripts (and VsDevCmd.bat itself) complain that
18 'vswhere.exe' is not recognized
2e281421
MV
19 - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim,
20 on the user PATH
2bbc9b41
MV
21 - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH
22 client so git shares the Windows ssh-agent: the fast ssh.exe the elevated
23 half unpacks beside rsync.exe if it is there, the in-box one otherwise
2e281421
MV
24
25 FILL IN $GitUserName / $GitUserEmail below before the first run.
26
27 Steps are independent: one failing warns and the rest still run. The exit code
28 is 1 if any step failed, 0 otherwise.
29#>
30
31[CmdletBinding()]
32param(
33 # Skip individual steps. Note that `powershell -File` cannot pass more than
34 # one value to an array parameter (neither comma- nor space-separated), so
35 # for several, dot-call the script or use -Command:
36 # .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
37 # powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim
7d4887fe 38 [ValidateSet('WinMerge', 'VsWhere', 'BinSkim', 'GitConfig')]
2e281421
MV
39 [string[]] $Skip = @()
40)
41
42$ErrorActionPreference = 'Stop'
43
44# --- Global git identity: FILL THESE IN BEFORE RUNNING ---
45# Left empty, Set-GlobalGitConfig skips the identity and says so, rather than
46# stamping a placeholder onto your commits. Leaving them empty is a legitimate
47# choice - it keeps your identity per-repository. core.sshCommand is set either
48# way, so the ssh side works regardless.
49$GitUserName = '' # e.g. 'Ada Lovelace'
50$GitUserEmail = '' # e.g. 'ada@example.com'
51
52# BinSkim's win-x64 build, from the NuGet flat container.
53$BinSkimPackage = 'microsoft.codeanalysis.binskim'
54$BinSkimDir = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim'
55
2bbc9b41
MV
56# Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only
57# read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in
58# setup-windows-with-uac.ps1 if you move the install.
59$RsyncDir = 'C:\Tools\rsync'
60
2e281421
MV
61function Write-Step([string]$Msg) {
62 Write-Host "`n==> $Msg" -ForegroundColor Cyan
63}
64
65function Add-ToUserPath([string]$Dir) {
66 # HKCU PATH, not the process PATH: this must outlive the script. Idempotent,
67 # and re-applied on every run so an entry lost to an unrelated PATH edit is
68 # repaired without re-doing the install that put it there.
69 $user = [Environment]::GetEnvironmentVariable('Path', 'User')
70 if (-not $user) { $user = '' }
71 if (($user -split ';') -contains $Dir) {
72 Write-Host " $Dir already in user PATH."
73 return
74 }
75 $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir }
76 [Environment]::SetEnvironmentVariable('Path', $new, 'User')
77 Write-Host " Added $Dir to user PATH (restart your shell to pick it up)."
78}
79
80function Add-WinMergeToUserPath {
81 Write-Step 'WinMerge on the user PATH'
82 $candidates = @(
83 (Join-Path $env:ProgramFiles 'WinMerge'),
84 (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'),
85 (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge')
86 )
87 $dir = $candidates |
88 Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } |
89 Select-Object -First 1
90 if (-not $dir) {
91 Write-Warning 'WinMerge not found; user PATH unchanged.'
92 return
93 }
94 Add-ToUserPath $dir
95}
96
7d4887fe
MV
97function Add-VsWhereToUserPath {
98 # vswhere.exe is how scripts locate Visual Studio (MSBuild, VsDevCmd.bat,
99 # the Windows SDK), and the VS installer drops it in a fixed directory that
100 # is never on the PATH. VsDevCmd.bat itself prints "'vswhere.exe' is not
101 # recognized" on every run without it. The directory is fixed by contract
102 # (32-bit Program Files, no version in the path), so there is nothing to
103 # search for: if it is missing, Visual Studio is not installed.
104 Write-Step 'vswhere on the user PATH'
105 $dir = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer'
106 if (-not (Test-Path (Join-Path $dir 'vswhere.exe'))) {
107 Write-Warning "vswhere.exe not found in $dir (no Visual Studio installer present); user PATH unchanged."
108 return
109 }
110 Add-ToUserPath $dir
111}
112
2e281421
MV
113function Install-BinSkim {
114 # BinSkim checks the exact mitigations the native project enables in
115 # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies,
116 # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained win-x64
117 # build, so this needs no .NET SDK/runtime: the .nupkg is a zip - extract the
118 # win-x64 tool folder and put it on the PATH. After restarting the shell:
119 # binskim analyze path\to\your.exe
120 #
121 # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so
122 # ask NuGet what the newest stable version is BEFORE fetching anything, and
123 # skip the download entirely when the installed copy already matches.
124 # Re-provisioning an up-to-date box should not pay for it.
125 #
126 # The installed version is recorded in nupkg-version.txt next to the tool.
127 # For a copy installed before that marker existed, fall back to BinSkim.exe's
128 # own ProductVersion; either way the marker is (re)written once we know the
129 # version, so the fallback runs at most once per install. The
130 # flat-container URL pins the exact version we checked,
131 # unlike the v2 /package/<id> endpoint, which just redirects to whatever is
132 # newest at the moment of the request.
133 Write-Step 'BinSkim'
134 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
135
136 $exe = Join-Path $BinSkimDir 'BinSkim.exe'
137 $marker = Join-Path $BinSkimDir 'nupkg-version.txt'
138
139 $have = $null
140 if (Test-Path $exe) {
141 if (Test-Path $marker) {
142 $have = (Get-Content $marker -Raw).Trim()
143 } else {
144 $pv = (Get-Item $exe).VersionInfo.ProductVersion
145 # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha").
146 if ($pv) { $have = $pv.Split('+')[0].Trim() }
147 }
148 }
149
150 $latest = $null
151 try {
152 $index = Invoke-RestMethod -UseBasicParsing `
153 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json"
154 # Versions come back oldest-first; '-' marks a prerelease.
155 $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1
156 } catch {
157 Write-Warning "BinSkim version check failed: $($_.Exception.Message)"
158 }
159
160 if (-not $latest) {
161 if (-not $have) {
162 Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.'
163 return
164 }
165 Write-Host " BinSkim $have kept (could not reach NuGet to check for a newer one)."
166 } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) {
167 Write-Host " BinSkim $have is already the newest stable release; skipping download."
168 # Records what the ProductVersion fallback just worked out, so the next
169 # run reads the marker instead of re-deriving it.
170 Set-Content -Path $marker -Value $latest -Encoding ascii
171 } else {
172 if ($have) {
173 Write-Host " BinSkim $have -> $latest; downloading."
174 } else {
175 Write-Host " BinSkim $latest; downloading."
176 }
177 $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N'))
178 New-Item -ItemType Directory -Force -Path $tmp | Out-Null
179 try {
180 $zip = Join-Path $tmp 'binskim.zip'
181 Invoke-WebRequest -UseBasicParsing -OutFile $zip `
182 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg"
183 Expand-Archive -Path $zip -DestinationPath $tmp -Force
184
185 $src = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe' |
186 Where-Object { $_.FullName -match 'win-x64' } |
187 Sort-Object FullName | Select-Object -Last 1
188 if (-not $src) { throw 'BinSkim.exe (win-x64) not found in package.' }
189
190 # Replace wholesale rather than merging over the old tree, so files
191 # dropped between releases don't linger.
192 if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir }
193 New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null
194 Copy-Item -Path (Join-Path $src.Directory.FullName '*') `
195 -Destination $BinSkimDir -Recurse -Force
196 # Written last: the marker must only claim a version that fully landed.
197 Set-Content -Path $marker -Value $latest -Encoding ascii
198 Write-Host " BinSkim $latest installed to $BinSkimDir"
199 } finally {
200 Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
201 }
202 }
203
204 Add-ToUserPath $BinSkimDir
205}
206
207function Get-GitPath {
208 # winget installed Git moments ago, but this process inherited its PATH
209 # before that happened, so Get-Command can miss it on a first run. Prefer a
210 # git already on PATH, then the usual install roots.
211 $onPath = Get-Command git.exe -ErrorAction SilentlyContinue
212 if ($onPath) { return $onPath.Source }
213 $roots = @(
214 (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'),
215 (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'),
216 (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe')
217 )
218 return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1
219}
220
221function Set-GlobalGitConfig {
222 Write-Step 'Global git config'
223 $git = Get-GitPath
224 if (-not $git) {
225 Write-Warning 'git.exe not found; skipping global git config.'
226 return
227 }
228 Write-Host " using $git"
229
230 if (-not $GitUserName -or -not $GitUserEmail) {
231 Write-Host ' Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow
232 Write-Host ' Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow
233 Write-Host ' your identity per-repository.' -ForegroundColor Yellow
234 } else {
235 & $git config --global user.name $GitUserName
236 & $git config --global user.email $GitUserEmail
237 Write-Host " identity: $GitUserName <$GitUserEmail>"
238 }
239
2bbc9b41 240 # --- Make git use a Win32-OpenSSH client ---
2e281421
MV
241 # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client
242 # cannot reach the Windows ssh-agent service that the elevated half enables:
243 # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not
244 # speak. So keys added with `ssh-add` from PowerShell stay invisible to git,
245 # and a push falls back to hunting for a key file and prompting for its
2bbc9b41
MV
246 # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git
247 # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as
2e281421 248 # `ssh` from an ordinary shell.
2bbc9b41
MV
249 #
250 # Two of those are on the box, and the one beside rsync.exe is preferred.
251 # It is the same client from the same source, with the same ~/.ssh, agent
252 # and known_hosts, built with a pump on its stdin: the in-box one reads
253 # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however
254 # fast the link is. It only exists once the elevated half has run, so the
255 # in-box client stays the fallback - and on a first provisioning run from
256 # setup-windows.bat it is the elevated half that runs first, so the fast one
257 # is normally already there.
258 $sshCandidates = @(
259 (Join-Path $RsyncDir 'ssh.exe'),
260 (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe')
261 )
262 $winSsh = $null
263 foreach ($cand in $sshCandidates) {
264 if (-not (Test-Path $cand)) { continue }
265 # Run it, rather than just believing the file is there: the build beside
266 # rsync.exe links against the libcrypto.dll the OpenSSH Client capability
267 # puts in System32, and without that capability it is a binary that does
268 # not start. Better to find that out here than on the next `git push`.
269 #
270 # EAP back to Continue for the call: ssh -V writes its version to
271 # STDERR, and with $ErrorActionPreference = 'Stop' a native command's
272 # stderr becomes a terminating RemoteException - so the working client
273 # would look like the broken one.
274 $prevEap = $ErrorActionPreference
275 $ErrorActionPreference = 'Continue'
276 $version = $null
277 # Clear the exit code first, explicitly at global scope. An exe that
278 # cannot start at all - the missing-libcrypto case - throws here without
279 # ever setting one, and the stale 0 from the last native command that DID
280 # run would otherwise read as success. $global: because a bare assignment
281 # would make a local copy that the native call then does not update.
282 $global:LASTEXITCODE = $null
283 try { $version = (& $cand -V 2>&1 | Select-Object -First 1) } catch { }
284 finally { $ErrorActionPreference = $prevEap }
285 if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break }
286 $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
287 Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })"
288 }
289 if (-not $winSsh) {
290 Write-Warning "No working Win32-OpenSSH client found (looked in $($sshCandidates -join ', ')). Add the 'OpenSSH Client' optional feature and re-run; until then git uses its own bundled ssh.exe, which cannot see keys held by the Windows ssh-agent service."
2e281421
MV
291 return
292 }
293 # Forward slashes on purpose: git parses core.sshCommand with shell quoting
294 # rules, in which a backslash is an escape character.
295 $value = $winSsh -replace '\\', '/'
296 & $git config --global core.sshCommand $value
297 Write-Host " core.sshCommand: $value"
2bbc9b41 298 Write-Host " $version"
2e281421
MV
299}
300
301# ---------------------------------------------------------------------------
302# Main
303# ---------------------------------------------------------------------------
304if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
305 [Security.Principal.WindowsBuiltInRole]::Administrator)) {
306 Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.'
307}
308
309$steps = [ordered]@{
310 WinMerge = { Add-WinMergeToUserPath }
7d4887fe 311 VsWhere = { Add-VsWhereToUserPath }
2e281421
MV
312 BinSkim = { Install-BinSkim }
313 GitConfig = { Set-GlobalGitConfig }
314}
315
316$failed = @()
317foreach ($name in $steps.Keys) {
318 if ($Skip -contains $name) {
319 Write-Host "`n==> $name (skipped)" -ForegroundColor DarkGray
320 continue
321 }
322 try {
323 & $steps[$name]
324 } catch {
325 # One broken step must not cost the others. Collect and report at the end.
326 Write-Warning "$name failed: $($_.Exception.Message)"
327 $failed += $name
328 }
329}
330
331if ($failed) {
332 Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red
333 exit 1
334}
335Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green
336exit 0