2
0

IpBasedAccessValidationMiddleware.cs 3.0 KB

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