mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Hardens outbound host validation against SSRF
- resolves host names and validates every address, with a connect callback that pins the checked address - applies the guard to every outbound HTTP client, with distinct rejection and resolution failures and warning logs - scopes the MusicBrainz private base URL permission to the configured host and blocks link local and cloud metadata endpoints - keeps provider redirects bounded and strips credentials and hop-by-hop headers on cross-origin redirects - adds unit, security, and end-to-end coverage, and updates the manual
This commit is contained in:
1 parent
ecdb39cc6a
commit
24af00579c
28 files changed
+2977
-162
No files matched your search
+3
-7
@@ -8,7 +8,6 @@ using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection;
|
||||
@@ -46,12 +45,9 @@ internal static class CoverArtArchiveServices
|
||||
// is fetched only once during a run.
|
||||
services.TryAddSingleton<CoverArtArchiveResponseCache>();
|
||||
|
||||
// Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client
|
||||
// follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically
|
||||
// would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF
|
||||
// control here; the base URL being a constant does not make the redirect target trustworthy.
|
||||
services.AddHttpClient<CoverArtArchiveHttpClient>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
// The client follows the redirects of the Cover Art Archive itself, confined to the hosts the archive may delegate its responses to, so it opts out of the
|
||||
// host redirect handling. The host still validates and pins the address of every request and confirms that it is public.
|
||||
services.AddHttpClient<CoverArtArchiveHttpClient>();
|
||||
|
||||
// Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations.
|
||||
services.AddKeyedTransient<IArtworkProvider, CoverArtArchiveAlbumArtworkProvider>(pluginId);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.CoverArtArchive.Core.Settings;
|
||||
@@ -118,8 +119,8 @@ internal sealed class CoverArtArchiveHttpClient
|
||||
|
||||
Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl);
|
||||
|
||||
// The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the
|
||||
// automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to.
|
||||
// The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the automatic
|
||||
// redirects disabled, opts out of the host redirect handling, and confines the following to the hosts the Cover Art Archive may delegate its responses to.
|
||||
for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
|
||||
{
|
||||
HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false);
|
||||
@@ -164,10 +165,14 @@ internal sealed class CoverArtArchiveHttpClient
|
||||
{
|
||||
HttpRequestMessage request = new(HttpMethod.Get, requestUri);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
// The client follows the redirects itself, confined to the hosts the Cover Art Archive may delegate its responses to, so it opts out of the
|
||||
// host redirect handling and receives the redirect response instead.
|
||||
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
|
||||
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException) when (!isLastAttempt)
|
||||
catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception))
|
||||
{
|
||||
// A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried.
|
||||
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
@@ -238,6 +243,22 @@ internal sealed class CoverArtArchiveHttpClient
|
||||
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> when the exception chain contains a policy rejection, otherwise <see langword="false"/>.</returns>
|
||||
/// <remarks>
|
||||
/// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception.
|
||||
/// </remarks>
|
||||
private static bool IsPolicyRejection(HttpRequestException exception)
|
||||
{
|
||||
for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException)
|
||||
if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
|
||||
/// </summary>
|
||||
|
||||
+3
-4
@@ -8,7 +8,6 @@ using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
|
||||
@@ -45,9 +44,9 @@ internal static class MusicBrainzServices
|
||||
// The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once.
|
||||
services.TryAddSingleton<MusicBrainzResponseCache>();
|
||||
|
||||
// Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror.
|
||||
services.AddHttpClient<MusicBrainzHttpClient>()
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
// The host creates the primary handler of the outbound clients, which disables automatic redirects and connects only to addresses validated to be
|
||||
// public. The client follows the redirects itself, confined to the configured host, so the configurable base URL cannot be used to reach an internal address.
|
||||
services.AddHttpClient<MusicBrainzHttpClient>();
|
||||
|
||||
// Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
|
||||
// A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Contracts.Common.Http;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
|
||||
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.MusicBrainz.Core.Settings;
|
||||
@@ -34,6 +35,9 @@ internal sealed class MusicBrainzHttpClient
|
||||
// Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
|
||||
private const int MAXIMUM_ATTEMPT_COUNT = 4;
|
||||
|
||||
// The redirects of a self hosted mirror are followed explicitly, so the host redirect policy can be opted out of and only the same host can be reached.
|
||||
private const int MAXIMUM_REDIRECT_COUNT = 5;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
|
||||
/// </summary>
|
||||
@@ -222,15 +226,55 @@ internal sealed class MusicBrainzHttpClient
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured
|
||||
/// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport
|
||||
/// exceptions are retried, preferring the delay requested by the web service when it is provided.
|
||||
/// Sends a GET request to the MusicBrainz web service, following its redirects explicitly so they are confined to the configured host, and throttled to
|
||||
/// respect the configured minimum request interval unless the configured base URL is not the real MusicBrainz service, in which case no rate limit is imposed.
|
||||
/// Transient failures, rate limiting and transport exceptions are retried, preferring the delay requested by the web service when it is provided.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
|
||||
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
/// <exception cref="HttpRequestException">The service redirected the request to a host or a scheme that is not allowed, or too many times.</exception>
|
||||
private async Task<HttpResponseMessage> SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
Uri baseUri = new(settings.BaseUrl, UriKind.Absolute);
|
||||
// The permission to reach a private address is scoped to the host of the configured base URL, so a mirror cannot redirect the request to another
|
||||
// private host, and the link local and cloud metadata ranges stay blocked even when the permission is granted.
|
||||
string? allowedPrivateHost = settings.DoesAllowPrivateBaseUrl ? baseUri.IdnHost : null;
|
||||
Uri requestUri = BuildRequestUri(settings.BaseUrl, relativeUrl);
|
||||
|
||||
for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++)
|
||||
{
|
||||
HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, allowedPrivateHost, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!IsRedirect(response.StatusCode) || response.Headers.Location is null)
|
||||
return response;
|
||||
|
||||
Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location);
|
||||
// The response of a redirect is not returned, so it must be disposed here to release its connection.
|
||||
response.Dispose();
|
||||
|
||||
// A redirect is followed only to the configured host, and never from HTTPS to HTTP, so a compromised or misbehaving mirror cannot redirect the
|
||||
// request to any other host, while a plain HTTP self hosted mirror keeps working across the redirects of its reverse proxy.
|
||||
if (redirectUri is null || !IsAllowedRedirect(baseUri, redirectUri))
|
||||
throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request to a disallowed target.");
|
||||
|
||||
requestUri = redirectUri;
|
||||
}
|
||||
|
||||
throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request too many times.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a GET request to the provided URI, throttled to respect the configured minimum request interval. Transient failures and rate limiting are retried,
|
||||
/// so a single hiccup does not surface as a failed resolution.
|
||||
/// </summary>
|
||||
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
|
||||
/// <param name="requestUri">The absolute URI of the resource to request.</param>
|
||||
/// <param name="allowedPrivateHost">The host that may be private, or <see langword="null"/> when no such permission was granted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The HTTP response message for the request.</returns>
|
||||
private async Task<HttpResponseMessage> SendWithRetriesAsync(MusicBrainzSettingsDto settings, Uri requestUri, string? allowedPrivateHost, CancellationToken cancellationToken)
|
||||
{
|
||||
EnsureRequestHeaders(settings);
|
||||
// The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted
|
||||
@@ -248,12 +292,17 @@ internal sealed class MusicBrainzHttpClient
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl));
|
||||
HttpRequestMessage request = new(HttpMethod.Get, requestUri);
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
// The client follows the redirects itself, confined to the configured host, so it opts out of the host redirect handling.
|
||||
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
|
||||
if (allowedPrivateHost is not null && string.Equals(requestUri.IdnHost, allowedPrivateHost, StringComparison.OrdinalIgnoreCase))
|
||||
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, allowedPrivateHost);
|
||||
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException) when (!isLastAttempt)
|
||||
catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception))
|
||||
{
|
||||
// A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried.
|
||||
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
@@ -271,6 +320,42 @@ internal sealed class MusicBrainzHttpClient
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided status code is a redirect.
|
||||
/// </summary>
|
||||
/// <param name="statusCode">The status code to check.</param>
|
||||
/// <returns><see langword="true"/> when the status code is a redirect, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsRedirect(HttpStatusCode statusCode)
|
||||
{
|
||||
return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther
|
||||
or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the location of a redirect against the URI of the request it was returned for.
|
||||
/// </summary>
|
||||
/// <param name="requestUri">The URI of the request the redirect was returned for.</param>
|
||||
/// <param name="location">The location of the redirect.</param>
|
||||
/// <returns>The absolute URI of the redirect, or <see langword="null"/> when it could not be resolved.</returns>
|
||||
private static Uri? ResolveRedirect(Uri requestUri, Uri location)
|
||||
{
|
||||
if (location.IsAbsoluteUri)
|
||||
return location;
|
||||
return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided redirect target may be followed: it must stay on the host of the configured base address, and it may not downgrade an HTTPS base address to plain HTTP.
|
||||
/// </summary>
|
||||
/// <param name="baseUri">The URI of the configured base address.</param>
|
||||
/// <param name="redirectUri">The URI of the redirect target.</param>
|
||||
/// <returns><see langword="true"/> when the redirect may be followed, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsAllowedRedirect(Uri baseUri, Uri redirectUri)
|
||||
{
|
||||
bool isSchemeAllowed = redirectUri.Scheme == Uri.UriSchemeHttps || (baseUri.Scheme == Uri.UriSchemeHttp && redirectUri.Scheme == Uri.UriSchemeHttp);
|
||||
return isSchemeAllowed && string.Equals(baseUri.IdnHost, redirectUri.IdnHost, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
|
||||
/// </summary>
|
||||
@@ -293,6 +378,22 @@ internal sealed class MusicBrainzHttpClient
|
||||
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> when the exception chain contains a policy rejection, otherwise <see langword="false"/>.</returns>
|
||||
/// <remarks>
|
||||
/// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception.
|
||||
/// </remarks>
|
||||
private static bool IsPolicyRejection(HttpRequestException exception)
|
||||
{
|
||||
for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException)
|
||||
if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
|
||||
/// </summary>
|
||||
|
||||
@@ -130,17 +130,20 @@ internal sealed class MusicBrainzSettingsProvider
|
||||
/// <param name="host">The host of the persisted base URL.</param>
|
||||
/// <returns><see langword="true"/> when the host is public, otherwise <see langword="false"/>.</returns>
|
||||
/// <remarks>
|
||||
/// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here.
|
||||
/// A private or local host is accepted when <see cref="MusicBrainzSettingsDto.DoesAllowPrivateBaseUrl"/> is enabled, which supports self hosted
|
||||
/// mirrors on a local network.
|
||||
/// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. The host that runs the plugin
|
||||
/// resolves it again when the request is sent, and rejects it when any address it resolves to is private, unless <see cref="MusicBrainzSettingsDto.DoesAllowPrivateBaseUrl"/>
|
||||
/// enabled the private base address. That permission applies only to the host of the configured base address, so a redirect to another private host is still
|
||||
/// rejected, and the link local and cloud metadata ranges are always rejected. Enabling the setting supports self hosted mirrors on a local network.
|
||||
/// The address classification matches the one the host applies to a resolved address, so the settings layer does not accept a base URL that the host later
|
||||
/// rejects.
|
||||
/// </remarks>
|
||||
private static bool IsPublicHost(string host)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(host))
|
||||
return false;
|
||||
|
||||
// Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept.
|
||||
string normalizedHost = host.Trim('[', ']');
|
||||
// Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept, and a fully qualified name may end with a dot.
|
||||
string normalizedHost = host.Trim('[', ']').TrimEnd('.');
|
||||
if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
@@ -153,32 +156,64 @@ internal sealed class MusicBrainzSettingsProvider
|
||||
if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
|
||||
return false;
|
||||
|
||||
if (address.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
byte[] octets = address.GetAddressBytes();
|
||||
// The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF.
|
||||
return octets[0] switch
|
||||
{
|
||||
0 => false,
|
||||
10 => false,
|
||||
100 when octets[1] is >= 64 and <= 127 => false,
|
||||
127 => false,
|
||||
169 when octets[1] == 254 => false,
|
||||
172 when octets[1] is >= 16 and <= 31 => false,
|
||||
192 when octets[1] == 168 => false,
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
// IPv4-mapped IPv6 addresses were converted to IPv4 above, so the family split never sees one.
|
||||
return address.AddressFamily == AddressFamily.InterNetwork
|
||||
? IsPublicIPv4Address(address)
|
||||
: IsPublicIPv6Address(address);
|
||||
}
|
||||
|
||||
if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal)
|
||||
/// <summary>
|
||||
/// Determines whether the provided IPv4 address is public.
|
||||
/// </summary>
|
||||
/// <param name="address">The IPv4 address to check.</param>
|
||||
/// <returns><see langword="true"/> when the address is public, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsPublicIPv4Address(IPAddress address)
|
||||
{
|
||||
byte[] octets = address.GetAddressBytes();
|
||||
return octets[0] switch
|
||||
{
|
||||
0 => false, // The 0.0.0.0/8 "this network" range.
|
||||
10 => false, // The 10.0.0.0/8 private range.
|
||||
100 when octets[1] is >= 64 and <= 127 => false, // The 100.64.0.0/10 carrier grade NAT range.
|
||||
127 => false, // The 127.0.0.0/8 loopback range.
|
||||
169 when octets[1] == 254 => false, // The 169.254.0.0/16 link local range, including the cloud metadata endpoints.
|
||||
172 when octets[1] is >= 16 and <= 31 => false, // The 172.16.0.0/12 private range.
|
||||
192 when octets[1] == 168 => false, // The 192.168.0.0/16 private range.
|
||||
192 when octets[1] == 0 && (octets[2] is 0 or 2) => false, // The IETF protocol assignments and TEST-NET-1 documentation ranges.
|
||||
198 when octets[1] is >= 18 and <= 19 => false, // The 198.18.0.0/15 benchmarking range.
|
||||
198 when octets[1] == 51 && octets[2] == 100 => false, // The TEST-NET-2 documentation range.
|
||||
203 when octets[1] == 0 && octets[2] == 113 => false, // The TEST-NET-3 documentation range.
|
||||
>= 224 => false, // The multicast range, the reserved range, and the broadcast address.
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided IPv6 address is public.
|
||||
/// </summary>
|
||||
/// <param name="address">The IPv6 address to check.</param>
|
||||
/// <returns><see langword="true"/> when the address is public, otherwise <see langword="false"/>.</returns>
|
||||
private static bool IsPublicIPv6Address(IPAddress address)
|
||||
{
|
||||
if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast || address.IsIPv6Teredo || address.IsIPv6UniqueLocal)
|
||||
return false;
|
||||
|
||||
byte[] addressBytes = address.GetAddressBytes();
|
||||
// The fc00::/7 unique local range is rejected, matching the private IPv4 ranges.
|
||||
if ((addressBytes[0] & 0xFE) == 0xFC)
|
||||
// The ::/96 IPv4 compatible and ::ffff:0:0/96 IPv4 translated ranges embed an IPv4 address, and the mapped form is already converted to IPv4, so no
|
||||
// address with an all zero first eighty bits is public.
|
||||
if (addressBytes[0] == 0 && addressBytes[1] == 0 && addressBytes[2] == 0 && addressBytes[3] == 0 &&
|
||||
addressBytes[4] == 0 && addressBytes[5] == 0 && addressBytes[6] == 0 && addressBytes[7] == 0 &&
|
||||
addressBytes[8] == 0 && addressBytes[9] == 0)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
return addressBytes[0] switch
|
||||
{
|
||||
0x00 when addressBytes[1] == 0x64 && addressBytes[2] == 0xFF && addressBytes[3] == 0x9B => false, // The 64:ff9b::/96 NAT64 prefix, which can map to private IPv4 addresses.
|
||||
0x01 when addressBytes[1] == 0x00 && addressBytes[2] == 0x00 && addressBytes[3] == 0x00 => false, // The 100::/64 discard only range.
|
||||
0x20 when addressBytes[1] == 0x01 && addressBytes[2] == 0x0D && addressBytes[3] == 0xB8 => false, // The 2001:db8::/32 documentation range.
|
||||
0x20 when addressBytes[1] == 0x02 => false, // The 2002::/16 6to4 range.
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user