Files
ucvl-zonghengjia-open-source/windows/PrivateAuxiliaryRouting.cs
T

245 lines
16 KiB
C#
Raw Normal View History

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace UCVL.VPNPlus;
// Availability preference, NOT identity/authentication. No route/gateway edits,
// LAN scanning, GPS, employee-office lookup or Tailscale process detection.
internal static class PrivateAuxiliaryRouting
{
internal const string JinanAddress = "192.168.50.111";
internal const string PhoneAddress = "192.168.50.170";
internal const string PhoneTailnetAddress = "100.64.0.4";
internal const string PublicPhoneAddress = "192.0.2.1";
internal const string PublicPhoneHost = "vpn.example.invalid";
internal static bool IsRegisteredEndpoint(string? address) =>
address is JinanAddress or PhoneAddress or PhoneTailnetAddress or PublicPhoneAddress or PublicPhoneHost;
internal static bool ValidEndpoint(PrivateAuxiliaryNode node) =>
node.ProbePort == 18081 && (node.ProbeIpv4 is JinanAddress or PhoneAddress or PhoneTailnetAddress)
&& node.EndpointHost == node.ProbeIpv4
|| node.ProbePort == 11080 && node.ProbeIpv4 == PublicPhoneAddress && node.EndpointHost == PublicPhoneHost;
internal const string Scope = "private_auxiliary";
internal const int Contract = 1;
private static readonly Regex Slug = new("^[a-z0-9][a-z0-9-]{0,79}$", RegexOptions.CultureInvariant);
internal static IReadOnlyList<PrivateAuxiliaryNode> Eligible(Profile profile, DateTimeOffset now)
{
if (profile.IdentityType != "employee" || profile.Subscription.Status != "active"
|| profile.Subscription.ExpiresAt is { } expiry && expiry <= now
|| profile.Subscription.TrafficLimitBytes > 0
&& profile.Subscription.UsedBytes >= profile.Subscription.TrafficLimitBytes)
return [];
var publicSlugs = profile.Nodes.Select(n => n.Slug).ToHashSet(StringComparer.Ordinal);
var privateNodes = (profile.PrivateAuxiliaryNodes ?? []).Where(n => n is not null && n.Slug is not null).ToArray();
var duplicates = privateNodes.GroupBy(n => n.Slug, StringComparer.Ordinal)
.Where(g => g.Count() != 1).Select(g => g.Key).ToHashSet(StringComparer.Ordinal);
return privateNodes.Where(n => n.Contract == Contract && ValidEndpoint(n)
&& n.TlsLeafSha256 is not null && Regex.IsMatch(n.TlsLeafSha256, "^[a-fA-F0-9]{64}$", RegexOptions.CultureInvariant)
&& n.Status == "candidate" && n.ExpiresAt > now && Slug.IsMatch(n.Slug)
&& n.Slug != "auto" && !publicSlugs.Contains(n.Slug) && !duplicates.Contains(n.Slug))
.Take(3).ToArray(); // Fixed registered endpoints only; never discover or scan other devices.
}
internal static async Task<long?> MeasureEndpointAsync(PrivateAuxiliaryNode node, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!ValidEndpoint(node) || node.ExpiresAt <= DateTimeOffset.UtcNow
|| !Regex.IsMatch(node.TlsLeafSha256 ?? "", "^[a-fA-F0-9]{64}$")) return null;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(TimeSpan.FromMilliseconds(2300));
try
{
using var ping = new Ping();
long pingLatency = long.MaxValue;
try {
var reply = await ping.SendPingAsync(IPAddress.Parse(node.ProbeIpv4), 800).WaitAsync(deadline.Token);
if (reply.Status == IPStatus.Success && reply.Address?.ToString() == node.ProbeIpv4)
pingLatency = reply.RoundtripTime;
} catch (PingException) { /* ICMP filtering is not proof of a broken proxy. */ }
using var socket = new TcpClient(AddressFamily.InterNetwork);
await socket.ConnectAsync(IPAddress.Parse(node.ProbeIpv4), node.ProbePort, deadline.Token);
// The management-supplied leaf pin authenticates the endpoint before
// any device credentials. A ping or open TCP port alone is insufficient.
using var tls = new SslStream(socket.GetStream(), false, (_, cert, _, _) => cert is not null
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(cert.GetRawCertData()),
Convert.FromHexString(node.TlsLeafSha256!)));
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions {
TargetHost = "zero3-test", EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
}, deadline.Token);
token.ThrowIfCancellationRequested();
return node.ExpiresAt > DateTimeOffset.UtcNow ? pingLatency : null;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return null; }
catch (Exception e) when (e is SocketException or IOException or AuthenticationException or PingException) { return null; }
}
internal static async Task<IReadOnlyList<PrivateAuxiliaryNode>> RankByLatencyAsync(
IReadOnlyList<PrivateAuxiliaryNode> grants, IReadOnlySet<string> coolingDown,
Func<PrivateAuxiliaryNode, CancellationToken, Task<long?>> measure, CancellationToken token)
{
token.ThrowIfCancellationRequested();
var candidates = grants.Where(n => ValidEndpoint(n)
&& n.ExpiresAt > DateTimeOffset.UtcNow && !coolingDown.Contains(n.Slug)).Take(3).ToArray();
var readings = await Task.WhenAll(candidates.Select(async (node, index) =>
(Node: node, Index: index, Latency: await measure(node, token))));
token.ThrowIfCancellationRequested();
return readings.Where(r => r.Latency is >= 0 && r.Node.ExpiresAt > DateTimeOffset.UtcNow)
.OrderBy(r => r.Node.ProbeIpv4 == PublicPhoneAddress ? 1 : 0)
.ThenBy(r => r.Latency).ThenBy(r => r.Index).Select(r => r.Node).ToArray();
}
internal static async Task<IReadOnlyList<PrivateAuxiliaryNode>> RankForSelectionAsync(ConnectionSelection selection,
IReadOnlyList<PrivateAuxiliaryNode> grants, IReadOnlySet<string> coolingDown, bool existingCoreRunning,
Func<PrivateAuxiliaryNode, CancellationToken, Task<long?>> measure, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (existingCoreRunning && !selection.Manual) return [];
var authorized = selection.Manual ? grants.Where(n => n.Slug == selection.NodeSlug) : grants;
var expanded = authorized.SelectMany(n => n.ConnectionEndpoints.Count == 0 ? new[] { n }
: n.ConnectionEndpoints.Take(3).Select(n.WithEndpoint)).ToArray();
var ranked = await RankByLatencyAsync(expanded, selection.Manual ? new HashSet<string>() : coolingDown, measure, token);
if (selection.Manual && expanded.Length > 0 && ranked.Count == 0)
throw new InvalidOperationException("所选节点内网和域名入口均不可达,未切换其他节点。");
return ranked;
}
internal static PrivateAuxiliaryNode ForRenewal(PrivateAuxiliaryNode grant, PrivateAuxiliaryNode current)
{
if (grant.Slug != current.Slug || !ValidEndpoint(current))
throw new InvalidOperationException("当前私有节点入口与授权不匹配。");
// Refresh the lease for the ACTUAL successful transport, never replace a
// healthy domain fallback with the profile's preferred tailnet address.
if (grant.ConnectionEndpoints.Count == 0 && grant.EndpointHost == current.EndpointHost
&& grant.ProbeIpv4 == current.ProbeIpv4 && grant.ProbePort == current.ProbePort) return grant;
var endpoint = grant.ConnectionEndpoints.SingleOrDefault(e => e.Address == current.EndpointHost
&& e.ProbeIpv4 == current.ProbeIpv4 && e.Port == current.ProbePort);
return endpoint is not null ? grant.WithEndpoint(endpoint)
: throw new InvalidOperationException("当前私有节点入口已撤回,未自动更换连接方式。");
}
internal static async Task<PrivateAuxiliaryNode?> SelectByLatencyAsync(ConnectionSelection selection,
IReadOnlyList<PrivateAuxiliaryNode> grants, IReadOnlySet<string> coolingDown, bool existingCoreRunning,
Func<PrivateAuxiliaryNode, CancellationToken, Task<long?>> measure, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (existingCoreRunning && !selection.Manual) return null;
if (!selection.Manual)
return (await RankByLatencyAsync(grants, coolingDown, measure, token)).FirstOrDefault();
var node = grants.SingleOrDefault(n => n.Slug == selection.NodeSlug);
if (node is null) return null;
if (!IsRegisteredEndpoint(node.ProbeIpv4) || node.ExpiresAt <= DateTimeOffset.UtcNow)
throw new InvalidOperationException("所选私有节点授权无效,未切换其他节点。");
var latency = await measure(node, token);
token.ThrowIfCancellationRequested();
if (latency is >= 0 && node.ExpiresAt > DateTimeOffset.UtcNow) return node;
throw new InvalidOperationException("所选私有节点加密入口暂不可达,未切换其他节点。");
}
internal static async Task<bool> PingAsync(PrivateAuxiliaryNode node, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (node.ProbeIpv4 != JinanAddress || node.ExpiresAt <= DateTimeOffset.UtcNow) return false;
try
{
using var ping = new Ping();
var reply = await ping.SendPingAsync(IPAddress.Parse(JinanAddress), 800).WaitAsync(token);
return reply.Status == IPStatus.Success && reply.Address?.ToString() == JinanAddress;
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch (Exception e) when (e is PingException or System.Net.Sockets.SocketException
or System.Security.SecurityException or PlatformNotSupportedException)
{ return false; }
}
internal static async Task<PrivateAuxiliaryNode?> SelectAsync(ConnectionSelection selection,
IReadOnlyList<PrivateAuxiliaryNode> grants, IReadOnlySet<string> coolingDown, bool existingCoreRunning,
Func<PrivateAuxiliaryNode, CancellationToken, Task<bool>> probe, CancellationToken token)
{
token.ThrowIfCancellationRequested();
// Healthy/running public sessions are not moved merely because ping now succeeds.
if (existingCoreRunning && !selection.Manual) return null;
var node = selection.Manual ? grants.SingleOrDefault(n => n.Slug == selection.NodeSlug)
: grants.FirstOrDefault(n => !coolingDown.Contains(n.Slug));
if (node is null) return null; // No configured grant: do not fabricate a node from an IP/name.
var reachable = await probe(node, token);
token.ThrowIfCancellationRequested();
if (reachable) return node;
if (selection.Manual) throw new InvalidOperationException("济南办私有节点暂不可达,未切换其他节点。");
return null;
}
internal static void ValidateConfig(PrivateAuxiliaryNode requested, ConfigResponse response, string route)
{
// Management token goes ONLY to the management API. A ping responder receives no token.
var now = DateTimeOffset.UtcNow;
if (!ValidEndpoint(requested) || requested.ExpiresAt <= now || response.ConnectionScope != Scope
|| response.ConfigContract != 3 || response.Node.Slug != requested.Slug
|| response.RouteMode != route || route is not ("smart" or "global") || response.Gateway is not null
|| response.ConfigExpiresAt is not { } expiry || expiry <= now
|| expiry > requested.ExpiresAt || expiry > now.AddMinutes(15))
throw new InvalidOperationException("私有辅助节点授权或配置不匹配,已拒绝连接。");
// This is the board's actual TCP SOCKS5 + pinned TLS protocol, NOT VLESS/Reality.
// Only a dedicated authenticated management response can activate it. USB trial
// credentials are accepted only by the isolated diagnostic, never this API path.
var root = response.Config;
if (!root.TryGetProperty("outbounds", out var outboundArray) || outboundArray.ValueKind != JsonValueKind.Array)
throw new InvalidOperationException("私有辅助节点缺少加密出站配置。");
var proxies = outboundArray.EnumerateArray().Where(o => Text(o, "tag") == "proxy").ToArray();
if (proxies.Length != 1) throw new InvalidOperationException("私有辅助节点出站数量不正确。");
var p = proxies[0];
if (Text(p, "protocol") != "socks" || !p.TryGetProperty("settings", out var settings)
|| !settings.TryGetProperty("servers", out var servers) || servers.ValueKind != JsonValueKind.Array
|| servers.GetArrayLength() != 1 || Text(servers[0], "address") != requested.EndpointHost
|| !servers[0].TryGetProperty("port", out var port) || !port.TryGetInt32(out var portNumber)
|| portNumber != requested.ProbePort
|| !p.TryGetProperty("streamSettings", out var stream) || Text(stream, "security") != "tls"
|| Text(stream, "network") != "tcp"
|| !stream.TryGetProperty("tlsSettings", out var tls)
|| Text(tls, "serverName") != "zero3-test"
|| !string.Equals(Text(tls, "pinnedPeerCertSha256"), requested.TlsLeafSha256, StringComparison.OrdinalIgnoreCase)
|| requested.TlsLeafSha256.Length != 64
|| tls.TryGetProperty("allowInsecure", out var insecure) && insecure.ValueKind != JsonValueKind.False)
throw new InvalidOperationException("私有辅助节点尚未提供兼容的加密入口,已拒绝连接。");
if (!servers[0].TryGetProperty("users", out var users) || users.ValueKind != JsonValueKind.Array
|| users.GetArrayLength() != 1 || Text(users[0], "user") is not { Length: >= 1 and <= 100 } username
|| username == "zero3-test" || Text(users[0], "pass") is not { Length: >= 32 and <= 255 })
throw new InvalidOperationException("私有辅助节点缺少有效设备凭据。");
}
private static string? Text(JsonElement value, string name) => value.ValueKind == JsonValueKind.Object
&& value.TryGetProperty(name, out var child) && child.ValueKind == JsonValueKind.String ? child.GetString() : null;
}
internal sealed record ConnectionAttempt(string Slug, PrivateAuxiliaryNode? Auxiliary)
{
internal bool IsPrivate => Auxiliary is not null;
}
internal static class ConnectionAttemptPlanner
{
internal static IReadOnlyList<ConnectionAttempt> CreateRanked(ConnectionSelection selection,
IReadOnlyList<PrivateAuxiliaryNode> ranked, int publicCount)
{
if (selection.Manual)
return ranked.Count == 0 ? [new(selection.NodeSlug, null)]
: ranked.Where(n => n.Slug == selection.NodeSlug).Select(n => new ConnectionAttempt(n.Slug, n)).ToArray();
return ranked.Select(n => new ConnectionAttempt(n.Slug, n))
.Concat(Enumerable.Range(0, Math.Clamp(publicCount, 0, 8)).Select(_ => new ConnectionAttempt("auto", null))).ToArray();
}
internal static IReadOnlyList<ConnectionAttempt> Create(ConnectionSelection selection,
PrivateAuxiliaryNode? preferred, int publicCount)
{
if (selection.Manual) return [new(selection.NodeSlug, preferred)];
var result = new List<ConnectionAttempt>();
if (preferred is not null) result.Add(new(preferred.Slug, preferred));
for (var i = 0; i < Math.Clamp(publicCount, 0, 8); i++) result.Add(new("auto", null));
return result;
}
}