Files
ucvl-zonghengjia-open-source/windows/TailnetTransport.cs
2026-10-11 23:23:20 +00:00

177 lines
9.9 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)
{
var endpoint = response.TailscaleEndpoint ?? KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints);
if (endpoint is null || endpoint.Contract != 1 || endpoint.NodeSlug != response.Node.Slug
|| string.IsNullOrWhiteSpace(endpoint.NodeSlug) || !IsTailnetAddress(endpoint.Address)
|| endpoint.Port is < 1 or > 65535 || response.ConfigContract != 2
|| response.ConnectionScope is not ("" or "public") || response.RouteMode is not ("smart" or "global"))
return null;
try
{
var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject();
if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null;
var proxy = Proxy(root);
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 };
return root.ToJsonString();
}
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{ 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>();
// Before starting/replacing a core, test only this socket through the existing
// user-owned route. ICMP success isn't enough; TCP success still isn't auth.
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(3));
try
{
var name = RequireExistingRoute(address);
var nic = NetworkInterface.GetAllNetworkInterfaces().Single(n => n.Name == name);
var index = nic.GetIPProperties().GetIPv4Properties()!.Index;
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Windows IP_UNICAST_IF=31 is not named by .NET 8's enum.
// https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(index));
await socket.ConnectAsync(new IPEndPoint(IPAddress.Parse(address), port), deadline.Token);
return true;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception e) when (e is SocketException or NetworkInformationException or InvalidOperationException) { 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.
// Require an existing more-specific route; never manufacture a /32 through the
// phone/default gateway. Bind the proxy socket to that interface so a lost
// tailnet route cannot silently recurse into our own TUN.
internal static string RequireExistingRoute(string address)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
var interfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.Select(n => new { n.Name, Index = n.GetIPProperties().GetIPv4Properties()?.Index })
.Where(n => n.Index.HasValue).ToDictionary(n => n.Index!.Value, n => n.Name);
var index = SelectRoute(address, new WindowsRouteTable().Snapshot(), interfaces.Keys.ToHashSet());
return index is { } found ? interfaces[found]
: throw new InvalidOperationException("Tailscale 节点路径暂不可用,保留原入口作为回退。");
}
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);
// Only an explicit user connect action resets failures. Automatic recovery
// continues respecting the existing monotonic cooldown.
internal void ResetForUserConnect() => _cooldowns.Clear();
internal bool MayTry(string slug, long now) => !_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry;
internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000;
}