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