| | 1 | | using System.Net; |
| | 2 | | using System.Threading.Tasks; |
| | 3 | | using System.Web; |
| | 4 | | using MediaBrowser.Common.Extensions; |
| | 5 | | using MediaBrowser.Common.Net; |
| | 6 | | using Microsoft.AspNetCore.Http; |
| | 7 | | using Microsoft.Extensions.Logging; |
| | 8 | |
|
| | 9 | | namespace Jellyfin.Api.Middleware; |
| | 10 | |
|
| | 11 | | /// <summary> |
| | 12 | | /// Validates the IP of requests coming from local networks wrt. remote access. |
| | 13 | | /// </summary> |
| | 14 | | public class IPBasedAccessValidationMiddleware |
| | 15 | | { |
| | 16 | | private readonly RequestDelegate _next; |
| | 17 | | private readonly ILogger<IPBasedAccessValidationMiddleware> _logger; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Initializes a new instance of the <see cref="IPBasedAccessValidationMiddleware"/> class. |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="next">The next delegate in the pipeline.</param> |
| | 23 | | /// <param name="logger">The logger to log to.</param> |
| | 24 | | public IPBasedAccessValidationMiddleware(RequestDelegate next, ILogger<IPBasedAccessValidationMiddleware> logger) |
| | 25 | | { |
| 21 | 26 | | _next = next; |
| 21 | 27 | | _logger = logger; |
| 21 | 28 | | } |
| | 29 | |
|
| | 30 | | /// <summary> |
| | 31 | | /// Executes the middleware action. |
| | 32 | | /// </summary> |
| | 33 | | /// <param name="httpContext">The current HTTP context.</param> |
| | 34 | | /// <param name="networkManager">The network manager.</param> |
| | 35 | | /// <returns>The async task.</returns> |
| | 36 | | public async Task Invoke(HttpContext httpContext, INetworkManager networkManager) |
| | 37 | | { |
| | 38 | | if (httpContext.IsLocal()) |
| | 39 | | { |
| | 40 | | // Accessing from the same machine as the server. |
| | 41 | | await _next(httpContext).ConfigureAwait(false); |
| | 42 | | return; |
| | 43 | | } |
| | 44 | |
|
| | 45 | | var remoteIP = httpContext.GetNormalizedRemoteIP(); |
| | 46 | |
|
| | 47 | | var result = networkManager.ShouldAllowServerAccess(remoteIP); |
| | 48 | | if (result != RemoteAccessPolicyResult.Allow) |
| | 49 | | { |
| | 50 | | // No access from network, respond with 503 instead of 200. |
| | 51 | | _logger.LogWarning( |
| | 52 | | "Blocking request to {Path} by {RemoteIP} due to IP filtering rule, reason: {Reason}", |
| | 53 | | // url-encode to block log injection |
| | 54 | | HttpUtility.UrlEncode(httpContext.Request.Path), |
| | 55 | | remoteIP, |
| | 56 | | result); |
| | 57 | | httpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; |
| | 58 | | return; |
| | 59 | | } |
| | 60 | |
|
| | 61 | | await _next(httpContext).ConfigureAwait(false); |
| | 62 | | } |
| | 63 | | } |