Exemple #1
0
    public async Task Firewall_With_Single_VIP_And_Request_With_Invalid_IP_Returns_AccessDenied()
    {
        var isSuccess          = false;
        var allowedIpAddress   = IPAddress.Parse("12.34.56.78");
        var allowedIpAddresses = new List <IPAddress> {
            allowedIpAddress
        };
        var firewall = new FirewallMiddleware(
            async(innerCtx) =>
        {
            isSuccess = true;
            await innerCtx.Response.WriteAsync("Success!");
        },
            FirewallRulesEngine
            .DenyAllAccess()
            .ExceptFromIPAddresses(allowedIpAddresses),
            logger: null);

        var httpContext = new DefaultHttpContext();

        httpContext.Connection.RemoteIpAddress = IPAddress.Parse("10.99.99.99");

        await firewall.Invoke(httpContext);

        Assert.Equal(StatusCodes.Status403Forbidden, httpContext.Response.StatusCode);
        Assert.False(isSuccess);
    }
Exemple #2
0
    public async Task Firewall_With_Single_CIDR_And_Request_With_Invalid_IP_Returns_AccessDenied()
    {
        var isSuccess        = false;
        var allowedIpAddress = IPAddress.Parse("174.74.115.210");
        var cidrNotations    = new List <CIDRNotation> {
            CIDRNotation.Parse("174.74.115.192/28")
        };
        var firewall = new FirewallMiddleware(
            async(innerCtx) =>
        {
            isSuccess = true;
            await innerCtx.Response.WriteAsync("Success!");
        },
            FirewallRulesEngine
            .DenyAllAccess()
            .ExceptFromIPAddressRanges(cidrNotations),
            logger: null);

        var httpContext = new DefaultHttpContext();

        httpContext.Connection.RemoteIpAddress = allowedIpAddress;

        await firewall.Invoke(httpContext);

        Assert.Equal(StatusCodes.Status403Forbidden, httpContext.Response.StatusCode);
        Assert.False(isSuccess);
    }
Exemple #3
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseFirewall(
                FirewallRulesEngine
                .DenyAllAccess()
                .ExceptFromLocalhost()
                .ExceptFromIPAddresses(new List <IPAddress>()
            {
                IPAddress.Parse("127.0.0.1")
            }));
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStatusCodePages();
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseFirewall(FirewallRulesEngine.DenyAllAccess().ExceptFromIPAddresses(new List <IPAddress> {
                IPAddress.Parse("1.1.1.1")
            }).ExceptFromLocalhost());

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #5
0
        public void Configure(IApplicationBuilder app)
        {
            var allowedIPs =
                new List <IPAddress>
            {
                IPAddress.Parse("10.20.30.40"),
                IPAddress.Parse("1.2.3.4"),
                IPAddress.Parse("5.6.7.8")
            };

            var allowedCIDRs =
                new List <CIDRNotation>
            {
                CIDRNotation.Parse("110.40.88.12/28"),
                CIDRNotation.Parse("88.77.99.11/8")
            };

            app.UseFirewall(
                FirewallRulesEngine
                .DenyAllAccess()
                .ExceptFromIPAddressRanges(allowedCIDRs)
                .ExceptFromIPAddresses(allowedIPs));

            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();

            app.UseSwaggerUI(c => c.SwaggerEndpoint(url: "/swagger/v1/swagger.json", name: "TransactionStore.API V1"));

            app.UseFirewall(
                FirewallRulesEngine
                .DenyAllAccess()
                .ExceptFromLocalhost()
                .ExceptFromIPAddresses(AllowedIPs.authorizedIPs));

            app.UseStaticFiles();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Exemple #7
0
 private void InitFirewallRules()
 {
     _firewallRule = FirewallRulesEngine.DenyAllAccess();
     if (_allow_cidrs != null && _allow_cidrs.Any())
     {
         _firewallRule = _firewallRule.ExceptFromIPAddressRanges(_allow_cidrs.ToList());
     }
 }
Exemple #8
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseForwardedHeaders(
                new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor,
                ForwardLimit     = 1
            }
                );

            // Register Firewall after error handling and forwarded headers,
            // but before other middleware:
            var allowedIPAddresses =
                new List <IPAddress>
            {
                IPAddress.Parse("10.20.30.40"),
                IPAddress.Parse("1.2.3.4"),
                IPAddress.Parse("5.6.7.8")
            };

            var allowedIPAddressRanges =
                new List <CIDRNotation>
            {
                CIDRNotation.Parse("110.40.88.12/28"),
                CIDRNotation.Parse("88.77.99.11/8")
            };

            app.UseFirewall(
                FirewallRulesEngine
                .DenyAllAccess()
                .ExceptFromCountries(new [] { CountryCode.FK })
                .ExceptFromIPAddressRanges(allowedIPAddressRanges)
                .ExceptFromIPAddresses(allowedIPAddresses)
                .ExceptFromCloudflare()
                .ExceptFromLocalhost(),
                accessDeniedDelegate:
                ctx =>
            {
                ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
                return(ctx.Response.WriteAsync("Forbidden"));
            });

            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
        private void SetupFirewall(IApplicationBuilder app)
        {
            var options = new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor,
                ForwardLimit     = 1,
            };

            options.KnownNetworks.Clear();
            options.KnownProxies.Clear();
            app.UseForwardedHeaders(options);

            var rules = FirewallRulesEngine
                        .DenyAllAccess()
                        .ExceptFromCloudflare();

            app.UseFirewall(rules, ctx =>
            {
                ctx.Response.Redirect("https://quickclip.tk");
                return(Task.CompletedTask);
            });
        }
Exemple #10
0
    public async Task Firewall_With_Multiple_IPs_And_CIDRs_And_Request_With_Invalid_IP_Returns_AccessDenied(string ip)
    {
        var isSuccess          = false;
        var allowedIpAddress   = IPAddress.Parse(ip);
        var allowedIpAddresses = new List <IPAddress>
        {
            IPAddress.Parse("1.2.3.4"),
            IPAddress.Parse("10.20.30.40"),
            IPAddress.Parse("50.6.70.8")
        };
        var cidrNotations = new List <CIDRNotation>
        {
            CIDRNotation.Parse("2803:f800::/32"),
            CIDRNotation.Parse("2c0f:f248::/32"),
            CIDRNotation.Parse("103.21.244.0/22"),
            CIDRNotation.Parse("141.101.64.0/18"),
            CIDRNotation.Parse("172.64.0.0/13")
        };
        var firewall = new FirewallMiddleware(
            async(innerCtx) =>
        {
            isSuccess = true;
            await innerCtx.Response.WriteAsync("Success!");
        },
            FirewallRulesEngine
            .DenyAllAccess()
            .ExceptFromIPAddresses(allowedIpAddresses)
            .ExceptFromIPAddressRanges(cidrNotations),
            logger: null);

        var httpContext = new DefaultHttpContext();

        httpContext.Connection.RemoteIpAddress = allowedIpAddress;

        await firewall.Invoke(httpContext);

        Assert.Equal(StatusCodes.Status403Forbidden, httpContext.Response.StatusCode);
        Assert.False(isSuccess);
    }
Exemple #11
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            app.UseMiddleware <ActivityTracingMiddleware>();
            app.UseMiddleware <ResponseStatusCodeHealthCheckMiddleware>();

            if (env.IsProduction())
            {
                app.UseFirewall(FirewallRulesEngine
                                .DenyAllAccess()
                                .ExceptFromCloudflare()
                                .ExceptFromLocalhost());
            }
            else if (env.IsDevelopment())
            {
                app.UseFirewall(FirewallRulesEngine
                                .DenyAllAccess()
                                .ExceptFromLocalhost());
            }

            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            if (BlogConfiguration.ServerSideHttpsRedirection)
            {
                app.UseHttpsRedirection();
            }
            if (BlogConfiguration.ClientSideHttpsRedirection)
            {
                app.UseMiddleware <ClientSideRedirectionMiddleware>();
            }
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseResponseCaching();
            app.UseMiddleware <ResponseHeaderMiddleware>();

            if (BlogConfiguration.UsePrometheusScrapingEndpoint)
            {
                app.UseOpenTelemetryPrometheusScrapingEndpoint();
            }

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/health");
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.MapFallbackToPage("/Error", "/Error");
                endpoints.MapFallbackToPage("/NotFound", "/NotFound");
            });

            ServerCertificateSelector.Instance.SetLoggerFactory(loggerFactory);
            if (env.IsDevelopment() && BlogConfiguration.PersistenceLayer == PersistenceLayerType.MySql)
            {
                using var scope = serviceProvider.CreateScope();
                var connectionFactory = scope.ServiceProvider.GetRequiredService <MySqlConnectionFactory>();
                connectionFactory.EnsureTablesExists();

                try
                {
                    foreach (var row in File.ReadAllLines("dev_data.sql"))
                    {
                        if (!string.IsNullOrEmpty(row))
                        {
                            connectionFactory.Connection.Execute(row);
                        }
                    }
                }
                catch
                {
                    /* seed only once */
                }
            }
        }