LanFilteringMiddleware.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  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 LAN host IP based on application configuration.
  11. /// </summary>
  12. public class LanFilteringMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. /// <summary>
  16. /// Initializes a new instance of the <see cref="LanFilteringMiddleware"/> class.
  17. /// </summary>
  18. /// <param name="next">The next delegate in the pipeline.</param>
  19. public LanFilteringMiddleware(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. var currentHost = httpContext.Request.Host.ToString();
  33. var hosts = serverConfigurationManager
  34. .Configuration
  35. .LocalNetworkAddresses
  36. .Select(NormalizeConfiguredLocalAddress)
  37. .ToList();
  38. if (hosts.Count == 0)
  39. {
  40. await _next(httpContext).ConfigureAwait(false);
  41. return;
  42. }
  43. currentHost ??= string.Empty;
  44. if (networkManager.IsInPrivateAddressSpace(currentHost))
  45. {
  46. hosts.Add("localhost");
  47. hosts.Add("127.0.0.1");
  48. if (hosts.All(i => currentHost.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1))
  49. {
  50. return;
  51. }
  52. }
  53. await _next(httpContext).ConfigureAwait(false);
  54. }
  55. private static string NormalizeConfiguredLocalAddress(string address)
  56. {
  57. var add = address.AsSpan().Trim('/');
  58. int index = add.IndexOf('/');
  59. if (index != -1)
  60. {
  61. add = add.Slice(index + 1);
  62. }
  63. return add.TrimStart('/').ToString();
  64. }
  65. }
  66. }