Files
ucvl-zonghengjia-open-source/windows/PlatformBootstrapTransport.cs

92 lines
4.3 KiB
C#

using System.Net;
using System.Net.Sockets;
namespace UCVL.VPNPlus;
// Only management API TCP establishment may use this bootstrap address.
// SocketsHttpHandler still performs ordinary hostname/SNI certificate checks;
// there is no HTTP retry, URL rewrite, system DNS change or TLS bypass.
internal static class PlatformBootstrapTransport
{
internal const string Host = "vpn.example.invalid";
private static readonly IPAddress BootstrapAddress = IPAddress.Parse("192.0.2.1");
internal static SocketsHttpHandler CreateHandler() => new()
{
UseProxy = false,
UseCookies = false,
AllowAutoRedirect = false,
ConnectTimeout = TimeSpan.FromSeconds(10),
AutomaticDecompression = DecompressionMethods.All,
ConnectCallback = (context, token) =>
{
ValidateRequest(context.InitialRequestMessage.RequestUri!, context.InitialRequestMessage.Headers.Host);
return ConnectAsync(context.DnsEndPoint, token,
(name, ct) => Dns.GetHostAddressesAsync(name, ct), OpenSocketAsync);
},
};
internal static void ValidateRequest(Uri uri, string? hostHeader = null)
{
if (!uri.IsAbsoluteUri || uri.Scheme != Uri.UriSchemeHttps || uri.Port != 443 ||
!string.Equals(uri.Host, Host, StringComparison.OrdinalIgnoreCase) || uri.UserInfo.Length != 0 ||
(hostHeader is not null && !string.Equals(hostHeader, Host, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(hostHeader, Host + ":443", StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("管理接口地址不在允许范围内。");
}
internal static bool IsFakeAddress(IPAddress address)
{
if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4();
var bytes = address.GetAddressBytes();
return bytes.Length == 4 && bytes[0] == 198 && bytes[1] is 18 or 19;
}
// The injectable operations are solely for offline self-tests. Production
// supplies OS DNS and the owned socket implementation above; no HTTP data
// has been sent when a failed TCP attempt switches to the bootstrap IP.
internal static async ValueTask<Stream> ConnectAsync(DnsEndPoint endpoint, CancellationToken token,
Func<string, CancellationToken, Task<IPAddress[]>> resolve,
Func<IPAddress, int, CancellationToken, ValueTask<Stream>> connect)
{
if (!string.Equals(endpoint.Host, Host, StringComparison.OrdinalIgnoreCase) || endpoint.Port != 443)
throw new InvalidOperationException("管理接口连接目标不在允许范围内。");
using var total = CancellationTokenSource.CreateLinkedTokenSource(token);
total.CancelAfter(TimeSpan.FromSeconds(10));
using var normal = CancellationTokenSource.CreateLinkedTokenSource(total.Token);
normal.CancelAfter(TimeSpan.FromSeconds(4));
total.Token.ThrowIfCancellationRequested();
try
{
var addresses = await resolve(Host, normal.Token).ConfigureAwait(false);
normal.Token.ThrowIfCancellationRequested();
if (!addresses.Any(IsFakeAddress))
{
foreach (var address in addresses.Distinct())
{
try { return await connect(address, 443, normal.Token).ConfigureAwait(false); }
catch (SocketException) { normal.Token.ThrowIfCancellationRequested(); }
}
}
}
catch (SocketException) { /* OS DNS/TCP failure, before TLS or HTTP. */ }
catch (OperationCanceledException) when (!total.IsCancellationRequested)
{ /* Only the normal-path sub-deadline may select the bootstrap. */ }
total.Token.ThrowIfCancellationRequested();
return await connect(BootstrapAddress, 443, total.Token).ConfigureAwait(false);
}
private static async ValueTask<Stream> OpenSocketAsync(IPAddress address, int port, CancellationToken token)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.NoDelay = true;
await socket.ConnectAsync(new IPEndPoint(address, port), token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
return new NetworkStream(socket, ownsSocket: true);
}
catch { socket.Dispose(); throw; }
}
}