Use verified company gateway for authorized Tailscale nodes

This commit is contained in:
UCVL Release
2026-11-16 10:37:17 +08:00
parent eb90ef4042
commit 16ac8227ea
7 changed files with 166 additions and 38 deletions
+1 -2
View File
@@ -63,9 +63,8 @@ internal sealed partial class MainForm
_checkingTailnetReadiness = true;
try
{
if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetEndpointConfirmation.ProbeAsync(
probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token);
_xray.ProbeCurrentOrPreferredTailnetAsync, _lifetime.Token);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
+9 -3
View File
@@ -564,19 +564,25 @@ internal sealed partial class MainForm : Form
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
_currentNodeLabel.Text = $"{candidateName} · 正在连接";
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
TailnetTransport.RouteBinding? tailnetBinding = null;
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
async (config, connectionToken) => {
candidateStarted = true;
replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate),
tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding);
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
TailnetTransport.RequireProbeRoute,
null,
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync,
endpointProbe: async (address, port, probeToken) =>
{
tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return tailnetBinding is not null;
},
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
+2 -2
View File
@@ -71,7 +71,7 @@ internal static class NodeTransportConnector
// No background race or periodic optimization may replace a healthy session.
internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference,
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
Action<string> requireRoute, Action<string> status, Func<long> ticks,
Action<string>? requireRoute, Action<string> status, Func<long> ticks,
CancellationToken token, bool allowKnownEndpoints = false,
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
Action<TransportDiagnostic>? diagnostic = null)
@@ -83,7 +83,7 @@ internal static class NodeTransportConnector
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
if (tailnet is null) Report("tailnet_skipped", reason);
else Report("tailnet_candidate", reason);
if (tailnet is not null)
if (tailnet is not null && requireRoute is not null)
{
try
{
+76 -15
View File
@@ -100,9 +100,40 @@ internal static class TailnetTransport
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// Check the authorized proxy port through the existing OS route. Proxy
// authentication and egress are verified separately after startup.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
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;
@@ -110,16 +141,47 @@ internal static class TailnetTransport
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
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);
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 e) when (e is SocketException or NetworkInformationException
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { 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)
@@ -144,13 +206,13 @@ internal static class TailnetTransport
// 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);
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 string ResolveRoute(string address, bool requireSpecificRoute)
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);
@@ -160,12 +222,11 @@ internal static class TailnetTransport
.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)
if (local is null || owner?.GetIPProperties().GetIPv4Properties()?.Index is not { } index)
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index
|| SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index))
if (requireSpecificRoute && SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index)
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
return owner.Name;
return new(owner.Name, index, local);
}
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
+37
View File
@@ -1,3 +1,4 @@
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -74,6 +75,42 @@ internal static class TailnetTransportSelfTest
checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null;
checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null;
checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null;
const string target = "100.99.142.38";
const int targetPort = 10803;
var native = new TailnetTransport.RouteBinding("Tailscale", 34, IPAddress.Parse("100.65.4.8"));
var office = new TunRouting.PhysicalNetwork("Ethernet", 9, IPAddress.Parse("172.16.1.154"),
24, IPAddress.Parse("172.16.1.1"), [IPAddress.Parse("172.16.1.1")]);
var gateway = new TailnetTransport.RouteBinding(office.InterfaceName, office.InterfaceIndex,
office.Ipv4Address, office.Ipv4Gateway);
TailnetTransport.RouteBinding NoSpecificRoute(string _) => throw new InvalidOperationException();
PhysicalUplink.Reading OfficeUplink() => new(true, office);
var testedBindings = new List<TailnetTransport.RouteBinding>();
Task<bool> Reachable(string address, int port, TailnetTransport.RouteBinding binding, CancellationToken token)
{
token.ThrowIfCancellationRequested();
testedBindings.Add(binding);
return Task.FromResult(address == target && port == targetPort);
}
checks["native_route_precedes_gateway"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, _ => native, () => throw new InvalidOperationException("Unused uplink"), Reachable) == native
&& testedBindings.SequenceEqual([native]);
testedBindings.Clear();
checks["company_gateway_requires_authorized_port_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, Reachable) == gateway
&& testedBindings.SequenceEqual([gateway]);
checks["unreachable_company_gateway_falls_back"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, (_, _, _, _) => Task.FromResult(false)) is null;
checks["no_gateway_no_unbound_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, () => new(true, office with { Ipv4Gateway = IPAddress.Any }),
(_, _, _, _) => throw new InvalidOperationException("Unbound probe")) is null;
checks["non_tailnet_address_never_probed"] = await TailnetTransport.ProbeAuthorizedRouteAsync("198.51.100.20", targetPort,
CancellationToken.None, _ => throw new InvalidOperationException("Unexpected route lookup"), OfficeUplink, Reachable) is null;
var routerRuntime = JsonNode.Parse(TunConfigBuilder.Build(prepared, office.InterfaceName, false, includeTun: false,
tailnetInterfaceName: gateway.InterfaceName))!.AsObject();
checks["router_runtime_binds_only_chosen_physical_interface"] =
routerRuntime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue<string>() == office.InterfaceName
&& Host(prepared) == target;
var preference = new TailnetPreference();
long tick = 100;
+4 -3
View File
@@ -112,7 +112,8 @@ internal static class TunRouting
IReadOnlyCollection<IPAddress> proxyServerAddresses,
CancellationToken cancellationToken,
bool preservePrivateNodeRoute = false,
string? preserveTailnetAddress = null)
string? preserveTailnetAddress = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{
if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。");
var proxyIpv4Addresses = proxyServerAddresses
@@ -134,7 +135,6 @@ internal static class TunRouting
if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1
|| proxyIpv4Addresses[0].ToString() != preserveTailnetAddress)
throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。");
TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
}
var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault();
if (tunDnsServer is null)
@@ -153,7 +153,8 @@ internal static class TunRouting
if (preservePrivateNodeRoute || preserveTailnetAddress is not null)
{
if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString());
if (preserveTailnetAddress is not null) TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
if (preserveTailnetAddress is not null)
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
}
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
preservePrivateNodeRoute || preserveTailnetAddress is not null);
+36 -12
View File
@@ -32,7 +32,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
// A public fallback is sticky: automatic physical-network recovery must
// never promote it to this cached internal alternative.
private string? _preferredTailnetConfigJson;
private string? _tailnetInterfaceName;
private TailnetTransport.RouteBinding? _tailnetBinding;
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
internal (string Address, int Port)? TailnetProbeEndpoint
{
@@ -56,6 +56,18 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
}
}
internal async Task<bool> ProbeCurrentOrPreferredTailnetAsync(CancellationToken token)
{
if (TailnetProbeEndpoint is not { } endpoint) return false;
if (!UsesTailnet)
return await TailnetTransport.ProbeAuthorizedRouteAsync(endpoint.Address, endpoint.Port, token) is not null;
var binding = _tailnetBinding;
// For an active session, verify the path used by Xray. A healthy
// alternate interface must not conceal failure of the current one.
return binding is not null
&& await TailnetTransport.ProbeBoundEndpointAsync(endpoint.Address, endpoint.Port, binding, token);
}
private string _routeMode = "smart";
private string _nodeSlug = "";
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
@@ -89,12 +101,20 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
replacementStarted = true;
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
token.ThrowIfCancellationRequested();
TailnetTransport.RouteBinding? binding = null;
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
async (config, rebindToken) =>
{
_baseConfigJson = config;
await StartCoreAsync(rebindToken, tailnetBinding: TailnetTransport.Address(config) is null ? null : binding);
},
StopCoreAsync, CheckProxyHealthAsync, token,
preferredTailnetConfig: _preferredTailnetConfigJson,
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
endpointProbe: TailnetTransport.ProbeEndpointAsync,
endpointProbe: async (address, port, probeToken) =>
{
binding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return binding is not null;
},
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage),
verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!));
}
@@ -209,7 +229,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
}
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{
// Fail locally before ownership/recovery or stopping a healthy core.
ValidateRuntime();
@@ -237,7 +258,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_preferredTailnetConfigJson = preferred;
_routeMode = routeMode;
_nodeSlug = nodeSlug;
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null);
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null, tailnetBinding);
}
catch
{
@@ -264,7 +285,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_baseConfigJson = null;
_tailnetFallbackConfigJson = null;
_preferredTailnetConfigJson = null;
_tailnetInterfaceName = null;
_tailnetBinding = null;
_nodeSlug = "";
_boundNetwork = null;
}
@@ -289,7 +310,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
}
private async Task StartCoreAsync(CancellationToken cancellationToken,
Action<CancellationToken>? beginStartupLearning = null)
Action<CancellationToken>? beginStartupLearning = null, TailnetTransport.RouteBinding? tailnetBinding = null)
{
ValidateRuntime();
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
@@ -299,10 +320,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson));
var tailnetAddress = TailnetTransport.Address(_baseConfigJson);
var tailnetInterface = tailnetAddress is null ? null : TailnetTransport.RequireExistingRoute(tailnetAddress);
_tailnetInterfaceName = tailnetInterface;
var proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken);
var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses);
_tailnetBinding = tailnetAddress is null ? null : TailnetTransport.RequireCurrentBinding(tailnetAddress, tailnetBinding, physicalNetwork);
var tailnetInterface = _tailnetBinding?.InterfaceName;
if (_tailnetBinding?.Gateway is not null)
AppPaths.WriteLog(new TransportDiagnostic("tailnet_route", "authorized_port_reached_via_gateway", _nodeSlug).SafeMessage);
_learningEpoch = new CancellationTokenSource();
_learningBudget = new LearningProbeBudget();
_networkLearned.Clear();
@@ -389,7 +412,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
try
{
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken, preservePrivateRoute, tailnetAddress);
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken,
preservePrivateRoute, tailnetAddress, _tailnetBinding);
// Apply 0.2.5 routing first, then wait until Windows has completed
// DAD before applications can use the tunnel's DNS/IPv4 path.
await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true);
@@ -534,7 +558,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1,
Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() });
var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName,
_learningProbePort, _directProbePort, _tailnetInterfaceName);
_learningProbePort, _directProbePort, _tailnetBinding?.InterfaceName);
await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token);
_networkLearned.Applied();
}