IpBasedAccessValidationMiddleware.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Linq;
  2. using System.Threading.Tasks;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Configuration;
  6. using Microsoft.AspNetCore.Http;
  7. namespace Jellyfin.Server.Middleware
  8. {
  9. /// <summary>
  10. /// Validates the IP of requests coming from local networks wrt. remote access.
  11. /// </summary>
  12. public class IpBasedAccessValidationMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="IpBasedAccessValidationMiddleware"/> class.
  17. /// </summary>
  18. /// <param name="next">The next delegate in the pipeline.</param>
  19. public IpBasedAccessValidationMiddleware(RequestDelegate next)
  20. {
  21. _next = next;
  22. }
  23. /// <summary>
  24. /// Executes the middleware action.
  25. /// </summary>
  26. /// <param name="httpContext">The current HTTP context.</param>
  27. /// <param name="networkManager">The network manager.</param>
  28. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  29. /// <returns>The async task.</returns>
  30. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
  31. {
  32. if (httpContext.Request.IsLocal())
  33. {
  34. await _next(httpContext).ConfigureAwait(false);
  35. return;
  36. }
  37. var remoteIp = httpContext.Request.RemoteIp();
  38. if (serverConfigurationManager.Configuration.EnableRemoteAccess)
  39. {
  40. var addressFilter = serverConfigurationManager.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  41. if (addressFilter.Length > 0 && !networkManager.IsInLocalNetwork(remoteIp))
  42. {
  43. if (serverConfigurationManager.Configuration.IsRemoteIPFilterBlacklist)
  44. {
  45. if (networkManager.IsAddressInSubnets(remoteIp, addressFilter))
  46. {
  47. return;
  48. }
  49. }
  50. else
  51. {
  52. if (!networkManager.IsAddressInSubnets(remoteIp, addressFilter))
  53. {
  54. return;
  55. }
  56. }
  57. }
  58. }
  59. else
  60. {
  61. if (!networkManager.IsInLocalNetwork(remoteIp))
  62. {
  63. return;
  64. }
  65. }
  66. await _next(httpContext).ConfigureAwait(false);
  67. }
  68. }
  69. }