Files
ucvl-zonghengjia-open-source/windows/build/GuardianGateFixture.cs
T

273 lines
19 KiB
C#
Raw Normal View History

// This isolated test executable links the real gate, but replaces the installer
// transaction with a TEMP-only sentinel. It never loads the client or registry.
using System.Diagnostics;
using System.IO.Pipes;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class InstallationTransaction
{
internal static void NoLinks(string path)
{
for (var part = path; !string.IsNullOrEmpty(part); part = Path.GetDirectoryName(part))
if ((File.Exists(part) || Directory.Exists(part)) && File.GetAttributes(part).HasFlag(FileAttributes.ReparsePoint))
throw new IOException("Fixture link refused.");
}
internal static string Resolve(string root, string relative)
{
if (relative.Contains(':') || relative.Contains('\\') || Path.IsPathRooted(relative)
|| relative.Split('/').Any(p => p is "" or "." or "..")) throw new IOException("Fixture traversal refused.");
return Path.Combine(root, relative.Replace('/', '\\'));
}
internal static int Run(string target, bool verifyOnly, bool integrated)
{
var parent = Path.GetDirectoryName(target)!;
if (Path.GetFileName(target) != "installed" || !Path.GetFileName(parent).StartsWith("ucvl-guardian-fixture-", StringComparison.Ordinal)
|| Path.GetDirectoryName(parent) != Path.TrimEndingDirectorySeparator(Path.GetTempPath())) return 99;
File.WriteAllText(Path.Combine(target, "apply-reached.fixture"), "ONLY A SYNTHETIC SENTINEL; NO INSTALLATION");
return int.Parse(File.ReadAllText(Path.Combine(parent, "fixture-exit.txt")));
}
}
internal static class GuardianGateFixture
{
private static readonly List<string> Checks = [];
private static string Hash(string path) { using var f = File.OpenRead(path); return Convert.ToHexString(SHA256.HashData(f)); }
private static void Check(string name, bool value) { if (!value) throw new Exception("FAIL " + name); Checks.Add(name); Console.WriteLine("PASS " + name); }
private static InstallerGuardianGate.Identity Identity(Process p)
{
// Process.Start may return before the image is visible to MainModule.
// Stay bound to this exact handle; never find a replacement by name.
var watch = Stopwatch.StartNew();
while (true)
{
p.Refresh();
if (p.HasExited) throw new IOException("Fixture process exited before identity was available: " + p.ExitCode);
var module = p.MainModule;
if (module is not null)
{
var path = Path.GetFullPath(module.FileName);
return new(p.Id, p.StartTime.ToUniversalTime().Ticks, path, p.SessionId,
WindowsIdentity.GetCurrent().User!.Value, Hash(path));
}
if (watch.Elapsed.TotalSeconds >= 2) throw new TimeoutException("Fixture process identity did not become available.");
Thread.Sleep(10);
}
}
private static Process Start(string exe, params string[] args)
{
var info = new ProcessStartInfo(exe) { UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden };
foreach (var arg in args) info.ArgumentList.Add(arg);
return Process.Start(info)!;
}
private static void Save(string path, object value) => InstallerGuardianGate.WriteNew(path, value);
private static async Task WaitFile(string path, Process process)
{
var timer = Stopwatch.StartNew();
while (!File.Exists(path))
{
if (process.HasExited) throw new Exception("NSIS exited before ready: " + process.ExitCode);
if (timer.Elapsed > TimeSpan.FromSeconds(12)) throw new TimeoutException("Fixture ready timeout.");
await Task.Delay(25);
}
}
private static async Task Serve(string nonce, InstallerGuardianGate.PipeApproval approval, int count, CancellationToken token)
{
if (count == 2)
{
// Exercise the exact independent production coordinator's pipe,
// including both successive NSIS helper connections and server PID.
using var pipe = new UCVL.Maintenance.GuardianApprovalPipe(nonce, JsonSerializer.Serialize(approval), 30000);
while (!pipe.Completed) { token.ThrowIfCancellationRequested(); await Task.Delay(25, token); }
pipe.Verify(); return;
}
for (var i = 0; i < count; i++)
{
using var server = new NamedPipeServerStream("UCVL.InstallerGuardian." + nonce,
PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await server.WaitForConnectionAsync(token);
using var writer = new StreamWriter(server, new UTF8Encoding(false)) { AutoFlush = true };
await writer.WriteLineAsync(JsonSerializer.Serialize(approval).AsMemory(), token);
await Task.Delay(75, token);
}
}
private static async Task Case(string setup, string name, int expected, bool released = false, int transactionExit = 0)
{
var root = Path.Combine(Path.GetTempPath(), "ucvl-guardian-fixture-" + Guid.NewGuid().ToString("N"));
var target = Path.Combine(root, "installed"); Directory.CreateDirectory(target);
File.WriteAllText(Path.Combine(target, "old.fixture"), "unchanged original fixture");
// An executable already exists at the install target, exercising the
// production shutdown/failure-restart branches' controlled-mode guards.
foreach (var file in new[] { "VPNPlus.exe", "VPNPlus.dll", "VPNPlus.deps.json", "VPNPlus.runtimeconfig.json" })
File.Copy(Path.Combine(AppContext.BaseDirectory, file), Path.Combine(target, file));
var originalHashes = Directory.GetFiles(target).ToDictionary(p => p, Hash);
File.WriteAllText(Path.Combine(root, "fixture-exit.txt"), transactionExit.ToString());
var control = Path.Combine(root, "ucvl-installer-control-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(control);
var baseline = Path.Combine(root, "baseline-job");
var nonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
using var installer = Start(setup, "/S", "/UPDATE", "/GUARDIAN=" + control, "/GUARDIANNONCE=" + nonce, "/D=" + target);
using var guardian = Process.GetCurrentProcess();
var now = DateTimeOffset.UtcNow;
var guardianIdentity = Identity(guardian);
var installerIdentity = Identity(installer);
var installerStart = new DateTimeOffset(installerIdentity.StartTicks, TimeSpan.Zero);
var fixedFiveMinuteSuccess = name == "fixed-start-five-minute-success";
var request = new InstallerGuardianGate.Request(1, nonce, target, baseline, installerStart,
installerStart.AddSeconds(name == "timeout" ? 2 : fixedFiveMinuteSuccess ? 300 : 25), guardianIdentity, installerIdentity);
if (name == "bad-identity") request = request with { Guardian = request.Guardian with { StartTicks = 1 } };
if (name == "bad-hash") request = request with { Guardian = request.Guardian with { Sha256 = new string('A', 64) } };
if (name == "bad-session") request = request with { Guardian = request.Guardian with { SessionId = request.Guardian.SessionId + 1 } };
if (name == "bad-owner") request = request with { Guardian = request.Guardian with { UserSid = "S-1-5-18" } };
if (name == "bad-nonce") request = request with { Nonce = new string('0', 64) };
if (name == "overlap") request = request with { BaselineJobDirectory = control };
if (name == "long-deadline") request = request with { DeadlineUtc = installerStart.AddSeconds(301) };
if (name == "installer-lifetime-bound") request = request with { CreatedAtUtc = now, DeadlineUtc = now.AddSeconds(300) };
if (name == "expired-deadline") request = request with { DeadlineUtc = installerStart.AddTicks(1) };
if (name != "missing-request") Save(Path.Combine(control, "request.json"), request);
if (name == "preexisting-release") Save(Path.Combine(control, "release.json"), new { invalid = true });
Task? pipe = null; Process? foreignServer = null; using var pipeDeadline = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
if (released)
{
await WaitFile(Path.Combine(control, "ready.json"), installer);
var ready = JsonSerializer.Deserialize<InstallerGuardianGate.Ready>(File.ReadAllText(Path.Combine(control, "ready.json")))!;
if (fixedFiveMinuteSuccess)
{
Check(name + "_created_from_real_installer_start", request.CreatedAtUtc.UtcTicks == installer.StartTime.ToUniversalTime().Ticks);
Check(name + "_deadline_exactly_start_plus_300", ready.DeadlineUtc == installerStart.AddSeconds(300));
await Task.Delay(150);
var delayedReady = JsonSerializer.Deserialize<InstallerGuardianGate.Ready>(File.ReadAllText(Path.Combine(control, "ready.json")))!;
Check(name + "_readiness_delay_does_not_refresh_deadline", delayedReady.DeadlineUtc == ready.DeadlineUtc);
}
Check(name + "_same_nsis_staging", Path.GetDirectoryName(ready.PayloadDirectory) == Path.GetDirectoryName(ready.ComponentsDirectory));
Check(name + "_target_untouched_before_release", Directory.GetFiles(target).Length == 5
&& originalHashes.All(p => File.Exists(p.Key) && Hash(p.Key) == p.Value));
Check(name + "_three_components_pinned", ready.Components.Length == 3 && ready.Components.All(c =>
Hash(Path.Combine(ready.ComponentsDirectory, new[] { "Uninstall.exe", "Desktop.lnk", "StartMenu.lnk" }[c.Id])) == c.Sha256));
var blocked = false;
try { using var write = File.Open(Path.Combine(ready.ComponentsDirectory, "Desktop.lnk"), FileMode.Open, FileAccess.Write, FileShare.ReadWrite); }
catch (IOException) { blocked = true; }
Check(name + "_staged_bytes_locked_during_wait", blocked);
Directory.CreateDirectory(baseline);
var components = ready.Components;
if (name == "wrong-baseline") components = components.Select(c => c.Id == 1 ? c with { Sha256 = new string('B', 64) } : c).ToArray();
Save(Path.Combine(baseline, "baseline.json"), new { Schema = 2, Mode = "production-current-user", Target = target,
Candidate = ready.Payload, CandidateComponents = components,
ManifestHashes = new[] { new string('C', 64), ready.PayloadManifestSha256, ready.ComponentsManifestSha256 } });
var release = new InstallerGuardianGate.Release(1, name == "wrong-release" ? new string('1', 64) : nonce,
"apply-integrated", Hash(Path.Combine(control, "request.json")), Hash(Path.Combine(control, "ready.json")),
Hash(Path.Combine(baseline, "baseline.json")), request.Installer, request.Guardian, request.DeadlineUtc);
if (name == "release-deadline-refresh") release = release with { ExpiresAtUtc = installerStart.AddSeconds(300) };
var releasePath = Path.Combine(control, "release.json");
var tmp = Path.Combine(control, "release.new"); Save(tmp, release);
var approval = new InstallerGuardianGate.PipeApproval(nonce, release.RequestSha256, release.ReadySha256, Hash(tmp));
if (name == "wrong-pipe-owner")
{
var approvalFile = Path.Combine(control, "fixture-pipe-approval.json"); Save(approvalFile, approval);
foreignServer = Start(Environment.ProcessPath!, "--serve-wrong-pipe", nonce, approvalFile);
}
else if (name != "missing-pipe") pipe = Serve(nonce, approval, name is "success" or "apply-failure" or "fixed-start-five-minute-success" ? 2 : 1, pipeDeadline.Token);
File.Move(tmp, releasePath);
}
using var wait = new CancellationTokenSource(TimeSpan.FromSeconds(32)); await installer.WaitForExitAsync(wait.Token);
await Task.Delay(150); // Make any accidental asynchronous Exec observable.
if(installer.ExitCode != expected && File.Exists(Path.Combine(control, "fixture-diagnostic.txt")))
Console.Error.WriteLine(File.ReadAllText(Path.Combine(control, "fixture-diagnostic.txt")));
Check(name + "_exact_exit_" + expected + "_actual_" + installer.ExitCode, installer.ExitCode == expected);
var applied = File.Exists(Path.Combine(target, "apply-reached.fixture"));
Check(name + "_apply_authorization", applied == (name is "success" or "apply-failure" or "fixed-start-five-minute-success"));
Check(name + "_original_fixture_preserved", originalHashes.All(p => File.Exists(p.Key) && Hash(p.Key) == p.Value));
if (applied) Check(name + "_single_use_consumed", File.Exists(Path.Combine(control, "consumed.json")));
// Refusals must not create .ucvl-installer/last-error or retry clients.
Check(name + "_no_client_shutdown_or_start", !File.Exists(Path.Combine(target, "unexpected-start.fixture"))
&& !File.Exists(Path.Combine(target, "unexpected-shutdown.fixture")));
Check(name + "_only_expected_target_files", Directory.GetFiles(target, "*", SearchOption.AllDirectories).Length == (applied ? 6 : 5));
}
finally
{
pipeDeadline.Cancel();
if (pipe is not null) try { await pipe; } catch (OperationCanceledException) { }
if (foreignServer is not null)
{
if (!foreignServer.WaitForExit(2000)) foreignServer.Kill(entireProcessTree: true);
foreignServer.Dispose();
}
if (!installer.HasExited) { installer.Kill(entireProcessTree: true); await installer.WaitForExitAsync(); }
}
}
private static async Task<int> Tests(string project)
{
var job = Path.Combine(Path.GetTempPath(), "ucvl-guardian-tests-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(job);
var payload = Path.Combine(job, "fixture-payload"); Directory.CreateDirectory(payload);
foreach (var name in new[] { "VPNPlus.exe", "VPNPlus.dll", "VPNPlus.deps.json", "VPNPlus.runtimeconfig.json" })
File.Copy(Path.Combine(AppContext.BaseDirectory, name), Path.Combine(payload, name));
Directory.CreateDirectory(Path.Combine(payload, "xray"));
File.WriteAllText(Path.Combine(payload, "xray", "xray.exe"), "NOT EXECUTABLE; synthetic fixture");
File.WriteAllText(Path.Combine(payload, "xray", "wintun.dll"), "NOT A DRIVER; synthetic fixture");
Save(Path.Combine(payload, "install-manifest.json"), new[] { "VPNPlus.exe", "xray/xray.exe", "xray/wintun.dll" }
.Select(p => new InstallerGuardianGate.Payload(p, Hash(Path.Combine(payload, p)))).ToArray());
var setup = Path.Combine(job, "guardian-production-nsis-fixture.exe");
using (var compile = Start(Path.Combine(project, ".tools", "nsis", "nsis-3.12", "makensis.exe"), "/V2",
"/DAPP_SOURCE_DIR=" + payload, "/DINSTALLER_OUTPUT=" + setup, "/INPUTCHARSET", "UTF8", Path.Combine(project, "installer", "VPNPlus.nsi")))
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(45)); await compile.WaitForExitAsync(timeout.Token);
Check("production_nsis_compiles_with_real_guardian_entry", compile.ExitCode == 0 && File.Exists(setup));
}
await Case(setup, "missing-request", 70);
await Case(setup, "bad-nonce", 70);
await Case(setup, "overlap", 70);
await Case(setup, "long-deadline", 70);
await Case(setup, "installer-lifetime-bound", 70);
await Case(setup, "expired-deadline", 71);
await Case(setup, "bad-identity", 72);
await Case(setup, "bad-hash", 72);
await Case(setup, "bad-session", 72);
await Case(setup, "bad-owner", 72);
await Case(setup, "preexisting-release", 75);
await Case(setup, "timeout", 71);
await Case(setup, "wrong-release", 74, released: true);
await Case(setup, "release-deadline-refresh", 74, released: true);
await Case(setup, "wrong-baseline", 73, released: true);
await Case(setup, "missing-pipe", 71, released: true);
await Case(setup, "wrong-pipe-owner", 72, released: true);
await Case(setup, "apply-failure", 83, released: true, transactionExit: 83);
await Case(setup, "success", 0, released: true);
await Case(setup, "fixed-start-five-minute-success", 0, released: true);
Save(Path.Combine(job, "results.json"), new { Kind = "real-nsis-guardian-gate-fixture", Passed = true, Count = Checks.Count,
ProductionInstalled = false, NetworkSampled = false, ProductionRegistryModified = false, GuardianRecoveryAccepted = false,
Checks, InstallerSha256 = Hash(setup), GateSourceSha256 = Hash(Path.Combine(project, "InstallerGuardianGate.cs")),
NsisSourceSha256 = Hash(Path.Combine(project, "installer", "VPNPlus.nsi")), FixtureJob = job });
Console.WriteLine("RESULT " + Path.Combine(job, "results.json")); return 0;
}
private static async Task<int> Main(string[] args)
{
if (args.Length == 3 && args[0] == "--serve-wrong-pipe")
{
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try { await Serve(args[1], JsonSerializer.Deserialize<InstallerGuardianGate.PipeApproval>(File.ReadAllText(args[2]))!, 1, deadline.Token); }
catch (IOException) { } // The real gate rejects this child's PID.
return 0;
}
if (args.Length == 1 && args[0] == "--installer-verify") return 0;
if (args.Length == 5 && args[0] is "--installer-guardian-gate" or "--installer-guardian-apply")
return InstallerGuardianGate.Run(args[1], args[2], args[3], args[4], args[0] == "--installer-guardian-apply",
diagnostic: error => File.WriteAllText(Path.Combine(args[2], "fixture-diagnostic.txt"),
JsonSerializer.Serialize(new { Args = args, Source = AppContext.BaseDirectory }) + Environment.NewLine + error));
if (args.Length == 2 && args[0] == "--test")
{
try { return await Tests(args[1]); } catch (Exception e) { Console.Error.WriteLine(e); return 1; }
}
// A forbidden client startup/shutdown is observable, but never loads UI
// or signals a production client. Paths are strictly generated fixtures.
var directory = args.Length == 2 && args[0] == "--shutdown-installed" ? args[1] : Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
if (Path.GetFileName(directory) == "installed" && Path.GetFileName(Path.GetDirectoryName(directory)!).StartsWith("ucvl-guardian-fixture-", StringComparison.Ordinal))
File.WriteAllText(Path.Combine(directory, args.Length == 0 || args[0] == "--auto-connect" ? "unexpected-start.fixture" : "unexpected-shutdown.fixture"), "FORBIDDEN FIXTURE INVOCATION");
return 98;
}
}