Files
jellyfin-jellyfin-1/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs

64 lines
2.2 KiB
C#
Raw Normal View History

using System.Net;
2020-09-03 11:32:22 +02:00
using System.Threading.Tasks;
using System.Web;
2020-09-03 11:32:22 +02:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
2020-09-03 11:32:22 +02:00
2023-01-31 12:18:10 +01:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Validates the IP of requests coming from local networks wrt. remote access.
/// </summary>
2023-02-17 19:27:36 +01:00
public class IPBasedAccessValidationMiddleware
2020-09-03 11:32:22 +02:00
{
2023-01-31 12:18:10 +01:00
private readonly RequestDelegate _next;
private readonly ILogger<IPBasedAccessValidationMiddleware> _logger;
2023-01-31 12:18:10 +01:00
2020-09-03 11:32:22 +02:00
/// <summary>
2023-02-17 19:27:36 +01:00
/// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class.
2020-09-03 11:32:22 +02:00
/// </summary>
2023-01-31 12:18:10 +01:00
/// <param name="next">The next delegate in the pipeline.</param>
/// <param name="logger">The logger to log to.</param>
public IPBasedAccessValidationMiddleware(RequestDelegate next, ILogger<IPBasedAccessValidationMiddleware> logger)
2020-09-03 11:32:22 +02:00
{
2023-01-31 12:18:10 +01:00
_next = next;
_logger = logger;
2023-01-31 12:18:10 +01:00
}
2020-09-03 11:32:22 +02:00
2023-01-31 12:18:10 +01:00
/// <summary>
/// Executes the middleware action.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <param name="networkManager">The network manager.</param>
/// <returns>The async task.</returns>
public async Task Invoke(HttpContext httpContext, INetworkManager networkManager)
{
if (httpContext.IsLocal())
2020-09-03 11:32:22 +02:00
{
// Accessing from the same machine as the server.
2023-01-31 12:18:10 +01:00
await _next(httpContext).ConfigureAwait(false);
return;
2020-09-03 11:32:22 +02:00
}
var remoteIP = httpContext.GetNormalizedRemoteIP();
2020-09-03 11:32:22 +02:00
var result = networkManager.ShouldAllowServerAccess(remoteIP);
if (result != RemoteAccessPolicyResult.Allow)
2023-01-31 12:18:10 +01:00
{
// No access from network, respond with 503 instead of 200.
_logger.LogWarning(
"Blocking request to {Path} by {RemoteIP} due to IP filtering rule, reason: {Reason}",
// url-encode to block log injection
HttpUtility.UrlEncode(httpContext.Request.Path),
remoteIP,
result);
httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
2023-01-31 12:18:10 +01:00
return;
2020-09-03 11:32:22 +02:00
}
2023-01-31 12:18:10 +01:00
await _next(httpContext).ConfigureAwait(false);
2020-09-03 11:32:22 +02:00
}
}