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

274 lines
15 KiB
C#
Raw Permalink Normal View History

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 const int EndpointProbeTimeoutSeconds = 5;
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>();
internal sealed record RouteBinding(string InterfaceName, int InterfaceIndex, IPAddress LocalAddress, IPAddress? Gateway = null);
// A company router can forward the authorized address over its Tailscale even
// when Windows has only a default route. Bind the probe to the chosen interface.
// A TCP response only permits trying the node; the normal proxy proof still runs.
internal static async Task<RouteBinding?> ProbeAuthorizedRouteAsync(string address, int port, CancellationToken token,
Func<string, RouteBinding>? readSpecificRoute = null,
Func<PhysicalUplink.Reading>? readUplink = null,
Func<string, int, RouteBinding, CancellationToken, Task<bool>>? probe = null)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return null;
RouteBinding? binding;
try { binding = readSpecificRoute is null ? ResolveRoute(address, true) : readSpecificRoute(address); }
catch (Exception error) when (IsRouteUnavailable(error))
{
var uplink = readUplink is null ? PhysicalUplink.Read() : readUplink();
binding = uplink.Success ? GatewayBinding(uplink.Network) : null;
}
token.ThrowIfCancellationRequested();
if (binding is null) return null;
var reachable = await (probe ?? ProbeBoundEndpointAsync)(address, port, binding, token);
token.ThrowIfCancellationRequested();
return reachable ? binding : null;
}
private static RouteBinding? GatewayBinding(TunRouting.PhysicalNetwork? network)
{
if (network is null || network.InterfaceIndex <= 0 || network.Ipv4Gateway.Equals(IPAddress.Any)
|| IsTailnetAddress(network.Ipv4Address.ToString())) return null;
return new(network.InterfaceName, network.InterfaceIndex, network.Ipv4Address, network.Ipv4Gateway);
}
internal static async Task<bool> ProbeBoundEndpointAsync(string address, int port, RouteBinding binding, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
try
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Winsock IP_UNICAST_IF expects the IPv4 interface index in network byte order.
const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(binding.InterfaceIndex));
socket.Bind(new IPEndPoint(binding.LocalAddress, 0));
await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
}
private static bool IsRouteUnavailable(Exception error) => error is SocketException or NetworkInformationException
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception;
internal static RouteBinding RequireCurrentBinding(string address, RouteBinding? binding, TunRouting.PhysicalNetwork physicalNetwork)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
if (binding?.Gateway is not null)
{
var uplink = PhysicalUplink.Read(binding.InterfaceIndex);
if (!uplink.Success || GatewayBinding(uplink.Network) != binding || GatewayBinding(physicalNetwork) != binding)
throw new InvalidOperationException("公司网关路径已变化,请重新检测内网入口。");
return binding;
}
var current = ResolveRoute(address, true);
if (binding is not null && current != binding)
throw new InvalidOperationException("Tailscale 路由已变化,请重新检测内网入口。");
return current;
}
// Strict native-route detection for private-node policy and the standalone probe.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
try
{
return await ProbeBoundEndpointAsync(address, port, ResolveRoute(address, true), token).ConfigureAwait(false);
}
catch (Exception error) when (IsRouteUnavailable(error)) { 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).InterfaceName;
// 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 RouteBinding 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 (local is null || owner?.GetIPProperties().GetIPv4Properties()?.Index is not { } index)
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
if (requireSpecificRoute && SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index)
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
return new(owner.Name, index, local);
}
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;
}