Files
ucvl-zonghengjia-open-source/windows/InstallerGuardianGate.cs
T
2026-10-11 23:23:20 +00:00

290 lines
20 KiB
C#

using System.Diagnostics;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Microsoft.Win32.SafeHandles;
namespace UCVL.VPNPlus;
// Opt-in NSIS handoff only. No network/shutdown/restart code belongs here.
// The independent guardian owns recovery, containment and the durable baseline.
internal static class InstallerGuardianGate
{
internal const int Invalid = 70, TimedOut = 71, IdentityMismatch = 72,
EvidenceMismatch = 73, ReleaseRefused = 74, Replay = 75;
internal record Identity(int Pid, long StartTicks, string Path, int SessionId, string UserSid, string Sha256);
internal record Request(int Schema, string Nonce, string TargetDirectory, string BaselineJobDirectory,
DateTimeOffset CreatedAtUtc, DateTimeOffset DeadlineUtc, Identity Guardian, Identity Installer);
internal record Payload(string Path, string Sha256);
internal record Component(int Id, string Sha256);
internal record Ready(int Schema, string Nonce, string RequestSha256, string TargetDirectory,
string BaselineJobDirectory, string PayloadDirectory, string PayloadManifestPath, string PayloadManifestSha256,
string ComponentsDirectory, string ComponentsManifestPath, string ComponentsManifestSha256,
Payload[] Payload, Component[] Components, Identity Installer, Identity Guardian, DateTimeOffset DeadlineUtc);
internal record Release(int Schema, string Nonce, string Permit, string RequestSha256, string ReadySha256,
string BaselineSha256, Identity Installer, Identity Guardian, DateTimeOffset ExpiresAtUtc);
internal record Accepted(string RequestSha256, string ReadySha256, string ReleaseSha256);
internal record PipeApproval(string Nonce, string RequestSha256, string ReadySha256, string ReleaseSha256);
private static readonly string[] ComponentNames = ["Uninstall.exe", "Desktop.lnk", "StartMenu.lnk"];
private static readonly JsonSerializerOptions Json = new() { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow };
private sealed class GateError(int code, string message) : IOException(message) { internal int Code => code; }
private static void Require(bool condition, int code, string message) { if (!condition) throw new GateError(code, message); }
internal static int Run(string target, string control, string nonce, string installerPid, bool apply, Action<Exception>? diagnostic = null)
{
try
{
Require(int.TryParse(installerPid, out var pid) && pid > 0, Invalid, "Invalid installer PID.");
using var scope = new Scope(AppContext.BaseDirectory, target, control, nonce, pid);
if (!apply) return scope.Wait();
// Recheck and pin the exact same staged bytes through the existing
// transaction. No second WriteUninstaller/CreateShortcut occurs.
return scope.Apply(() => InstallationTransaction.Run(target, verifyOnly: false, integrated: true));
}
catch (GateError error) { diagnostic?.Invoke(error); return error.Code; }
catch (Exception error) { diagnostic?.Invoke(error); return Invalid; } // No target error file or client launch on refusal.
}
internal static string Plain(string path)
{
Require(!string.IsNullOrWhiteSpace(path) && Regex.IsMatch(path, @"^[A-Za-z]:\\")
&& !path[2..].Contains(':') && !path.Contains('/') && !path.Contains('"')
&& !path.Any(char.IsControl), Invalid, "A canonical local path is required.");
var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
Require(string.Equals(full, path, StringComparison.Ordinal) && full.Length > 3
&& path[3..].Split('\\').All(p => p.Length > 0 && p is not "." and not ".." && !p.EndsWith('.') && !p.EndsWith(' ')),
Invalid, "Noncanonical gate path.");
InstallationTransaction.NoLinks(full);
return full;
}
private static bool Overlap(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase)
|| a.StartsWith(b + "\\", StringComparison.OrdinalIgnoreCase) || b.StartsWith(a + "\\", StringComparison.OrdinalIgnoreCase);
private static bool Hash(string? value) => value is not null && Regex.IsMatch(value, "^[A-F0-9]{64}$");
private static string Digest(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));
private static T Decode<T>(byte[] bytes) => JsonSerializer.Deserialize<T>(bytes, Json) ?? throw new GateError(Invalid, "Missing record.");
private static bool Same<T>(T a, T b) => JsonSerializer.Serialize(a, Json) == JsonSerializer.Serialize(b, Json);
internal static void WriteNew<T>(string path, T value)
{
Plain(path);
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{ JsonSerializer.Serialize(file, value, Json); file.Flush(true); }
File.Move(temporary, path, overwrite: false);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
internal sealed class Scope : IDisposable
{
private readonly List<IDisposable> held = [];
private readonly string source, target, control, requestHash;
private readonly Request request;
private readonly Process guardian, installer;
private readonly Stopwatch clock = Stopwatch.StartNew();
private readonly TimeSpan remaining;
private readonly FileStream lease;
private string FileAt(string name) => Path.Combine(control, name);
internal Scope(string source, string target, string control, string nonce, int installerPid)
{
// Constructor failures must also release all read locks.
try
{
// NSIS uses a short-name TEMP path. Canonicalize this trusted
// runtime location; caller-selected paths remain strict.
this.source = Plain(Path.GetFullPath(Path.TrimEndingDirectorySeparator(source))); this.target = Plain(target); this.control = Plain(control);
Require(Directory.Exists(control) && Regex.IsMatch(Path.GetFileName(control), "^ucvl-installer-control-[a-f0-9]{32}$"), Invalid, "Unknown control directory.");
Require(Regex.IsMatch(nonce, "^[a-f0-9]{64}$"), Invalid, "Invalid invocation nonce.");
var bytes = ReadPinned(FileAt("request.json")); requestHash = Digest(bytes); request = Decode<Request>(bytes);
Require(request.Schema == 1 && request.Nonce == nonce && request.TargetDirectory == this.target, Invalid, "Invocation does not match request.");
var baseline = Plain(request.BaselineJobDirectory);
var stage = Plain(Path.GetDirectoryName(this.source)!);
var roots = new[] { this.target, this.control, baseline, stage };
for (var i = 0; i < roots.Length; i++) for (var j = i + 1; j < roots.Length; j++)
Require(!Overlap(roots[i], roots[j]), Invalid, "Control, baseline, target and staging must be separate.");
var now = DateTimeOffset.UtcNow;
Require(request.CreatedAtUtc.Offset == TimeSpan.Zero && request.DeadlineUtc.Offset == TimeSpan.Zero
&& request.CreatedAtUtc <= now.AddSeconds(2) && request.DeadlineUtc > request.CreatedAtUtc
&& request.DeadlineUtc - request.CreatedAtUtc <= TimeSpan.FromMinutes(5), Invalid, "Invalid total gate deadline.");
Require(now < request.DeadlineUtc, TimedOut, "Gate deadline expired.");
Require(request.Installer.Pid == installerPid && request.Guardian.Pid != installerPid
&& request.Guardian.Pid != Environment.ProcessId, IdentityMismatch, "Invalid process relationship.");
guardian = PinIdentity(request.Guardian); installer = PinIdentity(request.Installer);
Require(request.DeadlineUtc.UtcTicks <= request.Installer.StartTicks + TimeSpan.FromMinutes(5).Ticks,
Invalid, "Deadline exceeds installer lifetime budget.");
Require(ParentPid(Environment.ProcessId) == installerPid && ParentPid(installerPid) == request.Guardian.Pid,
IdentityMismatch, "Guardian must own this installer and its helper.");
remaining = request.DeadlineUtc - now;
lease = new FileStream(FileAt("gate.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
held.Add(lease);
}
catch { Dispose(); throw; }
}
private byte[] ReadPinned(string path, int maximum = 4 * 1024 * 1024)
{
Plain(path);
var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
held.Add(file);
Require(file.Length is > 0 && file.Length <= maximum, EvidenceMismatch, "Invalid evidence file size.");
using var memory = new MemoryStream(); file.CopyTo(memory); return memory.ToArray();
}
private string PinHash(string path)
{
Plain(path);
var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); held.Add(file);
Require(file.Length > 0, EvidenceMismatch, "Empty staged file.");
return Convert.ToHexString(SHA256.HashData(file));
}
private Process PinIdentity(Identity expected)
{
Require(expected.Pid > 0 && expected.StartTicks > 0 && expected.SessionId >= 0 && Hash(expected.Sha256), IdentityMismatch, "Incomplete process identity.");
Plain(expected.Path);
var process = Process.GetProcessById(expected.Pid); held.Add(process);
using var current = Process.GetCurrentProcess();
using var identity = WindowsIdentity.GetCurrent();
Require(!process.HasExited && process.StartTime.ToUniversalTime().Ticks == expected.StartTicks
&& process.MainModule is not null && Path.GetFullPath(process.MainModule.FileName) == expected.Path && process.SessionId == expected.SessionId
&& expected.SessionId == current.SessionId && expected.UserSid == identity.User?.Value
&& OwnerSid(process) == expected.UserSid, IdentityMismatch, "Process identity or owner changed.");
Require(PinHash(expected.Path) == expected.Sha256, IdentityMismatch, "Process image hash changed.");
return process;
}
private void Alive()
{
Require(!guardian.HasExited && !installer.HasExited, IdentityMismatch, "Guardian or installer exited.");
Require(clock.Elapsed < remaining && DateTimeOffset.UtcNow < request.DeadlineUtc, TimedOut, "Gate deadline expired.");
}
private Ready Stage(bool createManifest)
{
Alive();
var manifestPath = Path.Combine(source, "install-manifest.json");
var bytes = ReadPinned(manifestPath); var rows = Decode<Payload[]>(bytes);
Require(rows.Length is >= 3 and <= 10000 && rows.Select(r => r.Path).Distinct(StringComparer.OrdinalIgnoreCase).Count() == rows.Length
&& new[] { "VPNPlus.exe", "xray/xray.exe", "xray/wintun.dll" }.All(n => rows.Any(r => r.Path == n)), EvidenceMismatch, "Incomplete payload manifest.");
foreach (var row in rows)
Require(Hash(row.Sha256) && PinHash(InstallationTransaction.Resolve(source, row.Path)) == row.Sha256, EvidenceMismatch, "Payload no longer matches its manifest.");
var integration = Plain(Path.Combine(Path.GetDirectoryName(source)!, "integration"));
var components = ComponentNames.Select((name, id) => new Component(id, PinHash(Path.Combine(integration, name)))).ToArray();
var componentsManifest = Path.Combine(integration, "guardian-components.json");
if (createManifest) WriteNew(componentsManifest, components);
var componentBytes = ReadPinned(componentsManifest);
Require(Same(Decode<Component[]>(componentBytes), components), EvidenceMismatch, "Staged component manifest changed.");
return new(1, request.Nonce, requestHash, target, request.BaselineJobDirectory, source, manifestPath, Digest(bytes),
integration, componentsManifest, Digest(componentBytes), rows, components, request.Installer, request.Guardian, request.DeadlineUtc);
}
internal int Wait()
{
Require(!File.Exists(FileAt("ready.json")) && !File.Exists(FileAt("release.json")) && !File.Exists(FileAt("accepted.json"))
&& !File.Exists(FileAt("consumed.json")), Replay, "Control directory has already been used.");
Require(!Directory.Exists(request.BaselineJobDirectory) && !File.Exists(request.BaselineJobDirectory), Invalid, "Baseline job must be new and independent.");
var ready = Stage(createManifest: true); WriteNew(FileAt("ready.json"), ready);
var readyBytes = ReadPinned(FileAt("ready.json")); var readyHash = Digest(readyBytes);
while (!File.Exists(FileAt("release.json"))) { Alive(); Thread.Sleep(100); }
var releaseBytes = ReadPinned(FileAt("release.json")); ValidateRelease(ready, readyHash, releaseBytes);
Alive(); WriteNew(FileAt("accepted.json"), new Accepted(requestHash, readyHash, Digest(releaseBytes)));
return 0;
}
internal int Apply(Func<int> apply)
{
Require(!File.Exists(FileAt("consumed.json")), Replay, "Release is single-use.");
var readyBytes = ReadPinned(FileAt("ready.json")); var ready = Decode<Ready>(readyBytes); var readyHash = Digest(readyBytes);
Require(Same(Stage(createManifest: false), ready), EvidenceMismatch, "A different staged batch reached apply.");
var releaseBytes = ReadPinned(FileAt("release.json")); ValidateRelease(ready, readyHash, releaseBytes);
var accepted = Decode<Accepted>(ReadPinned(FileAt("accepted.json")));
Require(Same(accepted, new Accepted(requestHash, readyHash, Digest(releaseBytes))), ReleaseRefused, "Gate acceptance changed.");
Alive(); WriteNew(FileAt("consumed.json"), accepted);
return apply();
}
private void ValidateRelease(Ready ready, string readyHash, byte[] releaseBytes)
{
Alive(); var release = Decode<Release>(releaseBytes);
Require(release.Schema == 1 && release.Nonce == request.Nonce && release.Permit == "apply-integrated"
&& release.RequestSha256 == requestHash && release.ReadySha256 == readyHash && Hash(release.BaselineSha256)
&& Same(release.Guardian, request.Guardian) && Same(release.Installer, request.Installer)
&& release.ExpiresAtUtc.Offset == TimeSpan.Zero && release.ExpiresAtUtc <= request.DeadlineUtc
&& release.ExpiresAtUtc > DateTimeOffset.UtcNow, ReleaseRefused, "Release does not match this live gate.");
var bytes = ReadPinned(Path.Combine(request.BaselineJobDirectory, "baseline.json"), 16 * 1024 * 1024);
Require(Digest(bytes) == release.BaselineSha256, EvidenceMismatch, "Baseline hash changed.");
using var document = JsonDocument.Parse(bytes); var root = document.RootElement;
Require(root.GetProperty("Schema").GetInt32() == 2 && root.GetProperty("Mode").GetString() == "production-current-user"
&& root.GetProperty("Target").GetString() == target, EvidenceMismatch, "Baseline scope mismatch.");
var payload = root.GetProperty("Candidate").Deserialize<Payload[]>(Json)!;
var components = root.GetProperty("CandidateComponents").Deserialize<Component[]>(Json)!;
var manifests = root.GetProperty("ManifestHashes").Deserialize<string[]>()!;
Require(Same(payload, ready.Payload) && Same(components, ready.Components) && manifests.Length == 3
&& manifests[1] == ready.PayloadManifestSha256 && manifests[2] == ready.ComponentsManifestSha256,
EvidenceMismatch, "Baseline does not bind this payload and all three generated components.");
ProveGuardianRelease(readyHash, Digest(releaseBytes));
}
private void ProveGuardianRelease(string readyHash, string releaseHash)
{
Alive();
var budget = request.DeadlineUtc - DateTimeOffset.UtcNow;
using var deadline = new CancellationTokenSource(budget < TimeSpan.FromSeconds(3) ? budget : TimeSpan.FromSeconds(3));
using var pipe = new NamedPipeClientStream(".", "UCVL.InstallerGuardian." + request.Nonce,
PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification);
try
{
pipe.ConnectAsync(deadline.Token).GetAwaiter().GetResult();
Require(GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverPid) && serverPid == request.Guardian.Pid,
IdentityMismatch, "Release pipe is not owned by the bound guardian.");
using var reader = new StreamReader(pipe);
var line = new System.Text.StringBuilder(); var character = new char[1];
while (true)
{
var count = reader.ReadAsync(character.AsMemory(), deadline.Token).AsTask().GetAwaiter().GetResult();
Require(count == 1 && line.Length < 2048, ReleaseRefused, "Missing or oversized guardian pipe approval.");
if (character[0] == '\n') break;
line.Append(character[0]);
}
var approval = JsonSerializer.Deserialize<PipeApproval>(line.ToString(), Json);
Require(Same(approval, new PipeApproval(request.Nonce, requestHash, readyHash, releaseHash)),
ReleaseRefused, "Guardian did not approve this exact release.");
}
catch (OperationCanceledException) { throw new GateError(TimedOut, "Guardian pipe deadline expired."); }
Alive();
}
public void Dispose() { foreach (var item in held.AsEnumerable().Reverse()) item.Dispose(); held.Clear(); }
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr process, uint access, out SafeAccessTokenHandle token);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out int serverPid);
private static string OwnerSid(Process process)
{
Require(OpenProcessToken(process.Handle, 8, out var token), IdentityMismatch, "Cannot inspect process owner.");
using (token) using (var identity = new WindowsIdentity(token.DangerousGetHandle()))
return identity.User?.Value ?? throw new GateError(IdentityMismatch, "Process owner SID missing.");
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct Entry
{
public uint Size, Usage, Pid; public UIntPtr Heap; public uint Module, Threads, ParentPid;
public int Priority; public uint Flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Exe;
}
[DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Process32First(IntPtr snapshot, ref Entry entry);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool Process32Next(IntPtr snapshot, ref Entry entry);
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
internal static int ParentPid(int pid)
{
var snapshot = CreateToolhelp32Snapshot(2, 0);
Require(snapshot != new IntPtr(-1), IdentityMismatch, "Cannot inspect process lineage.");
try
{
var entry = new Entry { Size = (uint)Marshal.SizeOf<Entry>(), Exe = "" };
if (Process32First(snapshot, ref entry)) do { if (entry.Pid == pid) return checked((int)entry.ParentPid); } while (Process32Next(snapshot, ref entry));
throw new GateError(IdentityMismatch, "Parent process missing.");
}
finally { CloseHandle(snapshot); }
}
}