[repo] Lab capture: lab-install.ps1 (pinned MSI, loopback bind, one elevation) and lab-api.ps1 (pinned TLS, DPAPI credentials)

This commit is contained in:
2026-11-25 13:08:46 +01:00
parent fd1c141ca8
commit 6c68a25b77
3 changed files with 608 additions and 0 deletions
+208
View File
@@ -0,0 +1,208 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "lab-relay"
version = "0.1.0"
dependencies = [
"ring",
"rustls",
"rustls-pki-types",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom",
"libc",
"untrusted",
"windows-sys",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
+183
View File
@@ -0,0 +1,183 @@
<#
.SYNOPSIS
Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated.
.DESCRIPTION
Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the
documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte.
Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line.
-Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway
-Action Status lists paired clients and apps (names only)
-Action Pin submits the PIN Moonlight shows: -PinFile <file with 4 digits> (the file is deleted after
reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight")
-Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets)
-Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2),
restart Sunshine
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')]
[string] $Action,
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $PinFile,
[string] $PairingId,
[string] $ClientName = 'DomiStream lab Moonlight'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$BaseUrl = 'https://127.0.0.2:47990'
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
$throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred'
$labFile = Join-Path $secrets 'sunshine-lab.cred'
$certFile = Join-Path $keys 'sunshine-lab-cert.pem'
function Fail([string] $Why) {
Write-Host "lab-api: STOPPED: $Why"
exit 1
}
# --- TLS pinning: accept exactly the lab certificate -------------------------------------------------------------
if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" }
$pem = Get-Content -LiteralPath $certFile -Raw
$m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')
if (-not $m.Success) { Fail 'lab certificate is not PEM' }
$pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', ''))
if (-not ('DomiLabPin' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class DomiLabPin {
public static byte[] Pinned;
public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) {
if (cert == null || Pinned == null) return false;
byte[] raw = cert.GetRawCertData();
if (raw.Length != Pinned.Length) return false;
int diff = 0;
for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i];
return diff == 0;
}
public static void Install() {
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check);
}
}
'@
}
[DomiLabPin]::Pinned = $pinnedDer
[DomiLabPin]::Install()
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# --- Credentials -------------------------------------------------------------------------------------------------
function Read-Cred([string] $File) {
if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" }
$j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json
$u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString))
$p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString))
return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password }
}
function Save-Cred([string] $File, [string] $User, [string] $Password) {
@{
user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII
}
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
# --- One API call ------------------------------------------------------------------------------------------------
function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) {
$pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password)
$headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) }
$req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 }
if ($null -ne $Body) {
$req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress)
$req.ContentType = 'application/json'
}
try {
if ($OutFile) {
Invoke-WebRequest @req -OutFile $OutFile | Out-Null
return $null
}
return Invoke-RestMethod @req
} catch {
# The message names the call only; the request, which holds the credentials, is never echoed.
Fail "$Method $Path failed: $($_.Exception.GetType().Name)"
}
}
# --- Actions -----------------------------------------------------------------------------------------------------
switch ($Action) {
'Rotate' {
$old = Read-Cred $throwawayFile
$newUser = 'lab' + (New-Secret).Substring(0, 12)
$newPass = New-Secret
$null = Invoke-Sunshine $old 'POST' '/api/password' @{
currentUsername = $old.User
currentPassword = $old.Password
newUsername = $newUser
newPassword = $newPass
confirmNewPassword = $newPass
}
Save-Cred $labFile $newUser $newPass
# Prove the new pair works before forgetting the old one.
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null
Remove-Item -LiteralPath $throwawayFile -Force
Write-Host 'lab-api: credentials rotated; throwaway deleted'
}
'Status' {
$c = Read-Cred $labFile
$clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null
$apps = Invoke-Sunshine $c 'GET' '/api/apps' $null
Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress)))
Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', '))
}
'Pin' {
if (-not $PinFile) { Fail '-PinFile is required' }
$pin = (Get-Content -LiteralPath $PinFile -Raw).Trim()
Remove-Item -LiteralPath $PinFile -Force
if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' }
$body = @{ pin = $pin; name = $ClientName }
if ($PairingId) { $body.pairing_id = $PairingId }
$r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body
Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress))
}
'Logs' {
$out = Join-Path $captures 'sunshine.log'
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out
Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)"
}
'Cleanup' {
$c = Read-Cred $labFile
$null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null
# Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair.
$null = Invoke-Sunshine $c 'POST' '/api/config' @{
bind_address = '127.0.0.2'
address_family = 'ipv4'
origin_web_ui_allowed = 'pc'
upnp = 'disabled'
external_ip = '127.0.0.2'
sunshine_name = 'DomiStream-lab'
lan_encryption_mode = '1'
wan_encryption_mode = '1'
}
$null = Invoke-Sunshine $c 'POST' '/api/restart' $null
Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting'
Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back'
}
}
exit 0
+217
View File
@@ -0,0 +1,217 @@
<#
.SYNOPSIS
Lab capture step (b): install the pinned Sunshine bound to 127.0.0.2 only (docs/LAB_CAPTURE.md section 2).
.DESCRIPTION
Runs ELEVATED, once, started by the operator with:
Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
'<repo>\tools\lab-relay\scripts\lab-install.ps1'
That is the one UAC prompt of the lab capture.
What it does, in order, and nothing else:
1. Refuses unless elevated, unless the MSI's sha256 matches the pin, and unless no Sunshine is installed.
2. Creates keys\, secrets\, captures\ under the lab root, readable only by this account and SYSTEM.
3. msiexec /i (quiet, logged to captures\msiexec.log), then stops the service the MSI started.
4. Writes sunshine.conf: bind_address 127.0.0.2, web UI for this PC only, no UPnP, lab cert/key under keys\.
5. Sets throwaway web-UI credentials with `sunshine --creds` (they exist only in that one process's argv and
in a DPAPI-protected file; lab-api.ps1 -Action Rotate replaces them).
6. Starts the service and checks that every Sunshine listener is on 127.0.0.2. Anything else: stop, fail.
It does not touch Windows Defender, firewall rules (it only lists the ones the MSI added), or any other app.
It never prints, logs or writes a credential in plain text.
#>
[CmdletBinding()]
param(
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $Msi = 'E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# --- Pins (release API, docs/LAB_CAPTURE.md section 2) ------------------------------------------------------------
$PinnedSha256 = '1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf'
$PinnedSize = 33710080
$BindAddress = '127.0.0.2'
$Ports = @(47984, 47989, 47990, 48010)
function Fail([string] $Why) {
Write-Host "lab-install: STOPPED: $Why"
exit 1
}
function Say([string] $What) {
Write-Host "lab-install: $What"
}
# --- 1. Preconditions --------------------------------------------------------------------------------------------
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Fail 'not elevated; start it with Start-Process -Verb RunAs'
}
if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { Fail "MSI not found: $Msi" }
$msiItem = Get-Item -LiteralPath $Msi
if ($msiItem.Length -ne $PinnedSize) { Fail "MSI size $($msiItem.Length) is not the pinned $PinnedSize" }
$hash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash.ToLowerInvariant()
if ($hash -ne $PinnedSha256) { Fail "MSI sha256 $hash does not match the pin; delete the file" }
Say 'MSI matches the pinned sha256'
if (Get-Service -Name '*sunshine*' -ErrorAction SilentlyContinue) { Fail 'a Sunshine service already exists' }
if (Test-Path -LiteralPath 'C:\Program Files\Sunshine\sunshine.exe') { Fail 'C:\Program Files\Sunshine\sunshine.exe already exists' }
$busy = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($busy) { Fail 'a GameStream port is already in use' }
# --- 2. Lab folders, this account + SYSTEM only ------------------------------------------------------------------
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
foreach ($dir in @($keys, $secrets, $captures)) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
& icacls.exe $dir /inheritance:r /grant:r "${account}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "icacls failed on $dir" }
}
$hostKey = Join-Path $keys 'sunshine-lab-key.pem'
$hostCert = Join-Path $keys 'sunshine-lab-cert.pem'
foreach ($f in @($hostKey, $hostCert)) { if (Test-Path -LiteralPath $f) { Fail "$f already exists; clean up first" } }
Say "lab folders ready under $LabRoot"
# --- 3. Install ----------------------------------------------------------------------------------------------------
$msiLog = Join-Path $captures 'msiexec.log'
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', "`"$Msi`"", '/qn', '/norestart', '/l*v', "`"$msiLog`"") -Wait -PassThru
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Fail "msiexec exit code $($p.ExitCode); see $msiLog" }
Say "MSI installed (exit code $($p.ExitCode))"
$service = Get-CimInstance Win32_Service | Where-Object { $_.PathName -like '*Sunshine*' } | Select-Object -First 1
if (-not $service) { Fail 'no Sunshine service after the install' }
Stop-Service -Name $service.Name -Force
Say "service $($service.Name) stopped until the config is in"
$exe = 'C:\Program Files\Sunshine\sunshine.exe'
if (-not (Test-Path -LiteralPath $exe)) { Fail "$exe not found after the install" }
$installDir = Split-Path -Parent $exe
$configDir = Join-Path $installDir 'config'
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
$conf = Join-Path $configDir 'sunshine.conf'
if (Test-Path -LiteralPath $conf) { Copy-Item -LiteralPath $conf -Destination (Join-Path $captures 'sunshine.conf.as-installed') -Force }
# --- 4. Config: loopback only ------------------------------------------------------------------------------------
function Write-Conf([bool] $WithLabKeys) {
$lines = @(
"bind_address = $BindAddress",
'address_family = ipv4',
'origin_web_ui_allowed = pc',
'upnp = disabled',
"external_ip = $BindAddress",
'sunshine_name = DomiStream-lab',
'lan_encryption_mode = 1',
'wan_encryption_mode = 1',
'min_log_level = debug'
)
if ($WithLabKeys) {
# Forward slashes: how the config parser treats backslashes is not documented.
$lines += 'pkey = ' + ($hostKey -replace '\\', '/')
$lines += 'cert = ' + ($hostCert -replace '\\', '/')
}
[IO.File]::WriteAllLines($conf, [string[]] $lines, (New-Object Text.UTF8Encoding($false)))
}
Write-Conf $true
Say 'sunshine.conf written (bind_address 127.0.0.2)'
# --- 5. Throwaway credentials ------------------------------------------------------------------------------------
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
# base64url: only [A-Za-z0-9_-], so it needs no quoting on a command line.
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
$user = 'lab' + (New-Secret).Substring(0, 12)
$pass = New-Secret
# One child process; its argv dies with it. Output is read and discarded, never written anywhere.
$psi = New-Object Diagnostics.ProcessStartInfo
$psi.FileName = $exe
$psi.Arguments = "--creds $user $pass"
$psi.WorkingDirectory = $installDir
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$proc = [Diagnostics.Process]::Start($psi)
$null = $proc.StandardOutput.ReadToEnd()
$null = $proc.StandardError.ReadToEnd()
if (-not $proc.WaitForExit(60000)) { $proc.Kill(); Fail 'sunshine --creds did not finish' }
$credsExit = $proc.ExitCode
$psi = $null
$proc.Dispose()
if ($credsExit -ne 0) { Fail "sunshine --creds exit code $credsExit" }
# DPAPI (this account): readable only by this account on this PC; lab-api.ps1 -Action Rotate replaces it.
$throwaway = Join-Path $secrets 'sunshine-throwaway.cred'
@{
user = (ConvertTo-SecureString -String $user -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $pass -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $throwaway -Encoding ASCII
Remove-Variable -Name user, pass -ErrorAction SilentlyContinue
Say 'throwaway credentials set and stored (DPAPI)'
# --- 6. Start and check the binding ------------------------------------------------------------------------------
function Wait-Listeners([int] $Seconds) {
$deadline = (Get-Date).AddSeconds($Seconds)
while ((Get-Date) -lt $deadline) {
$l = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($l -and (@($l | Select-Object -ExpandProperty LocalPort -Unique).Count -eq $Ports.Count)) { return $l }
Start-Sleep -Milliseconds 500
}
return $null
}
function Assert-Loopback($Listeners) {
$wrong = @($Listeners | Where-Object { $_.LocalAddress -ne $BindAddress })
if ($wrong.Count -gt 0) {
Stop-Service -Name $service.Name -Force
Fail ('Sunshine listened on ' + (($wrong | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', ') + '; service stopped')
}
}
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) {
Stop-Service -Name $service.Name -Force
Fail 'Sunshine did not listen on all four TCP ports; service stopped (bind_address 127.0.0.2 refused? see LAB_CAPTURE.md section 4 fallback)'
}
Assert-Loopback $listeners
# Did Sunshine create its pair at the lab path? If not, fall back to its default pair and copy it for the relay.
$deadline = (Get-Date).AddSeconds(30)
while (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert)) -and (Get-Date) -lt $deadline) {
Start-Sleep -Milliseconds 500
}
if (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert))) {
Say 'Sunshine did not create the lab pair at keys\; using its default pair'
Stop-Service -Name $service.Name -Force
Write-Conf $false
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) { Stop-Service -Name $service.Name -Force; Fail 'Sunshine did not come back after the fallback' }
Assert-Loopback $listeners
$defKey = Join-Path $configDir 'credentials\cakey.pem'
$defCert = Join-Path $configDir 'credentials\cacert.pem'
if (-not ((Test-Path -LiteralPath $defKey) -and (Test-Path -LiteralPath $defCert))) { Fail 'default pair not found either' }
Copy-Item -LiteralPath $defKey -Destination $hostKey
Copy-Item -LiteralPath $defCert -Destination $hostCert
}
Say 'Sunshine listens on 127.0.0.2 only; lab certificate pair in keys\'
# --- Report what the MSI did to the firewall (read only, nothing changed) ----------------------------------------
$rules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Sunshine*' })
$notes = Join-Path $captures 'install-notes.txt'
@(
"installed: $(Get-Date -Format o)",
"service: $($service.Name)",
"msi sha256: $hash",
"listeners: " + (($listeners | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', '),
"firewall rules named like Sunshine (not changed): " + (($rules | ForEach-Object { "$($_.DisplayName) [$($_.Direction) $($_.Action) $($_.Enabled)]" }) -join '; ')
) | Set-Content -LiteralPath $notes -Encoding ASCII
Say "done; notes in $notes. Next, not elevated: lab-api.ps1 -Action Rotate"
exit 0