Files
ucvl-zonghengjia-open-source/windows/TailnetTransport.cs

213 lines
12 KiB
C#

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.Json.Nodes;
namespace UCVL.VPNPlus;
// A transport alternative for the SAME authorized public node. This does not
// start/configure Tailscale, change its ACLs, or turn reachability into identity.
internal static class TailnetTransport
{
internal const string Marker = "ucvl_tailnet_transport";
internal static bool IsTailnetAddress(string? value) =>
IPAddress.TryParse(value, out var ip) && ip.AddressFamily == AddressFamily.InterNetwork
&& ip.ToString() == value && ip.GetAddressBytes()[0] == 100
&& ip.GetAddressBytes()[1] is >= 64 and <= 127
&& value is not ("100.100.100.100" or "100.64.0.0" or "100.127.255.255");
internal static string? TryPrepare(ConfigResponse response, bool allowKnownEndpoints = false)
=> TryPrepare(response, out _, allowKnownEndpoints);
internal static string? TryPrepare(ConfigResponse response, out string reason, bool allowKnownEndpoints = false)
{
reason = "explicit_endpoint";
var endpoint = response.TailscaleEndpoint;
if (endpoint is null)
{
if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; }
endpoint = KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints, out reason);
if (endpoint is null) return null;
}
var source = reason;
reason = "endpoint_contract_unsupported";
if (endpoint.Contract != 1) return null;
reason = "endpoint_node_mismatch";
if (endpoint.NodeSlug != response.Node.Slug || string.IsNullOrWhiteSpace(endpoint.NodeSlug)) return null;
reason = "endpoint_address_invalid";
if (!IsTailnetAddress(endpoint.Address)) return null;
reason = "endpoint_port_invalid";
if (endpoint.Port is < 1 or > 65535) return null;
reason = "config_contract_unsupported";
if (response.ConfigContract != 2) return null;
reason = "scope_unsupported";
if (response.ConnectionScope is not ("" or "public")) return null;
reason = "route_mode_unsupported";
if (response.RouteMode is not ("smart" or "global")) return null;
try
{
var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject();
reason = "config_scope_or_marker_invalid";
if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null;
var proxy = Proxy(root);
reason = "proxy_identity_unsupported";
if (proxy is null) return null;
var server = proxy["settings"]!["vnext"]![0]!.AsObject();
// Preserve users/flow/encryption/Reality key/SNI/shortId and all rules.
// Never send the management access token to this endpoint.
server["address"] = endpoint.Address;
server["port"] = endpoint.Port;
root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port };
reason = source;
return root.ToJsonString();
}
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{ reason = "config_invalid"; return null; } // Invalid optional metadata never breaks the original ingress.
}
internal static JsonObject? Proxy(JsonObject root)
{
if (root["outbounds"] is not JsonArray outbounds) return null;
var proxies = outbounds.OfType<JsonObject>().Where(o => o["tag"]?.GetValue<string>() == "proxy").ToArray();
if (proxies.Length != 1) return null;
var proxy = proxies[0];
if (proxy["protocol"]?.GetValue<string>() != "vless"
|| proxy["settings"]?["vnext"] is not JsonArray { Count: 1 } servers
|| servers[0]?["users"] is not JsonArray { Count: > 0 }
|| proxy["streamSettings"]?["security"]?.GetValue<string>() != "reality"
|| proxy["streamSettings"]?["network"]?.GetValue<string>() is not ("tcp" or "raw")
|| proxy["streamSettings"]?["realitySettings"] is not JsonObject reality
|| string.IsNullOrWhiteSpace(reality["serverName"]?.GetValue<string>())
|| string.IsNullOrWhiteSpace((reality["password"] ?? reality["publicKey"])?.GetValue<string>())) return null;
return proxy;
}
internal static string? Address(JsonObject root)
{
if (!root.ContainsKey(Marker)) return null;
var address = root[Marker]?["address"]?.GetValue<string>();
var port = root[Marker]?["port"]?.GetValue<int>();
var proxy = Proxy(root);
if (!IsTailnetAddress(address) || port is null or < 1 or > 65535 || proxy is null
|| proxy["settings"]!["vnext"]![0]!["address"]?.GetValue<string>() != address
|| proxy["settings"]!["vnext"]![0]!["port"]?.GetValue<int>() != port)
throw new InvalidOperationException("Tailscale 入口与授权节点配置不一致。");
return address;
}
internal static string? Address(string json) => Address(JsonNode.Parse(json)!.AsObject());
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// Selection checks only ICMP through the existing OS network. It never
// queries or changes Tailscale; authenticated proxy health is checked after
// starting the chosen authorized transport, separately from reachability.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(TimeSpan.FromSeconds(5));
try
{
RequireProbeRoute(address);
// The first connection may need to establish a Tailscale path.
// Test the actual proxy listener instead of gating on ICMP.
using var socket = new TcpClient(AddressFamily.InterNetwork);
await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception e) when (e is SocketException or NetworkInformationException
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; }
}
internal static bool SameAuthorizedFallback(string current, string? fallback)
{
if (fallback is null) return false;
try
{
var a = JsonNode.Parse(current)!.AsObject(); var b = JsonNode.Parse(fallback)!.AsObject();
if (Address(a) is null || b.ContainsKey(Marker) || PrivateAuxiliaryRuntime.IsPrivate(b)) return false;
var bp = Proxy(b); if (bp is null) return false;
a.Remove(Marker);
var server = Proxy(a)!["settings"]!["vnext"]![0]!;
server["address"] = bp["settings"]!["vnext"]![0]!["address"]!.DeepClone();
server["port"] = bp["settings"]!["vnext"]![0]!["port"]!.DeepClone();
return JsonNode.DeepEquals(a, b);
}
catch { return false; }
}
// Read only. No CLI/process/service dependency: user owns the underlying network.
// Ask Windows which existing interface owns this IP path, including a valid
// default route. No adapter-name, service or route-prefix prerequisite.
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
// no /32 or user route is manufactured or removed.
internal static string RequireExistingRoute(string address) => ResolveRoute(address, false);
// Candidate discovery requires a specific existing route to the authorized
// Tailnet address. A generic internet default must not carry probe packets.
internal static void RequireProbeRoute(string address) => ResolveRoute(address, true);
private static string ResolveRoute(string address, bool requireSpecificRoute)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
route.Connect(new IPEndPoint(IPAddress.Parse(address), 443));
var local = (route.LocalEndPoint as IPEndPoint)?.Address;
var owner = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
if (owner is null)
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index
|| SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index))
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
return owner.Name;
}
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
{
if (!IsTailnetAddress(address)) return null;
var target = IPAddress.Parse(address).GetAddressBytes();
var matches = new List<(Ipv4Route Route, int Prefix)>();
foreach (var route in routes)
{
if (!IPAddress.TryParse(route.Mask, out var mask) || mask.AddressFamily != AddressFamily.InterNetwork
|| !IPAddress.TryParse(route.Destination, out var dest) || dest.AddressFamily != AddressFamily.InterNetwork) continue;
var m = mask.GetAddressBytes(); var d = dest.GetAddressBytes();
var prefix = 0; var zero = false; var valid = true;
foreach (var b in m) for (var bit = 7; bit >= 0; bit--)
{
var one = (b & (1 << bit)) != 0;
if (one && zero) valid = false;
if (one) prefix++; else zero = true;
}
if (valid && prefix > 1 && Enumerable.Range(0, 4).All(i => (target[i] & m[i]) == (d[i] & m[i])))
matches.Add((route, prefix));
}
if (matches.Count == 0) return null;
var longest = matches.Max(r => r.Prefix);
var preferred = matches.Where(r => r.Prefix == longest).Select(r => r.Route).ToArray();
// Ambiguous, down, or our own more-specific route: fail closed.
var indices = preferred.Select(r => r.InterfaceIndex).Distinct().ToArray();
return indices.Length == 1 && usable.Contains(indices[0]) ? indices[0] : null;
}
}
// Monotonic cooldown affects only NEW attempts, not healthy existing sessions.
internal sealed class TailnetPreference
{
private readonly Dictionary<string, long> _cooldowns = new(StringComparer.Ordinal);
internal bool DomainOnly { get; private set; }
// Only an explicit user connect action resets failures. Automatic recovery
// continues respecting the existing monotonic cooldown.
internal void ResetForUserConnect() { _cooldowns.Clear(); DomainOnly = false; }
internal void CommitDomainFallback() => DomainOnly = true;
internal void ReleaseDomainFallbackAfterNodeFailure() => DomainOnly = false;
internal bool MayTry(string slug, long now) => !DomainOnly && (!_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry);
internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000;
}