181 lines
9.7 KiB
C#
181 lines
9.7 KiB
C#
using System.Globalization;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Net.Security;
|
|
using System.Security.Authentication;
|
|
using System.Text.Json;
|
|
using System.Text;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal static class ProxyProbe
|
|
{
|
|
private const int SocksPort = 10808;
|
|
|
|
internal sealed record PathComparison(bool? DirectTls, bool? ProxyTls)
|
|
{
|
|
internal bool ShouldProxy => DirectTls == false && ProxyTls == true;
|
|
}
|
|
|
|
internal static async Task<PathComparison> CompareTlsAsync(LearningObservation observation,
|
|
int directPort, int proxyPort, CancellationToken token)
|
|
{
|
|
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return new(null, null);
|
|
var destination = await ResolvePublicAsync(observation, proxyPort, token);
|
|
if (destination is null) return new(null, null); // Resolver/node failure is not direct-path failure.
|
|
var direct = await TlsAtAsync(observation.Target, destination, directPort, 4, token);
|
|
if (direct) return new(true, null); // Do not send business TLS over the proxy when direct works.
|
|
var proxy = await TlsAtAsync(observation.Target, destination, proxyPort, 6, token);
|
|
return new(false, proxy);
|
|
}
|
|
|
|
internal static async Task<bool?> ProbeTlsAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token, int resolverProxyPort = 0)
|
|
{
|
|
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return null;
|
|
var destination = await ResolvePublicAsync(observation, resolverProxyPort > 0 ? resolverProxyPort : forcedProxyPort, token);
|
|
return destination is not null && await TlsAtAsync(observation.Target, destination, forcedProxyPort, 6, token);
|
|
}
|
|
|
|
private static async Task<IPAddress?> ResolvePublicAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
try
|
|
{
|
|
IPAddress? destination;
|
|
if (observation.TargetType == "ip") destination = IPAddress.Parse(observation.Target);
|
|
else
|
|
{
|
|
// Resolve through the already authorized node, not local poisoned DNS.
|
|
// Pin the returned public IP into SOCKS CONNECT; TLS still verifies the
|
|
// original hostname. No arbitrary HTTP URL, redirect or request replay.
|
|
using var http = new HttpClient(new SocketsHttpHandler { UseProxy = true,
|
|
Proxy = new WebProxy($"socks5://127.0.0.1:{forcedProxyPort}"), AllowAutoRedirect = false,
|
|
ConnectTimeout = TimeSpan.FromSeconds(4) }) { MaxResponseContentBufferSize = 32768 };
|
|
var body = await http.GetStringAsync("https://8.8.8.8/resolve?type=A&name=" + Uri.EscapeDataString(observation.Target), timeout.Token);
|
|
using var dns = JsonDocument.Parse(body);
|
|
if (!dns.RootElement.TryGetProperty("Answer", out var answers)) return null;
|
|
var ips = answers.EnumerateArray().Where(a => a.TryGetProperty("type", out var type) && type.GetInt32() == 1)
|
|
.Select(a => IPAddress.TryParse(a.GetProperty("data").GetString(), out var ip) ? ip : null).ToArray();
|
|
if (ips.Length == 0 || ips.Any(ip => ip is null || !LearningPolicy.PublicIp(ip))) return null;
|
|
destination = ips[0];
|
|
}
|
|
return destination is not null && LearningPolicy.PublicIp(destination) ? destination : null;
|
|
}
|
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
|
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
|
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return null; }
|
|
}
|
|
|
|
internal static async Task<bool> TlsAtAsync(string target, IPAddress destination, int socksPort, int seconds, CancellationToken token)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
|
|
try
|
|
{
|
|
using var client = new TcpClient(AddressFamily.InterNetwork);
|
|
await client.ConnectAsync(IPAddress.Loopback, socksPort, timeout.Token);
|
|
var stream = client.GetStream();
|
|
await stream.WriteAsync(new byte[] { 5, 1, 0 }, timeout.Token);
|
|
var greeting = new byte[2]; await stream.ReadExactlyAsync(greeting, timeout.Token);
|
|
if (greeting[0] != 5 || greeting[1] != 0) return false;
|
|
await stream.WriteAsync(BuildConnectRequest("ip", destination.ToString(), 443), timeout.Token);
|
|
var header = new byte[4]; await stream.ReadExactlyAsync(header, timeout.Token);
|
|
if (header[0] != 5 || header[1] != 0) return false;
|
|
var length = header[3] switch { 1 => 4, 4 => 16, 3 => await ReadDomainLengthAsync(stream, timeout.Token), _ => 0 };
|
|
if (length < 1) return false;
|
|
await stream.ReadExactlyAsync(new byte[length + 2], timeout.Token);
|
|
using var tls = new SslStream(stream, false); // Default platform certificate validation, no bypass.
|
|
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = target }, timeout.Token);
|
|
return tls.IsAuthenticated && tls.IsEncrypted;
|
|
}
|
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
|
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
|
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return false; }
|
|
}
|
|
|
|
internal static async Task<bool?> ProbeAsync(
|
|
LearningObservation observation,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (!string.Equals(observation.Network, "tcp", StringComparison.OrdinalIgnoreCase)) return null;
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
try
|
|
{
|
|
using var client = new TcpClient(AddressFamily.InterNetwork);
|
|
await client.ConnectAsync(IPAddress.Loopback, SocksPort, timeout.Token);
|
|
await using var stream = client.GetStream();
|
|
await stream.WriteAsync(new byte[] { 0x05, 0x01, 0x00 }, timeout.Token);
|
|
var greeting = new byte[2];
|
|
await stream.ReadExactlyAsync(greeting, timeout.Token);
|
|
if (greeting[0] != 0x05 || greeting[1] != 0x00) return false;
|
|
|
|
var request = BuildConnectRequest(observation.TargetType, observation.Target, observation.Port);
|
|
await stream.WriteAsync(request, timeout.Token);
|
|
var header = new byte[4];
|
|
await stream.ReadExactlyAsync(header, timeout.Token);
|
|
if (header[0] != 0x05 || header[1] != 0x00) return false;
|
|
var addressLength = header[3] switch
|
|
{
|
|
0x01 => 4,
|
|
0x04 => 16,
|
|
0x03 => await ReadDomainLengthAsync(stream, timeout.Token),
|
|
_ => 0,
|
|
};
|
|
if (addressLength <= 0) return false;
|
|
var remainder = new byte[addressLength + 2];
|
|
await stream.ReadExactlyAsync(remainder, timeout.Token);
|
|
return true;
|
|
}
|
|
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
|
{
|
|
AppPaths.WriteLog($"vpn-ai 代理复测失败:{observation.Target}:{observation.Port} {exception.GetBaseException().Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
internal static bool SelfTest()
|
|
{
|
|
var domain = BuildConnectRequest("domain", "example.com", 443);
|
|
var ipv4 = BuildConnectRequest("ip", "203.0.113.10", 8443);
|
|
var ipv6 = BuildConnectRequest("ip", "2001:db8::10", 443);
|
|
return domain[3] == 0x03
|
|
&& domain[4] == "example.com".Length
|
|
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
|
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
|
&& ipv6[3] == 0x04 && ipv6.Length == 22;
|
|
}
|
|
|
|
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
|
{
|
|
if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
|
var request = new List<byte> { 0x05, 0x01, 0x00 };
|
|
if (string.Equals(targetType, "ip", StringComparison.OrdinalIgnoreCase)
|
|
&& IPAddress.TryParse(target.Trim('[', ']'), out var address))
|
|
{
|
|
request.Add(address.AddressFamily == AddressFamily.InterNetwork ? (byte)0x01 : (byte)0x04);
|
|
request.AddRange(address.GetAddressBytes());
|
|
}
|
|
else
|
|
{
|
|
var ascii = new IdnMapping().GetAscii(target.Trim().TrimEnd('.'));
|
|
var bytes = Encoding.ASCII.GetBytes(ascii);
|
|
if (bytes.Length is < 1 or > 255) throw new ArgumentException("域名长度无效", nameof(target));
|
|
request.Add(0x03);
|
|
request.Add((byte)bytes.Length);
|
|
request.AddRange(bytes);
|
|
}
|
|
request.Add((byte)(port >> 8));
|
|
request.Add((byte)(port & 0xff));
|
|
return request.ToArray();
|
|
}
|
|
|
|
private static async Task<int> ReadDomainLengthAsync(NetworkStream stream, CancellationToken cancellationToken)
|
|
{
|
|
var length = new byte[1];
|
|
await stream.ReadExactlyAsync(length, cancellationToken);
|
|
return length[0];
|
|
}
|
|
}
|