| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- using System.Net;
- using System.Net.Sockets;
- using Microsoft.Extensions.Configuration;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- public sealed record MdpApiPullTarget(string Host, int Port, string[] Addresses, bool AllowHttp = false)
- {
- public bool AllowsAddress(IPAddress value)
- {
- var address = Normalize(value);
- return IsUsable(address) && Addresses.Any(text => IPAddress.TryParse(text, out var approved)
- && Normalize(approved).Equals(address));
- }
- private static IPAddress Normalize(IPAddress value) => value.IsIPv4MappedToIPv6 ? value.MapToIPv4() : value;
- private static bool IsUsable(IPAddress address)
- {
- if (IPAddress.IsLoopback(address)) return false;
- var bytes = address.GetAddressBytes();
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- // Never delegate link-local, node-local cloud endpoints, or special network ranges to configuration.
- return bytes[0] is > 0 and < 224 and not 127
- && !(bytes[0] == 169 && bytes[1] == 254)
- && !(bytes[0] == 168 && bytes[1] == 63 && bytes[2] == 129 && bytes[3] == 16)
- && !(bytes[0] == 100 && bytes[1] is >= 64 and <= 127);
- }
- // IPv6 endpoints are limited to direct global unicast and explicitly pinned unique local addresses.
- return address.ScopeId == 0 && (bytes[0] is 0xfc or 0xfd
- || (bytes[0] & 0xe0) == 0x20 && !(bytes[0] == 0x20 && bytes[1] == 0x02)
- && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x00 && bytes[3] == 0x00));
- }
- }
- public sealed class MdpApiPullEgress(IConfiguration configuration)
- {
- internal HttpClient Open(long tenant, long source, Uri uri, bool requireHttps = true)
- {
- var target = Target(tenant, source, uri, requireHttps);
- var handler = new SocketsHttpHandler
- {
- AllowAutoRedirect = false,
- UseCookies = false,
- UseProxy = false,
- AutomaticDecompression = DecompressionMethods.None,
- PooledConnectionLifetime = TimeSpan.Zero,
- ConnectTimeout = TimeSpan.FromSeconds(8),
- ConnectCallback = async (context, token) =>
- {
- var host = uri.IdnHost.Trim('[', ']');
- if (!string.Equals(context.DnsEndPoint.Host.Trim('[', ']'), host, StringComparison.OrdinalIgnoreCase)
- || context.DnsEndPoint.Port != uri.Port)
- throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
- var addresses = IPAddress.TryParse(host, out var exact) ? [exact] : await Dns.GetHostAddressesAsync(host, token);
- if (addresses.Length == 0 || addresses.Any(address => !target.AllowsAddress(address)))
- throw new MdpApiPullException("PULL_ADDRESS_FORBIDDEN");
- foreach (var address in addresses)
- {
- var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
- try
- {
- await socket.ConnectAsync(address, context.DnsEndPoint.Port, token);
- return new NetworkStream(socket, ownsSocket: true);
- }
- catch (SocketException)
- {
- socket.Dispose();
- }
- catch
- {
- socket.Dispose();
- throw;
- }
- }
- throw new HttpRequestException("Approved API destination was unreachable.");
- }
- };
- return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(25) };
- }
- internal MdpApiPullTarget Target(long tenant, long source, Uri uri, bool requireHttps = true)
- {
- if (!uri.IsAbsoluteUri || uri.UserInfo.Length != 0 || uri.Fragment.Length != 0
- || uri.Scheme != "https" && (requireHttps || uri.Scheme != "http"))
- throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
- var host = uri.IdnHost.Trim('[', ']').TrimEnd('.');
- if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase))
- throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
- var section = configuration.GetSection($"MdpApiPull:Targets:{tenant}:{source}");
- var target = section.GetChildren().Select(rule =>
- new MdpApiPullTarget(rule["Host"] ?? "", rule.GetValue<int>("Port"),
- rule.GetSection("Addresses").Get<string[]>() ?? [], rule.GetValue<bool>("AllowHttp")))
- .SingleOrDefault(rule => string.Equals(rule.Host.TrimEnd('.'), host, StringComparison.OrdinalIgnoreCase)
- && rule.Port == uri.Port && (uri.Scheme == "https" || rule.AllowHttp));
- if (target is null || target.Addresses.Length == 0 || IPAddress.TryParse(host, out var ip) && !target.AllowsAddress(ip))
- throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
- return target;
- }
- internal static bool SameOrigin(Uri first, Uri second) =>
- first.Scheme == second.Scheme && first.Port == second.Port &&
- string.Equals(first.IdnHost, second.IdnHost, StringComparison.OrdinalIgnoreCase);
- }
- internal sealed class MdpApiPullException(string code, TimeSpan? retry = null) : Exception(code)
- {
- internal string Code { get; } = code;
- internal TimeSpan? Retry { get; } = retry;
- }
|