<# setup-windows-no-uac.ps1 Non-elevated portion of the Windows provisioning. Invoked by setup-windows.bat after its winget installs, or run directly from an ordinary (NOT elevated) prompt: powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1 Run it non-elevated on purpose. Every step here writes per-user state - the HKCU PATH and the global .gitconfig under $env:USERPROFILE - so running it elevated would configure the *administrator's* profile instead of yours. What this installs / configures: - WinMerge on the user PATH - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim, on the user PATH - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH client so git shares the Windows ssh-agent: the fast ssh.exe the elevated half unpacks beside rsync.exe if it is there, the in-box one otherwise FILL IN $GitUserName / $GitUserEmail below before the first run. Steps are independent: one failing warns and the rest still run. The exit code is 1 if any step failed, 0 otherwise. #> [CmdletBinding()] param( # Skip individual steps. Note that `powershell -File` cannot pass more than # one value to an array parameter (neither comma- nor space-separated), so # for several, dot-call the script or use -Command: # .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig # powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim [ValidateSet('WinMerge', 'BinSkim', 'GitConfig')] [string[]] $Skip = @() ) $ErrorActionPreference = 'Stop' # --- Global git identity: FILL THESE IN BEFORE RUNNING --- # Left empty, Set-GlobalGitConfig skips the identity and says so, rather than # stamping a placeholder onto your commits. Leaving them empty is a legitimate # choice - it keeps your identity per-repository. core.sshCommand is set either # way, so the ssh side works regardless. $GitUserName = '' # e.g. 'Ada Lovelace' $GitUserEmail = '' # e.g. 'ada@example.com' # BinSkim's win-x64 build, from the NuGet flat container. $BinSkimPackage = 'microsoft.codeanalysis.binskim' $BinSkimDir = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim' # Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only # read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in # setup-windows-with-uac.ps1 if you move the install. $RsyncDir = 'C:\Tools\rsync' function Write-Step([string]$Msg) { Write-Host "`n==> $Msg" -ForegroundColor Cyan } function Add-ToUserPath([string]$Dir) { # HKCU PATH, not the process PATH: this must outlive the script. Idempotent, # and re-applied on every run so an entry lost to an unrelated PATH edit is # repaired without re-doing the install that put it there. $user = [Environment]::GetEnvironmentVariable('Path', 'User') if (-not $user) { $user = '' } if (($user -split ';') -contains $Dir) { Write-Host " $Dir already in user PATH." return } $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir } [Environment]::SetEnvironmentVariable('Path', $new, 'User') Write-Host " Added $Dir to user PATH (restart your shell to pick it up)." } function Add-WinMergeToUserPath { Write-Step 'WinMerge on the user PATH' $candidates = @( (Join-Path $env:ProgramFiles 'WinMerge'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'), (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge') ) $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } | Select-Object -First 1 if (-not $dir) { Write-Warning 'WinMerge not found; user PATH unchanged.' return } Add-ToUserPath $dir } function Install-BinSkim { # BinSkim checks the exact mitigations the native project enables in # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies, # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained win-x64 # build, so this needs no .NET SDK/runtime: the .nupkg is a zip - extract the # win-x64 tool folder and put it on the PATH. After restarting the shell: # binskim analyze path\to\your.exe # # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so # ask NuGet what the newest stable version is BEFORE fetching anything, and # skip the download entirely when the installed copy already matches. # Re-provisioning an up-to-date box should not pay for it. # # The installed version is recorded in nupkg-version.txt next to the tool. # For a copy installed before that marker existed, fall back to BinSkim.exe's # own ProductVersion; either way the marker is (re)written once we know the # version, so the fallback runs at most once per install. The # flat-container URL pins the exact version we checked, # unlike the v2 /package/ endpoint, which just redirects to whatever is # newest at the moment of the request. Write-Step 'BinSkim' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $exe = Join-Path $BinSkimDir 'BinSkim.exe' $marker = Join-Path $BinSkimDir 'nupkg-version.txt' $have = $null if (Test-Path $exe) { if (Test-Path $marker) { $have = (Get-Content $marker -Raw).Trim() } else { $pv = (Get-Item $exe).VersionInfo.ProductVersion # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha"). if ($pv) { $have = $pv.Split('+')[0].Trim() } } } $latest = $null try { $index = Invoke-RestMethod -UseBasicParsing ` -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json" # Versions come back oldest-first; '-' marks a prerelease. $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1 } catch { Write-Warning "BinSkim version check failed: $($_.Exception.Message)" } if (-not $latest) { if (-not $have) { Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.' return } Write-Host " BinSkim $have kept (could not reach NuGet to check for a newer one)." } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) { Write-Host " BinSkim $have is already the newest stable release; skipping download." # Records what the ProductVersion fallback just worked out, so the next # run reads the marker instead of re-deriving it. Set-Content -Path $marker -Value $latest -Encoding ascii } else { if ($have) { Write-Host " BinSkim $have -> $latest; downloading." } else { Write-Host " BinSkim $latest; downloading." } $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { $zip = Join-Path $tmp 'binskim.zip' Invoke-WebRequest -UseBasicParsing -OutFile $zip ` -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg" Expand-Archive -Path $zip -DestinationPath $tmp -Force $src = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe' | Where-Object { $_.FullName -match 'win-x64' } | Sort-Object FullName | Select-Object -Last 1 if (-not $src) { throw 'BinSkim.exe (win-x64) not found in package.' } # Replace wholesale rather than merging over the old tree, so files # dropped between releases don't linger. if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir } New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null Copy-Item -Path (Join-Path $src.Directory.FullName '*') ` -Destination $BinSkimDir -Recurse -Force # Written last: the marker must only claim a version that fully landed. Set-Content -Path $marker -Value $latest -Encoding ascii Write-Host " BinSkim $latest installed to $BinSkimDir" } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue } } Add-ToUserPath $BinSkimDir } function Get-GitPath { # winget installed Git moments ago, but this process inherited its PATH # before that happened, so Get-Command can miss it on a first run. Prefer a # git already on PATH, then the usual install roots. $onPath = Get-Command git.exe -ErrorAction SilentlyContinue if ($onPath) { return $onPath.Source } $roots = @( (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'), (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'), (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe') ) return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1 } function Set-GlobalGitConfig { Write-Step 'Global git config' $git = Get-GitPath if (-not $git) { Write-Warning 'git.exe not found; skipping global git config.' return } Write-Host " using $git" if (-not $GitUserName -or -not $GitUserEmail) { Write-Host ' Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow Write-Host ' Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow Write-Host ' your identity per-repository.' -ForegroundColor Yellow } else { & $git config --global user.name $GitUserName & $git config --global user.email $GitUserEmail Write-Host " identity: $GitUserName <$GitUserEmail>" } # --- Make git use a Win32-OpenSSH client --- # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client # cannot reach the Windows ssh-agent service that the elevated half enables: # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not # speak. So keys added with `ssh-add` from PowerShell stay invisible to git, # and a push falls back to hunting for a key file and prompting for its # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as # `ssh` from an ordinary shell. # # Two of those are on the box, and the one beside rsync.exe is preferred. # It is the same client from the same source, with the same ~/.ssh, agent # and known_hosts, built with a pump on its stdin: the in-box one reads # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however # fast the link is. It only exists once the elevated half has run, so the # in-box client stays the fallback - and on a first provisioning run from # setup-windows.bat it is the elevated half that runs first, so the fast one # is normally already there. $sshCandidates = @( (Join-Path $RsyncDir 'ssh.exe'), (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe') ) $winSsh = $null foreach ($cand in $sshCandidates) { if (-not (Test-Path $cand)) { continue } # Run it, rather than just believing the file is there: the build beside # rsync.exe links against the libcrypto.dll the OpenSSH Client capability # puts in System32, and without that capability it is a binary that does # not start. Better to find that out here than on the next `git push`. # # EAP back to Continue for the call: ssh -V writes its version to # STDERR, and with $ErrorActionPreference = 'Stop' a native command's # stderr becomes a terminating RemoteException - so the working client # would look like the broken one. $prevEap = $ErrorActionPreference $ErrorActionPreference = 'Continue' $version = $null # Clear the exit code first, explicitly at global scope. An exe that # cannot start at all - the missing-libcrypto case - throws here without # ever setting one, and the stale 0 from the last native command that DID # run would otherwise read as success. $global: because a bare assignment # would make a local copy that the native call then does not update. $global:LASTEXITCODE = $null try { $version = (& $cand -V 2>&1 | Select-Object -First 1) } catch { } finally { $ErrorActionPreference = $prevEap } if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break } $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" } Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })" } if (-not $winSsh) { 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." return } # Forward slashes on purpose: git parses core.sshCommand with shell quoting # rules, in which a backslash is an escape character. $value = $winSsh -replace '\\', '/' & $git config --global core.sshCommand $value Write-Host " core.sshCommand: $value" Write-Host " $version" } # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.' } $steps = [ordered]@{ WinMerge = { Add-WinMergeToUserPath } BinSkim = { Install-BinSkim } GitConfig = { Set-GlobalGitConfig } } $failed = @() foreach ($name in $steps.Keys) { if ($Skip -contains $name) { Write-Host "`n==> $name (skipped)" -ForegroundColor DarkGray continue } try { & $steps[$name] } catch { # One broken step must not cost the others. Collect and report at the end. Write-Warning "$name failed: $($_.Exception.Message)" $failed += $name } } if ($failed) { Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red exit 1 } Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green exit 0