Use verified company gateway for authorized Tailscale nodes
This commit is contained in:
+76
-15
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user