IpBasedAccessValidationMiddleware.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Net;
  2. using System.Threading.Tasks;
  3. using Jellyfin.Networking.Configuration;
  4. using MediaBrowser.Common.Extensions;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Configuration;
  7. using Microsoft.AspNetCore.Http;
  8. using NetworkCollection;
  9. namespace Jellyfin.Server.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. /// <summary>
  18. /// Initializes a new instance of the <see cref="IpBasedAccessValidationMiddleware"/> class.
  19. /// </summary>
  20. /// <param name="next">The next delegate in the pipeline.</param>
  21. public IpBasedAccessValidationMiddleware(RequestDelegate next)
  22. {
  23. _next = next;
  24. }
  25. /// <summary>
  26. /// Executes the middleware action.
  27. /// </summary>
  28. /// <param name="httpContext">The current HTTP context.</param>
  29. /// <param name="networkManager">The network manager.</param>
  30. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  31. /// <returns>The async task.</returns>
  32. public async Task Invoke(HttpContext httpContext, INetworkManager networkManager, IServerConfigurationManager serverConfigurationManager)
  33. {
  34. if (httpContext.IsLocal())
  35. {
  36. // Running locally.
  37. await _next(httpContext).ConfigureAwait(false);
  38. return;
  39. }
  40. var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
  41. if (serverConfigurationManager.GetNetworkConfiguration().EnableRemoteAccess)
  42. {
  43. // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
  44. // If left blank, all remote addresses will be allowed.
  45. NetCollection remoteAddressFilter = networkManager.RemoteAddressFilter;
  46. if (remoteAddressFilter.Count > 0 && !networkManager.IsInLocalNetwork(remoteIp))
  47. {
  48. // remoteAddressFilter is a whitelist or blacklist.
  49. bool isListed = remoteAddressFilter.Contains(remoteIp);
  50. if (!serverConfigurationManager.GetNetworkConfiguration().IsRemoteIPFilterBlacklist)
  51. {
  52. // Black list, so flip over.
  53. isListed = !isListed;
  54. }
  55. if (!isListed)
  56. {
  57. // If your name isn't on the list, you arn't coming in.
  58. return;
  59. }
  60. }
  61. }
  62. else if (!networkManager.IsInLocalNetwork(remoteIp))
  63. {
  64. // Remote not enabled. So everyone should be LAN.
  65. return;
  66. }
  67. await _next(httpContext).ConfigureAwait(false);
  68. }
  69. }
  70. }