Make main the lean product a site receives
main was 16 days and 259 commits behind the line the product is actually built on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It was neither current nor curated - just stale. This brings it forward and, at the same time, makes it mean something: main is what a receiving site installs, and nothing else. WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides, knowledgebase, machines, network, notifications, printers, slides, tools, warranty - plus applications, which is manifest-less core and always ships. The only manifest dependency inside that set is endpoints on computers, and both are in it, so the closure is self-contained. WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb stay on the site line. So do the Windows installer tree, the VM rehearsal helpers, the agent tooling config, one site's data loader, the internal audit and findings records, and the planner spreadsheet. 1,135 tracked files against 1,438. A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped: deploy/site-profile-universal.json still named all seventeen plugins. It is the file docs/DEPLOY.md tells a site to provision from, so a fresh install would have failed at `flask plugin apply-profile` with PluginError - the first thing a receiving site does, broken by the branch meant to serve them. It now names the twelve that exist, and its comment says the two must agree. agent/ was never refreshed. Whoever populated this branch copied shopdb/, plugins/, frontend/ and tests/ from the site line and left the agent tree at its September state: 22 C# and PowerShell sources missing, including AgentCredentials, EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the site line had deleted still present. The old tree is internally consistent, so it compiles, and nothing in CI builds it - every gate was green over a server that speaks enrollment and per-PC credentials to a bundled agent source that cannot. Resynced whole. DECISIONS THIS ENCODES, rather than defers: - The plugin-authoring lab builds printedparts, whose manifest depends on employees, so it could not stay. The lab remains on the site line and main ships no build-along tutorial. That is a real loss for an adopting developer and is recorded here rather than discovered later. - Recognition, Training and Recertification notifications are no longer seeded. Each splits one notification into a card per employee and renders a photo, which needs a plugin this branch does not bundle. Seeding them would offer an author a type that cannot resolve anybody. A site that installs employees gets them from that plugin's own seed. - Windows/IIS is documented as the legacy path throughout, and the README leads with Docker, because that is what a receiving site gets. The API description is regenerated for THIS branch - 347 paths and 483 operations, down from 415 and 573 - so the published contract describes what is here rather than what the site line serves. docs/CONFIG.md lost the two measuring-tool label keys the code no longer declares, which two lanes had decided opposite ways. Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run rather than skip, and every index line count is derived from the file it names.
This commit is contained in:
157
plugins/endpoints/client/Get-ShopDBServerPin.ps1
Normal file
157
plugins/endpoints/client/Get-ShopDBServerPin.ps1
Normal file
@@ -0,0 +1,157 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Print the SPKI SHA-256 pin of a ShopDB server certificate, for building the
|
||||
Set-ShopDBServerPins.ps1 entry.
|
||||
|
||||
.DESCRIPTION
|
||||
The pin is the lowercase hex SHA-256 of the leaf certificate's
|
||||
SubjectPublicKeyInfo: the same value the Server Certificate settings page
|
||||
shows and the endpoint agent compares. It depends only on the key pair, so
|
||||
a certificate renewed with the same key keeps its pin.
|
||||
|
||||
Give it either a URL (the certificate the server actually presents is read
|
||||
from the TLS handshake; it is NOT trusted or validated, only hashed) or a
|
||||
certificate file (.cer, .crt, .pem, DER or PEM). Use the file form to pin a
|
||||
new certificate BEFORE it goes live on the server.
|
||||
|
||||
Reading from a URL trusts the network path at that moment. Compare the
|
||||
printed pin with the one on the Server Certificate settings page before
|
||||
rolling it out.
|
||||
|
||||
.PARAMETER Url
|
||||
https://<server>[:port]. Only the host and port are used.
|
||||
|
||||
.PARAMETER Path
|
||||
A certificate file.
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-ShopDBServerPin.ps1 -Url https://<server>
|
||||
|
||||
.EXAMPLE
|
||||
.\Get-ShopDBServerPin.ps1 -Path .\server.crt
|
||||
#>
|
||||
[CmdletBinding(DefaultParameterSetName = 'Url')]
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Url', Position = 0)]
|
||||
[string]$Url,
|
||||
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Path')]
|
||||
[string]$Path,
|
||||
|
||||
[int]$TimeoutSec = 15
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$source = @'
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
public static class ShopDbServerPinReader
|
||||
{
|
||||
public static byte[] FetchLeafCertificate(string host, int port, int timeoutMilliseconds)
|
||||
{
|
||||
using (TcpClient client = new TcpClient())
|
||||
{
|
||||
IAsyncResult pending = client.BeginConnect(host, port, null, null);
|
||||
if (!pending.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
|
||||
{
|
||||
throw new TimeoutException("Timed out connecting to " + host + ":" + port);
|
||||
}
|
||||
client.EndConnect(pending);
|
||||
client.ReceiveTimeout = timeoutMilliseconds;
|
||||
client.SendTimeout = timeoutMilliseconds;
|
||||
|
||||
byte[] captured = null;
|
||||
RemoteCertificateValidationCallback capture = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||||
{
|
||||
if (certificate != null) { captured = certificate.GetRawCertData(); }
|
||||
return true;
|
||||
};
|
||||
using (SslStream ssl = new SslStream(client.GetStream(), false, capture))
|
||||
{
|
||||
ssl.AuthenticateAsClient(host, null, SslProtocols.Tls12, false);
|
||||
}
|
||||
if (captured == null) { throw new InvalidOperationException("The server presented no certificate"); }
|
||||
return captured;
|
||||
}
|
||||
}
|
||||
|
||||
// Walks the DER: Certificate > TBSCertificate > [0] version (optional),
|
||||
// serialNumber, signature, issuer, validity, subject, subjectPublicKeyInfo.
|
||||
public static string SpkiSha256Hex(byte[] der)
|
||||
{
|
||||
int length;
|
||||
int position = EnterSequence(der, 0, out length);
|
||||
position = EnterSequence(der, position, out length);
|
||||
if (der[position] == 0xA0) { position = Skip(der, position); }
|
||||
for (int field = 0; field < 5; field++) { position = Skip(der, position); }
|
||||
if (der[position] != 0x30) { throw new FormatException("SubjectPublicKeyInfo not found"); }
|
||||
int end = Skip(der, position);
|
||||
using (SHA256 sha = SHA256.Create())
|
||||
{
|
||||
byte[] hash = sha.ComputeHash(der, position, end - position);
|
||||
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
private static int ReadLength(byte[] der, int position, out int length)
|
||||
{
|
||||
int first = der[position];
|
||||
if (first < 0x80) { length = first; return position + 1; }
|
||||
int count = first & 0x7F;
|
||||
if (count == 0 || count > 4) { throw new FormatException("Unsupported DER length"); }
|
||||
length = 0;
|
||||
for (int i = 1; i <= count; i++) { length = (length << 8) | der[position + i]; }
|
||||
return position + 1 + count;
|
||||
}
|
||||
|
||||
private static int EnterSequence(byte[] der, int position, out int length)
|
||||
{
|
||||
if (der[position] != 0x30) { throw new FormatException("Expected SEQUENCE"); }
|
||||
return ReadLength(der, position + 1, out length);
|
||||
}
|
||||
|
||||
private static int Skip(byte[] der, int position)
|
||||
{
|
||||
int length;
|
||||
int content = ReadLength(der, position + 1, out length);
|
||||
return content + length;
|
||||
}
|
||||
}
|
||||
'@
|
||||
|
||||
if (-not ('ShopDbServerPinReader' -as [type])) {
|
||||
Add-Type -TypeDefinition $source
|
||||
}
|
||||
|
||||
try {
|
||||
if ($PSCmdlet.ParameterSetName -eq 'Path') {
|
||||
$resolved = (Resolve-Path -LiteralPath $Path).ProviderPath
|
||||
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $resolved
|
||||
$der = $certificate.RawData
|
||||
$label = "$resolved (subject $($certificate.Subject), expires $($certificate.NotAfter.ToString('yyyy-MM-dd')))"
|
||||
} else {
|
||||
$uri = [Uri]$Url
|
||||
if ($uri.Scheme -ne 'https') { throw "The URL must be https ($Url)" }
|
||||
$der = [ShopDbServerPinReader]::FetchLeafCertificate($uri.Host, $uri.Port, $TimeoutSec * 1000)
|
||||
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList (,$der)
|
||||
$label = "$($uri.Host):$($uri.Port) (subject $($certificate.Subject), expires $($certificate.NotAfter.ToString('yyyy-MM-dd')))"
|
||||
}
|
||||
$pin = [ShopDbServerPinReader]::SpkiSha256Hex($der)
|
||||
} catch {
|
||||
Write-Error "Could not read a certificate: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "Certificate: $label"
|
||||
Write-Host "Pin (SPKI SHA-256):"
|
||||
Write-Output $pin
|
||||
exit 0
|
||||
194
plugins/endpoints/client/Install-ShopDBServerCertificate.ps1
Normal file
194
plugins/endpoints/client/Install-ShopDBServerCertificate.ps1
Normal file
@@ -0,0 +1,194 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Trust the ShopDB server's own certificate on this PC by adding it to
|
||||
LocalMachine\Root, after checking it is the expected certificate and not a
|
||||
certificate authority.
|
||||
|
||||
.DESCRIPTION
|
||||
WHY: endpoint agents older than 1.20 check the normal Windows certificate
|
||||
chain when they download the upgrade package. They know nothing about
|
||||
ServerPins. A server with a self-signed certificate is therefore refused
|
||||
by those agents, and the upgrade to 1.20 never lands. The certificate has
|
||||
to be trusted on the PC BEFORE a store wave queues the upgrade.
|
||||
|
||||
PCs installed by the server's generated installer already trust it. PCs
|
||||
installed from the share do not, and need this entry.
|
||||
|
||||
Adding a non-CA leaf certificate to Root trusts exactly that one server.
|
||||
It cannot be used to vouch for any other site, so the blast radius is the
|
||||
server itself. A CA certificate in Root would trust everything that CA
|
||||
signs, which is why a CA is refused unless -AllowCa is passed.
|
||||
|
||||
Get the .cer from Settings > Endpoints > Server certificate (download), or
|
||||
GET /api/endpoints/settings/server-cert/download. The expected thumbprint
|
||||
is the sha1thumbprint field of GET /api/endpoints/settings/server-cert.
|
||||
|
||||
Meant to run as a GE-Enforce PS1 entry under the SYSTEM task, in the same
|
||||
targeting as the Set-ShopDBServerPins.ps1 entry. Idempotent: the Root store
|
||||
is checked first and nothing is written when the certificate is already
|
||||
there, so it is safe every cycle. Nothing else is removed or changed.
|
||||
|
||||
.PARAMETER CertPath
|
||||
Path to the server certificate file, DER or PEM (.cer / .crt / .pem).
|
||||
|
||||
.PARAMETER Thumbprint
|
||||
Expected SHA-1 thumbprint of the certificate. Spaces, colons and case are
|
||||
ignored. The file is refused when it does not match.
|
||||
|
||||
.PARAMETER AllowCa
|
||||
Import even when the certificate is a CA (basicConstraints CA=true). Only
|
||||
for a site that deliberately trusts its own private CA.
|
||||
|
||||
.PARAMETER LogPath
|
||||
Append a transcript here as well as writing to the pipeline.
|
||||
|
||||
.EXAMPLE
|
||||
.\Install-ShopDBServerCertificate.ps1 -CertPath <share>\shopdb-server.cer -Thumbprint <sha1thumbprint>
|
||||
Trust the server certificate on this PC.
|
||||
|
||||
.EXAMPLE
|
||||
.\Install-ShopDBServerCertificate.ps1 -CertPath .\shopdb-server.cer -Thumbprint <sha1thumbprint> -WhatIf
|
||||
Show what would be imported without touching the store.
|
||||
|
||||
.NOTES
|
||||
Exit codes:
|
||||
0 imported, or already trusted
|
||||
1 bad input, mismatch, refused CA, or an error stopped the import
|
||||
#>
|
||||
[CmdletBinding(SupportsShouldProcess = $true)]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$CertPath,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Thumbprint,
|
||||
[switch]$AllowCa,
|
||||
[string]$LogPath
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Log {
|
||||
param([string]$Message)
|
||||
$line = "{0} [Install-ShopDBServerCertificate] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message
|
||||
Write-Output $line
|
||||
if ($LogPath) {
|
||||
try { Add-Content -LiteralPath $LogPath -Value $line -WhatIf:$false -ErrorAction Stop } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
function Read-Certificate {
|
||||
param([string]$Path)
|
||||
$bytes = [System.IO.File]::ReadAllBytes($Path)
|
||||
$text = [System.Text.Encoding]::ASCII.GetString($bytes)
|
||||
$match = [regex]::Match($text, '-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----',
|
||||
[System.Text.RegularExpressions.RegexOptions]::Singleline)
|
||||
if ($match.Success) {
|
||||
$bytes = [Convert]::FromBase64String(($match.Groups[1].Value -replace '\s', ''))
|
||||
}
|
||||
return New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,[byte[]]$bytes)
|
||||
}
|
||||
|
||||
# --- 1. validate the request ------------------------------------------------
|
||||
|
||||
$expected = ($Thumbprint -replace '[\s:]', '').ToUpperInvariant()
|
||||
if ($expected -notmatch '^[0-9A-F]{40}$') {
|
||||
Log "ERROR '$Thumbprint' is not a SHA-1 thumbprint (40 hex characters); nothing imported"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $CertPath -PathType Leaf)) {
|
||||
Log "ERROR certificate file not found: $CertPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
try {
|
||||
$cert = Read-Certificate -Path $CertPath
|
||||
} catch {
|
||||
Log "ERROR could not read a certificate from $CertPath : $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$actual = $cert.Thumbprint.ToUpperInvariant()
|
||||
Log "file: $CertPath"
|
||||
Log "subject: $($cert.Subject); issuer: $($cert.Issuer); expires: $($cert.NotAfter.ToString('yyyy-MM-dd'))"
|
||||
if ($actual -ne $expected) {
|
||||
Log "ERROR thumbprint of the file is $actual, expected $expected; refusing to import"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if ($cert.HasPrivateKey) {
|
||||
Log 'ERROR the file carries a private key; export the public certificate only'
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- 2. refuse a CA ---------------------------------------------------------
|
||||
|
||||
$isCa = $false
|
||||
foreach ($extension in $cert.Extensions) {
|
||||
if ($extension.Oid.Value -eq '2.5.29.19') {
|
||||
$constraints = [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]$extension
|
||||
$isCa = $constraints.CertificateAuthority
|
||||
}
|
||||
}
|
||||
if ($isCa) {
|
||||
if (-not $AllowCa) {
|
||||
Log ('ERROR the certificate is a CA (basicConstraints CA=true). In Root it would trust every ' +
|
||||
'certificate it signs, not just the ShopDB server. Refusing; pass -AllowCa only if that is intended.')
|
||||
exit 1
|
||||
}
|
||||
Log 'WARN the certificate is a CA and -AllowCa was passed; everything it signs will be trusted'
|
||||
} else {
|
||||
Log 'not a CA (basicConstraints CA absent or false); trusts only this server'
|
||||
}
|
||||
|
||||
if ($cert.Subject -ne $cert.Issuer) {
|
||||
Log 'WARN the certificate is not self-signed; Windows may still need its issuer to build the chain'
|
||||
}
|
||||
if ($cert.NotAfter -lt (Get-Date)) {
|
||||
Log 'WARN the certificate has expired; the server needs a new one, importing anyway'
|
||||
}
|
||||
|
||||
# --- 3. import into LocalMachine\Root ---------------------------------------
|
||||
|
||||
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
|
||||
[System.Security.Cryptography.X509Certificates.StoreName]::Root,
|
||||
[System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
|
||||
try {
|
||||
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
|
||||
try {
|
||||
$present = $store.Certificates.Find(
|
||||
[System.Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $actual, $false)
|
||||
$alreadyTrusted = $present.Count -gt 0
|
||||
} finally { $store.Close() }
|
||||
|
||||
if ($alreadyTrusted) {
|
||||
Log "LocalMachine\Root already holds $actual; nothing to do"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($PSCmdlet.ShouldProcess("Cert:\LocalMachine\Root", "Import $actual ($($cert.Subject))")) {
|
||||
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
|
||||
try { $store.Add($cert) } finally { $store.Close() }
|
||||
|
||||
# Read back rather than trust Add.
|
||||
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
|
||||
try {
|
||||
$after = $store.Certificates.Find(
|
||||
[System.Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint, $actual, $false)
|
||||
} finally { $store.Close() }
|
||||
if ($after.Count -eq 0) {
|
||||
Log "ERROR $actual did not read back from LocalMachine\Root after import"
|
||||
exit 1
|
||||
}
|
||||
Log "imported $actual into LocalMachine\Root"
|
||||
}
|
||||
} catch {
|
||||
Log "ERROR $($_.Exception.Message)"
|
||||
exit 1
|
||||
} finally {
|
||||
$store.Close()
|
||||
}
|
||||
|
||||
exit 0
|
||||
212
plugins/endpoints/client/Set-ShopDBServerPins.ps1
Normal file
212
plugins/endpoints/client/Set-ShopDBServerPins.ps1
Normal file
@@ -0,0 +1,212 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Write the ShopDB server public key pins to HKLM:\SOFTWARE\GE\ShopDB
|
||||
ServerPins, so the endpoint agent and the SYSTEM reporters trust only this
|
||||
site's server key.
|
||||
|
||||
.DESCRIPTION
|
||||
Each pin is the lowercase hex SHA-256 of the server leaf certificate's
|
||||
SubjectPublicKeyInfo. The ShopDB Server Certificate settings page shows the
|
||||
current one, and Get-ShopDBServerPin.ps1 computes one from a URL or a
|
||||
certificate file.
|
||||
|
||||
Written as REG_MULTI_SZ in BOTH registry views (64-bit and WOW6432Node),
|
||||
the same way CollectorKey is, so a 32-bit reader sees the same set.
|
||||
|
||||
Meant to run as a GE-Enforce PS1 entry under the SYSTEM task, before agent
|
||||
1.20 reaches the PC. Idempotent: the set on the PC is compared with the
|
||||
requested set first, and nothing is written when they already match, so it
|
||||
is safe every cycle.
|
||||
|
||||
THE REGISTRY WINS. When ServerPins exists in either view, even empty, the
|
||||
agent uses it alone and ignores serverpins / servercertthumbprint in
|
||||
appsettings.json (the installer and store upgrade write those). Only when
|
||||
the value is absent in both views do the appsettings pins apply.
|
||||
|
||||
ROTATING THE SERVER KEY: pass the old pin AND the new pin until every PC has
|
||||
both, switch the server certificate, then write ONLY the new pin to retire
|
||||
the old one. A PC holding only the old pin refuses the new certificate.
|
||||
|
||||
.PARAMETER Pins
|
||||
One or more pins separated by commas, semicolons or spaces. Colons and case
|
||||
are ignored. Every value must be 64 hex characters or nothing is written.
|
||||
|
||||
.PARAMETER Clear
|
||||
Delete ServerPins from both views. The agent then falls back to the pins
|
||||
in appsettings.json; with none there, normal Windows certificate checks.
|
||||
|
||||
.PARAMETER None
|
||||
Write an EMPTY ServerPins in both views. The registry stays authoritative
|
||||
with no pins, so appsettings.json pins are ignored and the normal Windows
|
||||
certificate checks apply.
|
||||
|
||||
.PARAMETER LogPath
|
||||
Append a transcript here as well as writing to the pipeline.
|
||||
|
||||
.EXAMPLE
|
||||
.\Set-ShopDBServerPins.ps1 -Pins <pin>
|
||||
Pin one server key.
|
||||
|
||||
.EXAMPLE
|
||||
.\Set-ShopDBServerPins.ps1 -Pins "<oldpin>,<newpin>" -WhatIf
|
||||
Show what a key rotation would write without touching the registry.
|
||||
|
||||
.EXAMPLE
|
||||
.\Set-ShopDBServerPins.ps1 -Pins <newpin>
|
||||
After the server switched certificates: retire the old pin.
|
||||
|
||||
.EXAMPLE
|
||||
.\Set-ShopDBServerPins.ps1 -None
|
||||
Turn pinning off on a PC whose appsettings.json still carries pins.
|
||||
|
||||
.NOTES
|
||||
Exit codes:
|
||||
0 written, or already correct
|
||||
1 bad input or an error stopped the write
|
||||
#>
|
||||
[CmdletBinding(SupportsShouldProcess = $true)]
|
||||
param(
|
||||
[string]$Pins,
|
||||
[switch]$Clear,
|
||||
[switch]$None,
|
||||
[string]$LogPath
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$SubKey = 'SOFTWARE\GE\ShopDB'
|
||||
$ValueName = 'ServerPins'
|
||||
|
||||
function Log {
|
||||
param([string]$Message)
|
||||
$line = "{0} [Set-ShopDBServerPins] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message
|
||||
Write-Output $line
|
||||
if ($LogPath) {
|
||||
try { Add-Content -LiteralPath $LogPath -Value $line -ErrorAction Stop } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
# Returns @{ Present; Pins }. Present = the value exists, even empty.
|
||||
function Get-CurrentPins {
|
||||
param([Microsoft.Win32.RegistryView]$View)
|
||||
$result = @{ Present = $false; Pins = @() }
|
||||
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $View)
|
||||
try {
|
||||
$key = $base.OpenSubKey($SubKey)
|
||||
if (-not $key) { return $result }
|
||||
try {
|
||||
$value = $key.GetValue($ValueName)
|
||||
if ($null -eq $value) { return $result }
|
||||
$result.Present = $true
|
||||
$result.Pins = @(@($value) | ForEach-Object { ([string]$_).Trim().ToLowerInvariant() } | Where-Object { $_ })
|
||||
return $result
|
||||
} finally { $key.Dispose() }
|
||||
} finally { $base.Dispose() }
|
||||
}
|
||||
|
||||
function Test-SamePins {
|
||||
param([string[]]$Left, [string[]]$Right)
|
||||
$a = @($Left | Sort-Object -Unique)
|
||||
$b = @($Right | Sort-Object -Unique)
|
||||
if ($a.Count -ne $b.Count) { return $false }
|
||||
for ($i = 0; $i -lt $a.Count; $i++) {
|
||||
if ($a[$i] -ne $b[$i]) { return $false }
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
# --- 1. validate the request ------------------------------------------------
|
||||
|
||||
$requested = @()
|
||||
if (@(@($Clear.IsPresent, $None.IsPresent, [bool]$Pins) | Where-Object { $_ }).Count -gt 1) {
|
||||
Log 'ERROR use only one of -Pins, -Clear, -None'
|
||||
exit 1
|
||||
}
|
||||
if ($None) {
|
||||
Log 'requested an empty ServerPins (registry authoritative, no pins)'
|
||||
} elseif (-not $Clear) {
|
||||
if (-not $Pins -or -not $Pins.Trim()) {
|
||||
Log 'ERROR no -Pins given (-Clear deletes the value, -None writes it empty)'
|
||||
exit 1
|
||||
}
|
||||
foreach ($raw in ($Pins -split '[,;\s]+')) {
|
||||
if (-not $raw) { continue }
|
||||
$pin = ($raw -replace ':', '').ToLowerInvariant()
|
||||
if ($pin -notmatch '^[0-9a-f]{64}$') {
|
||||
Log "ERROR '$raw' is not a SHA-256 pin (64 hex characters); nothing written"
|
||||
exit 1
|
||||
}
|
||||
if ($requested -notcontains $pin) { $requested += $pin }
|
||||
}
|
||||
if ($requested.Count -eq 0) {
|
||||
Log 'ERROR -Pins held no values; nothing written'
|
||||
exit 1
|
||||
}
|
||||
Log "requested $($requested.Count) pin(s): $($requested -join ', ')"
|
||||
}
|
||||
|
||||
# --- 2. write each view -----------------------------------------------------
|
||||
|
||||
$views = @(
|
||||
@{ Name = '64-bit'; View = [Microsoft.Win32.RegistryView]::Registry64 },
|
||||
@{ Name = '32-bit'; View = [Microsoft.Win32.RegistryView]::Registry32 }
|
||||
)
|
||||
|
||||
$failed = $false
|
||||
foreach ($entry in $views) {
|
||||
try {
|
||||
$state = Get-CurrentPins -View $entry.View
|
||||
$current = @($state.Pins)
|
||||
|
||||
if ($Clear) {
|
||||
if (-not $state.Present) {
|
||||
Log "$($entry.Name): no ServerPins; nothing to do"
|
||||
continue
|
||||
}
|
||||
if ($PSCmdlet.ShouldProcess("HKLM\$SubKey ($($entry.Name))", "Remove $ValueName")) {
|
||||
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $entry.View)
|
||||
try {
|
||||
$key = $base.OpenSubKey($SubKey, $true)
|
||||
if ($key) {
|
||||
try { $key.DeleteValue($ValueName, $false) } finally { $key.Dispose() }
|
||||
}
|
||||
} finally { $base.Dispose() }
|
||||
Log "$($entry.Name): deleted ServerPins (appsettings.json pins apply)"
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if ($state.Present -and (Test-SamePins -Left $current -Right $requested)) {
|
||||
Log "$($entry.Name): ServerPins already correct; nothing to do"
|
||||
continue
|
||||
}
|
||||
|
||||
$action = "Set $ValueName to $($requested.Count) pin(s) (was $($current.Count))"
|
||||
if ($PSCmdlet.ShouldProcess("HKLM\$SubKey ($($entry.Name))", $action)) {
|
||||
$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $entry.View)
|
||||
try {
|
||||
$key = $base.CreateSubKey($SubKey)
|
||||
try {
|
||||
$key.SetValue($ValueName, [string[]]$requested, [Microsoft.Win32.RegistryValueKind]::MultiString)
|
||||
} finally { $key.Dispose() }
|
||||
} finally { $base.Dispose() }
|
||||
|
||||
# Read back rather than trust SetValue.
|
||||
$after = Get-CurrentPins -View $entry.View
|
||||
if (-not $after.Present -or -not (Test-SamePins -Left @($after.Pins) -Right $requested)) {
|
||||
Log "ERROR $($entry.Name): ServerPins did not read back as written"
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
Log "$($entry.Name): wrote ServerPins ($($requested.Count) pin(s), was $($current.Count))"
|
||||
}
|
||||
} catch {
|
||||
Log "ERROR $($entry.Name): $($_.Exception.Message)"
|
||||
$failed = $true
|
||||
}
|
||||
}
|
||||
|
||||
if ($failed) { exit 1 }
|
||||
exit 0
|
||||
Reference in New Issue
Block a user