Exemple #1
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 #2
0
    public void Contains_WithValidIp_ReturnsTrue(string cidr, string ip)
    {
        var cidrNotation = CIDRNotation.Parse(cidr);
        var ipAddress    = IPAddress.Parse(ip);

        Assert.True(cidrNotation.Contains(ipAddress));
    }
Exemple #3
0
    public void Contains_WithOutOfRangeIp_ReturnsFalse(string cidr, string ip)
    {
        var cidrNotation = CIDRNotation.Parse(cidr);
        var ipAddress    = IPAddress.Parse(ip);

        Assert.False(cidrNotation.Contains(ipAddress));
    }
Exemple #4
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!");
            });
        }
Exemple #5
0
    public void Parse_WithValidString_ParsesCorrectObject(
        string value, string expectedIpAddress, int expectedMaskBits)
    {
        var cidrNotation = CIDRNotation.Parse(value);

        Assert.Equal(expectedIpAddress, cidrNotation.Address.ToString());
        Assert.Equal(expectedMaskBits, cidrNotation.MaskBits);
        Assert.Equal(value, cidrNotation.ToString());
    }
Exemple #6
0
        static void Main(string[] args)
        {
            var proxyServer = new FirewallTcpProxyServer(IPEndPoint.Parse("192.168.31.1:80"));

            proxyServer.OnConnected += (session) =>
            {
                Console.WriteLine("New Connection");
            };
            proxyServer.Start().Wait();

            Console.WriteLine($"Port: {proxyServer.ListenPort}");

            proxyServer.UpdateAllowCidrList(new CIDRNotation[] { CIDRNotation.Parse("0.0.0.0/0") });

            Console.Read();
        }
Exemple #7
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!");
            });
        }
Exemple #8
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 #9
0
 public void Parse_WithNull_ThrowsException()
 {
     Assert.Throws <ArgumentException>(() => CIDRNotation.Parse(null));
 }
Exemple #10
0
 public void Parse_WithInvalidString_ThrowsException(string value)
 {
     Assert.Throws <ArgumentException>(() => CIDRNotation.Parse(value));
 }
Exemple #11
0
 public void Parse_WithWhitespaceString_ThrowsException()
 {
     Assert.Throws <ArgumentException>(() => CIDRNotation.Parse(" "));
 }
Exemple #12
0
        private async Task <IEnumerable <CIDRNotation> > GetServiceAllowRuleCIDRNotation(int serviceId, int?serviceForwardTargetId = null)
        {
            var rules = await ListServiceAllowRule(serviceId, serviceForwardTargetId);

            List <CIDRNotation> result = new List <CIDRNotation>();

            foreach (var rule in rules)
            {
                try
                {
                    switch (rule.Type)
                    {
                    case ServiceAllowRuleTypes.CIDR:
                        result.Add(CIDRNotation.Parse(rule.Cidr));
                        break;

                    case ServiceAllowRuleTypes.CIDR_GROUP:
                        result.AddRange((await _cidrGroupService.GetCidrGroup(rule.CidrGroupId.Value)).CidrList.Select(CIDRNotation.Parse));
                        break;

                    case ServiceAllowRuleTypes.USER:
                        var ip = await _userService.GetUserIP(rule.UserId.Value);

                        if (ip == null)
                        {
                            break;
                        }
                        result.Add(CIDRNotation.Parse(ip.ToString() + "/" + (ip.GetAddressBytes().Length * 8)));

                        if (IPAddress.IsLoopback(ip))
                        {
                            result.Add(CIDRNotation.Parse("::1/128"));
                            result.Add(CIDRNotation.Parse("127.0.0.1/32"));
                        }
                        else
                        {
                            if (ip.IsIPv4MappedToIPv6)
                            {
                                var ipv4 = ip.MapToIPv4();
                                result.Add(CIDRNotation.Parse(ipv4.ToString() + "/" + (ipv4.GetAddressBytes().Length * 8)));
                            }
                        }
                        break;

                    case ServiceAllowRuleTypes.USER_GROUP:
                        var userlist = await _userGroupService.ListUserGroupMember(rule.UserGroupId.Value);

                        foreach (var user in userlist)
                        {
                            var userIp = await _userService.GetUserIP(user.Id);

                            if (userIp == null)
                            {
                                continue;
                            }
                            result.Add(CIDRNotation.Parse(userIp.ToString() + "/" + (userIp.GetAddressBytes().Length * 8)));

                            if (IPAddress.IsLoopback(userIp))
                            {
                                result.Add(CIDRNotation.Parse("::1/128"));
                                result.Add(CIDRNotation.Parse("127.0.0.1/32"));
                            }
                            else
                            {
                                if (userIp.IsIPv4MappedToIPv6)
                                {
                                    var ipv4 = userIp.MapToIPv4();
                                    result.Add(CIDRNotation.Parse(ipv4.ToString() + "/" + (ipv4.GetAddressBytes().Length * 8)));
                                }
                            }
                        }
                        break;
                    }
                }
                catch { }
            }

            return(result);
        }