mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the public host validation and redirect handler that protect the outbound HTTP downloads
This commit is contained in:
1 parent
e139a7bb00
commit
9541b0ab98
5 files changed
+448
No files matched your search
@@ -0,0 +1,12 @@
|
||||
namespace Lumina.Infrastructure.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Names of the named HTTP clients registered by the infrastructure layer.
|
||||
/// </summary>
|
||||
internal static class NamedHttpClients
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the HTTP client used to download remote artwork, whose redirects are followed only to public hosts.
|
||||
/// </summary>
|
||||
internal const string ARTWORK_DOWNLOAD = "artwork-download";
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class PublicHostRedirectHandler : DelegatingHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The maximum number of redirects that are followed before the request is considered to be looping.
|
||||
/// </summary>
|
||||
private const int MAXIMUM_REDIRECT_COUNT = 5;
|
||||
|
||||
/// <summary>
|
||||
/// Sends the request, validating that its host is public, and following its redirects only to public HTTPS hosts.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The final response of the request.</returns>
|
||||
protected override async Task<HttpResponseMessage> 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<HttpRequestMessage> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Creates the request used to follow a redirect to <paramref name="requestUri"/>, carrying over the method and the headers of
|
||||
/// <paramref name="request"/>. It is meant for the bodyless GET downloads this handler is registered for.
|
||||
/// </summary>
|
||||
/// <param name="request">The request that is being redirected.</param>
|
||||
/// <param name="requestUri">The URI of the redirect target.</param>
|
||||
/// <returns>The request used to follow the redirect.</returns>
|
||||
private static HttpRequestMessage CloneRequest(HttpRequestMessage request, Uri requestUri)
|
||||
{
|
||||
HttpRequestMessage redirectRequest = new(request.Method, requestUri)
|
||||
{
|
||||
Version = request.Version,
|
||||
VersionPolicy = request.VersionPolicy
|
||||
};
|
||||
foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
|
||||
redirectRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
return redirectRequest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether a host is public, so that a request can never be sent to a private, loopback, link local or otherwise internal address.
|
||||
/// </summary>
|
||||
internal static class PublicHostValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the provided host is a public host.
|
||||
/// </summary>
|
||||
/// <param name="host">The host to check.</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. 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.
|
||||
/// </remarks>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+190
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostRedirectHandler"/> class.
|
||||
/// </summary>
|
||||
[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<HttpRequestException>(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<HttpRequestException>(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<HttpRequestException>(Act);
|
||||
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
|
||||
Assert.Equal(6, innerHandler.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
|
||||
/// </summary>
|
||||
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
|
||||
/// <returns>The created client.</returns>
|
||||
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
|
||||
{
|
||||
PublicHostRedirectHandler handler = new() { InnerHandler = innerHandler };
|
||||
return new HttpClient(handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class StubHttpMessageHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public List<HttpRequestMessage> Requests { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of requests that were sent through the handler.
|
||||
/// </summary>
|
||||
public int CallCount => _callCount;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
|
||||
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
|
||||
{
|
||||
_responseFactory = responseFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the provided request, producing its response through the configured factory.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to send.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>The response produced for the request.</returns>
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
int callIndex = Interlocked.Increment(ref _callCount);
|
||||
Requests.Add(request);
|
||||
return Task.FromResult(_responseFactory(request, callIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Infrastructure.Common.Networking;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="PublicHostValidator"/> class.
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user