Files

121 lines
8.3 KiB
C#
Raw Permalink Normal View History

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
namespace UCVL.VPNPlus;
// Explicit diagnostic only: unique loopback ports, config via stdin, no TUN,
// no saved credentials, no system proxy, no recovery/installed-client actions.
internal static class PrivateTransportProbe
{
private sealed record Pairing(string Host, string Pin, string Password);
internal static async Task<int> RunAsync(string xrayPath)
{
var checks = new Dictionary<string, bool>();
string? failure = null;
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(100));
try
{
var input = Console.In.ReadLine();
if (input is null || input.Length > 4096) throw new InvalidOperationException("pairing_input");
var pairing = JsonSerializer.Deserialize<Pairing>(input) ?? throw new InvalidOperationException("pairing_missing");
if (pairing.Host != PrivateAuxiliaryRouting.JinanAddress || !Regex.IsMatch(pairing.Pin, "^[0-9a-f]{64}$")
|| !Regex.IsMatch(pairing.Password, "^[0-9a-f]{48}$") || !File.Exists(xrayPath))
throw new InvalidOperationException("pairing_invalid");
checks["user_supplied_site_route_exists"] = PrivateAuxiliaryRuntime.HasPreservedRoute(
new WindowsRouteTable().Snapshot(), System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
.Where(n => !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.Select(n => n.GetIPProperties().GetIPv4Properties()?.Index ?? 0).ToHashSet());
var positive = await RunCoreAsync(xrayPath, pairing, includeDns: true, deadline.Token);
foreach (var item in positive) checks[item.Key] = item.Value;
var badPin = await RunCoreAsync(xrayPath, pairing with { Pin = new string('0', 64) }, false, deadline.Token);
checks["wrong_leaf_pin_rejected_by_actual_core"] = !badPin["google_https_204"];
var badPassword = await RunCoreAsync(xrayPath, pairing with { Password = new string('0', 48) }, false, deadline.Token);
checks["wrong_socks_password_rejected_by_actual_core"] = !badPassword["google_https_204"];
var after = await RunCoreAsync(xrayPath, pairing, false, deadline.Token);
checks["positive_control_after_negative_cases"] = after["google_https_204"];
}
catch (Exception e) { failure = e.GetType().Name; }
var passed = failure is null && checks.Count >= 7 && checks.Values.All(v => v);
var report = JsonSerializer.Serialize(new { passed, network_modified = false, tun_started = false,
authenticated_business_tested = false, per_employee_authorization_tested = false,
production_released = false, failure, checks }, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "private-transport-board-test.json"), report);
Console.WriteLine(report);
return passed ? 0 : 20;
}
private static async Task<Dictionary<string, bool>> RunCoreAsync(string xrayPath, Pairing pairing, bool includeDns, CancellationToken token)
{
var tcp = new TcpListener(IPAddress.Loopback, 0); tcp.Start();
var httpPort = ((IPEndPoint)tcp.LocalEndpoint).Port; tcp.Stop();
int dnsPort;
using (var udp = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0))) dnsPort = ((IPEndPoint)udp.Client.LocalEndPoint!).Port;
var root = JsonNode.Parse("""
{"log":{"loglevel":"error"},"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"socks","settings":{"servers":[]},"streamSettings":{"network":"tcp","security":"tls","tlsSettings":{"serverName":"zero3-test","minVersion":"1.2"}}},{"tag":"direct","protocol":"freedom"}],"routing":{"rules":[]}}
""")!;
root["outbounds"]![0]!["settings"]!["servers"] = new JsonArray(new JsonObject {
["address"] = pairing.Host, ["port"] = 18081,
["users"] = new JsonArray(new JsonObject { ["user"] = "zero3-test", ["pass"] = pairing.Password }) });
root["outbounds"]![0]!["streamSettings"]!["tlsSettings"]!["pinnedPeerCertSha256"] = pairing.Pin;
root["inbounds"] = new JsonArray(
new JsonObject { ["tag"] = "probe-http", ["listen"] = "127.0.0.1", ["port"] = httpPort, ["protocol"] = "http" },
new JsonObject { ["tag"] = "tun-in", ["listen"] = "127.0.0.1", ["port"] = dnsPort, ["protocol"] = "dokodemo-door",
["settings"] = new JsonObject { ["address"] = "8.8.8.8", ["port"] = 53, ["network"] = "udp" } });
var response = new ConfigResponse { Config = JsonSerializer.SerializeToElement(root),
ConnectionScope = PrivateAuxiliaryRouting.Scope, ConfigExpiresAt = DateTimeOffset.UtcNow.AddMinutes(2) };
// Exercise the SAME runtime adapter as the candidate client, with no TUN.
var config = TunConfigBuilder.Build(response.GetRuntimeConfigJson(), "", false, includeTun: false);
using var process = new Process { StartInfo = new ProcessStartInfo {
FileName = xrayPath, WorkingDirectory = Path.GetDirectoryName(xrayPath)!,
UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true,
RedirectStandardOutput = true, RedirectStandardError = true } };
process.StartInfo.ArgumentList.Add("run"); process.StartInfo.ArgumentList.Add("-c"); process.StartInfo.ArgumentList.Add("stdin:");
process.Start();
var output = process.StandardOutput.ReadToEndAsync(); var errors = process.StandardError.ReadToEndAsync();
try
{
await process.StandardInput.WriteAsync(config.AsMemory(), token); process.StandardInput.Close();
await Task.Delay(700, token);
if (process.HasExited) throw new IOException("isolated_core_start_failed");
var result = new Dictionary<string, bool>();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = true,
Proxy = new WebProxy($"http://127.0.0.1:{httpPort}"), AllowAutoRedirect = false,
ConnectTimeout = TimeSpan.FromSeconds(6) }) { Timeout = TimeSpan.FromSeconds(12) };
async Task<int> Get(string uri)
{
try { using var reply = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, token); return (int)reply.StatusCode; }
catch (Exception e) when (e is HttpRequestException or TaskCanceledException) { return 0; }
}
result["google_https_204"] = await Get("https://www.google.com/generate_204") == 204;
if (includeDns)
{
var status = await Get("https://chatgpt.com/backend-api/codex/models");
result["codex_endpoint_tls_transport_only"] = status is >= 200 and < 500;
// DNS datagram enters the loopback adapter; Xray must turn it into
// DoH through the authenticated TCP relay (board has no UDP).
using var dns = new UdpClient(); dns.Connect(IPAddress.Loopback, dnsPort);
byte[] question = [0x4b,0x31,1,0,0,1,0,0,0,0,0,0,3,119,119,119,6,103,111,111,103,108,101,3,99,111,109,0,0,1,0,1];
await dns.SendAsync(question, token);
using var dnsDeadline = CancellationTokenSource.CreateLinkedTokenSource(token); dnsDeadline.CancelAfter(TimeSpan.FromSeconds(12));
try { var answer = (await dns.ReceiveAsync(dnsDeadline.Token)).Buffer;
result["dns_datagram_via_encrypted_tcp_doh"] = answer.Length > 12 && answer[0] == 0x4b && answer[1] == 0x31
&& (answer[2] & 0x80) != 0 && (answer[3] & 15) == 0 && (answer[6] > 0 || answer[7] > 0); }
catch (OperationCanceledException) when (!token.IsCancellationRequested) { result["dns_datagram_via_encrypted_tcp_doh"] = false; }
result["second_https_request_succeeds"] = await Get("https://www.google.com/generate_204") == 204;
}
return result;
}
finally
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
await process.WaitForExitAsync();
await output; await errors; // Do not print core logs containing endpoint/config details.
}
}
}