diff --git a/src/Admin/Startup.cs b/src/Admin/Startup.cs index e48815169..7b9a87604 100644 --- a/src/Admin/Startup.cs +++ b/src/Admin/Startup.cs @@ -104,10 +104,7 @@ namespace Bit.Admin if(globalSettings.SelfHosted) { app.UsePathBase("/admin"); - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto - }); + app.UseForwardedHeaders(globalSettings); } if(env.IsDevelopment()) diff --git a/src/Api/Startup.cs b/src/Api/Startup.cs index a4aed3427..93f0a187c 100644 --- a/src/Api/Startup.cs +++ b/src/Api/Startup.cs @@ -171,10 +171,7 @@ namespace Bit.Api } else { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto - }); + app.UseForwardedHeaders(globalSettings); } // Add static files to the request pipeline. diff --git a/src/Core/GlobalSettings.cs b/src/Core/GlobalSettings.cs index 6cfb0e4e6..709b9cca1 100644 --- a/src/Core/GlobalSettings.cs +++ b/src/Core/GlobalSettings.cs @@ -5,6 +5,7 @@ namespace Bit.Core public class GlobalSettings { public bool SelfHosted { get; set; } + public virtual string KnownProxies { get; set; } public virtual string SiteName { get; set; } public virtual string StripeApiKey { get; set; } public virtual string ProjectName { get; set; } diff --git a/src/Core/Utilities/ServiceCollectionExtensions.cs b/src/Core/Utilities/ServiceCollectionExtensions.cs index b697a4c3b..d6a86d4a2 100644 --- a/src/Core/Utilities/ServiceCollectionExtensions.cs +++ b/src/Core/Utilities/ServiceCollectionExtensions.cs @@ -27,6 +27,8 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using IdentityServer4.AccessTokenValidation; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.HttpOverrides; +using System.Linq; namespace Bit.Core.Utilities { @@ -390,5 +392,29 @@ namespace Bit.Core.Utilities await next.Invoke(); }); } + + public static void UseForwardedHeaders(this IApplicationBuilder app, GlobalSettings globalSettings) + { + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + }; + if(!string.IsNullOrWhiteSpace(globalSettings.KnownProxies)) + { + var proxies = globalSettings.KnownProxies.Split(','); + foreach(var proxy in proxies) + { + if(System.Net.IPAddress.TryParse(proxy, out var ip)) + { + options.KnownProxies.Add(ip); + } + } + } + if(options.KnownProxies.Count > 1) + { + options.ForwardLimit = null; + } + app.UseForwardedHeaders(options); + } } } diff --git a/src/Identity/Startup.cs b/src/Identity/Startup.cs index 650c6d965..d649c5286 100644 --- a/src/Identity/Startup.cs +++ b/src/Identity/Startup.cs @@ -97,6 +97,10 @@ namespace Bit.Identity // Rate limiting app.UseMiddleware(); } + else + { + app.UseForwardedHeaders(globalSettings); + } // Add current context app.UseMiddleware();