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