diff --git a/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs new file mode 100644 index 00000000..926e983d --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs @@ -0,0 +1,12 @@ +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Names of the named HTTP clients registered by the infrastructure layer. +/// +internal static class NamedHttpClients +{ + /// + /// The name of the HTTP client used to download remote artwork, whose redirects are followed only to public hosts. + /// + internal const string ARTWORK_DOWNLOAD = "artwork-download"; +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs new file mode 100644 index 00000000..a72b0354 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Message handler that validates the host of the initial request, and follows the redirects of the response only to public HTTPS hosts, so that +/// neither the URL emitted by a provider nor a server controlled redirect can make the host issue a request to a private, loopback, link local or +/// otherwise internal address. It is provider agnostic: it protects every download that is routed through the client it is attached to. +/// +internal sealed class PublicHostRedirectHandler : DelegatingHandler +{ + /// + /// The maximum number of redirects that are followed before the request is considered to be looping. + /// + private const int MAXIMUM_REDIRECT_COUNT = 5; + + /// + /// Sends the request, validating that its host is public, and following its redirects only to public HTTPS hosts. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The final response of the request. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + // The sink is provider agnostic, so the initial request is validated too, not only the redirects, so a provider that emits an internal URL + // cannot make the host fetch a private, loopback or link local address before any redirect is even involved. + Uri? initialUri = request.RequestUri; + string initialHost = initialUri is { IsAbsoluteUri: true } ? initialUri.Host : string.Empty; + if (initialUri is not { IsAbsoluteUri: true } || !PublicHostValidator.IsPublicHost(initialHost)) + throw new HttpRequestException($"The request was sent to the disallowed host '{initialHost}'."); + + HttpRequestMessage currentRequest = request; + // The requests created here to follow a redirect are owned by this handler, so they are disposed once the sending is complete. + List redirectRequests = []; + + try + { + for (int redirectCount = 0; ; redirectCount++) + { + Uri requestUri = currentRequest.RequestUri ?? throw new HttpRequestException("The request has no request URI."); + + HttpResponseMessage response = await base.SendAsync(currentRequest, 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(); + + if (redirectCount >= MAXIMUM_REDIRECT_COUNT) + throw new HttpRequestException("The request was redirected too many times."); + + // Only public HTTPS targets are followed, so a redirect can never reach a private, loopback, link local or other internal address, + // nor downgrade the transfer back to an unencrypted one. + if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !PublicHostValidator.IsPublicHost(redirectUri.Host)) + throw new HttpRequestException($"The request was redirected to the disallowed host '{redirectUri?.Host}'."); + + HttpRequestMessage redirectRequest = CloneRequest(currentRequest, redirectUri); + redirectRequests.Add(redirectRequest); + currentRequest = redirectRequest; + } + } + finally + { + foreach (HttpRequestMessage redirectRequest in redirectRequests) + redirectRequest.Dispose(); + } + } + + /// + /// Determines whether the provided status code is a redirect. + /// + /// The status code to check. + /// when the status code is a redirect, otherwise . + private static bool IsRedirect(HttpStatusCode statusCode) + { + return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + } + + /// + /// Resolves the location of a redirect against the URI of the request it was returned for. + /// + /// The URI of the request the redirect was returned for. + /// The location of the redirect. + /// The absolute URI of the redirect, or when it could not be resolved. + private static Uri? ResolveRedirect(Uri requestUri, Uri location) + { + if (location.IsAbsoluteUri) + return location; + return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null; + } + + /// + /// Creates the request used to follow a redirect to , carrying over the method and the headers of + /// . It is meant for the bodyless GET downloads this handler is registered for. + /// + /// The request that is being redirected. + /// The URI of the redirect target. + /// The request used to follow the redirect. + private static HttpRequestMessage CloneRequest(HttpRequestMessage request, Uri requestUri) + { + HttpRequestMessage redirectRequest = new(request.Method, requestUri) + { + Version = request.Version, + VersionPolicy = request.VersionPolicy + }; + foreach (KeyValuePair> header in request.Headers) + redirectRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); + return redirectRequest; + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs new file mode 100644 index 00000000..4f0ce059 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Net; +using System.Net.Sockets; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Determines whether a host is public, so that a request can never be sent to a private, loopback, link local or otherwise internal address. +/// +internal static class PublicHostValidator +{ + /// + /// Determines whether the provided host is a public host. + /// + /// The host to check. + /// when the host is public, otherwise . + /// + /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. An IP literal is accepted + /// only when it is a public address, so the unspecified, private, loopback, link local and carrier grade NAT ranges are all rejected. + /// + public 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('[', ']'); + if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) + return false; + + if (!IPAddress.TryParse(normalizedHost, out IPAddress? address)) + return true; + + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + return false; + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + byte[] octets = address.GetAddressBytes(); + 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 + }; + } + + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + return false; + + byte[] addressBytes = address.GetAddressBytes(); + // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. + if ((addressBytes[0] & 0xFE) == 0xFC) + return false; + + return true; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs new file mode 100644 index 00000000..97aa0d77 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs @@ -0,0 +1,190 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Networking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostRedirectHandlerTests +{ + [Fact] + public async Task SendAsync_WhenTheInitialRequestHostIsPublic_ShouldSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); + using HttpClient client = CreateClient(innerHandler); + + // Act + HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, innerHandler.CallCount); + } + + [Theory] + [InlineData("http://127.0.0.1/cover.jpg")] // the IPv4 loopback address + [InlineData("http://localhost/cover.jpg")] // the loopback host name + [InlineData("http://[::1]/cover.jpg")] // the IPv6 loopback address + [InlineData("http://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("http://10.0.0.5/cover.jpg")] // a private class A address + [InlineData("http://172.16.0.1/cover.jpg")] // a private class B address + [InlineData("http://192.168.1.10/cover.jpg")] // a private class C address + public async Task SendAsync_WhenTheInitialRequestHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url) + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync(url); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheInitialRequestRedirectsToAPublicHttpsHost_ShouldFollowIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/download/mbid-1/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + HttpResponseMessage response = await client.GetAsync("https://coverartarchive.org/release/1"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(2, innerHandler.CallCount); + Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host); + } + + [Theory] + [InlineData("http://archive.org/index.json")] // a downgrade of a trusted host to plain HTTP + [InlineData("https://127.0.0.1/index.json")] // the IPv4 loopback address + [InlineData("https://localhost/index.json")] // the loopback host name + [InlineData("https://169.254.169.254/latest/meta-data/")] // the link local cloud metadata endpoint + [InlineData("https://10.0.0.5/index.json")] // a private class A address + [InlineData("https://192.168.1.10/index.json")] // a private class C address + public async Task SendAsync_WhenTheInitialRequestRedirectsToADisallowedTarget_ShouldThrow(string location) + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRequestIsRedirectedTooManyTimes_ShouldThrow() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/loop/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + await Assert.ThrowsAsync(Act); + // The initial request plus the maximum number of followed redirects are sent before the loop is detected. + Assert.Equal(6, innerHandler.CallCount); + } + + /// + /// Creates an whose requests are sent through the handler under test, wrapping the provided inner handler. + /// + /// The handler that answers the requests that reach the network. + /// The created client. + private static HttpClient CreateClient(HttpMessageHandler innerHandler) + { + PublicHostRedirectHandler handler = new() { InnerHandler = innerHandler }; + return new HttpClient(handler); + } + + /// + /// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. + /// + [ExcludeFromCodeCoverage] + private sealed class StubHttpMessageHandler : HttpMessageHandler + { + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public StubHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the provided request, producing its response through the configured factory. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + return Task.FromResult(_responseFactory(request, callIndex)); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs new file mode 100644 index 00000000..0d2e3097 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Networking; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostValidatorTests +{ + [Theory] + [InlineData("coverartarchive.org")] // a public host name + [InlineData("example.com")] // a public host name + [InlineData("8.8.8.8")] // a public IPv4 address + [InlineData("1.1.1.1")] // a public IPv4 address + [InlineData("172.15.0.1")] // the address just below the private class B range + [InlineData("172.32.0.1")] // the address just above the private class B range + [InlineData("2606:4700:4700::1111")] // a public IPv6 address + public void IsPublicHost_WhenTheHostIsPublic_ShouldReturnTrue(string host) + { + // Act + bool result = PublicHostValidator.IsPublicHost(host); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("")] // an empty host + [InlineData(" ")] // only white space + [InlineData("localhost")] // the loopback host name + [InlineData("LOCALHOST")] // the loopback host name, upper cased + [InlineData("127.0.0.1")] // the IPv4 loopback address + [InlineData("::1")] // the IPv6 loopback address + [InlineData("[::1]")] // the IPv6 loopback address, bracketed like a URI host + [InlineData("0.0.0.0")] // the unspecified IPv4 address + [InlineData("[::]")] // the unspecified IPv6 address + [InlineData("169.254.169.254")] // the link local cloud metadata endpoint + [InlineData("10.0.0.5")] // a private class A address + [InlineData("172.16.0.1")] // the lower bound of the private class B range + [InlineData("172.31.255.255")] // the upper bound of the private class B range + [InlineData("192.168.1.10")] // a private class C address + [InlineData("100.64.0.1")] // the lower bound of the carrier grade NAT range + [InlineData("100.127.255.255")] // the upper bound of the carrier grade NAT range + [InlineData("fc00::1")] // the IPv6 unique local range + [InlineData("fe80::1")] // the IPv6 link local range + public void IsPublicHost_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host) + { + // Act + bool result = PublicHostValidator.IsPublicHost(host); + + // Assert + Assert.False(result); + } +}