Code Monkey home page Code Monkey logo

znetcs.aspnetcore.ipfiltering's Introduction

ZNetCS.AspNetCore.IPFiltering

NuGet Build

A middleware that allows whitelist or blacklist incomming requests based on IP address. It can be configured using single IP address or ranges. It supports single IP, IP range IPv4 and IPv6. There is also possible to ignore specific paths from IP filtering.

Installing

Install using the ZNetCS.AspNetCore.IPFiltering NuGet package

PM> Install-Package ZNetCS.AspNetCore.IPFiltering

Usage

When you install the package, it should be added to your .csproj. Alternatively, you can add it directly by adding:

<ItemGroup>
    <PackageReference Include="ZNetCS.AspNetCore.IPFiltering" Version="6.0.1" />
</ItemGroup>

.NET 6

In order to use the IP filtering middleware, you must configure the services in the Program.cs file.

// Add services to the container.
builder.Services.AddIPFiltering(builder.Configuration.GetSection("IPFiltering"));

or

// Add services to the container.
builder.Services.AddIPFiltering(
        opts =>
        {
            opts.DefaultBlockLevel = DefaultBlockLevel.All;
            opts.HttpStatusCode = HttpStatusCode.NotFound;
            opts.Blacklist = new List<string> { "192.168.0.100-192.168.1.200" };
            opts.Whitelist = new List<string> { "192.168.0.10-192.168.10.20", "fe80::/10" };
            opts.IgnoredPaths = new List<string> { "get:/ignoreget", "*:/ignore" };
            opts.PathOptions = new List<PathOptions> { ... };
        });

then

// Configure IP filtering
app.UseIPFiltering();

.NET 5 and Below

In order to use the IP filtering middleware, you must configure the services in the ConfigureServices and Configure call of Startup. Make sure middleware is added just after logging to prevent any other middleware to run, so block is most effective:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIPFiltering(this.Configuration.GetSection("IPFiltering"));
}

or

public void ConfigureServices(IServiceCollection services)
{
    services.AddIPFiltering(
        opts =>
        {
            opts.DefaultBlockLevel = DefaultBlockLevel.All;
            opts.HttpStatusCode = HttpStatusCode.NotFound;
            opts.Blacklist = new List<string> { "192.168.0.100-192.168.1.200" };
            opts.Whitelist = new List<string> { "192.168.0.10-192.168.10.20", "fe80::/10" };
            opts.IgnoredPaths = new List<string> { "get:/ignoreget", "*:/ignore" };
            opts.PathOptions = new List<PathOptions> { ... };
        });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{   
    app.UseIPFiltering();

    // other middleware e.g. MVC etc
}

File

Middleware can be configured in appsettings.json file. By adding following section and use following ConfigureServices method:

{
    "IPFiltering": {
        "DefaultBlockLevel": "All",
        "HttpStatusCode": 404,
        "Whitelist": [ "192.168.0.10-192.168.10.20", "fe80::/10" ],
        "Blacklist": [ "192.168.0.100-192.168.1.200"],
        "IgnoredPaths": [ "GET:/ignoreget", "*:/ignore" ],
        "PathOptions": [
            {
                "Paths": [ "GET:/pathget", "*:/path" ],
                "DefaultBlockLevel": "None",
                "HttpStatusCode": 401,
                "Whitelist": [ "192.168.0.100-192.168.1.200" ],
                "Blacklist": [ "192.168.0.10-192.168.10.20", "fe80::/10" ]
            }, 
            {
                "Paths": [ "GET:/path2get", "*:/path2" ],
                "DefaultBlockLevel": "All",
                "HttpStatusCode": 401,
                "Whitelist": [ "192.168.0.10-192.168.10.20", "fe80::/10" ],
                "Blacklist": [ "192.168.0.100-192.168.1.200" ]
          }
        ]
    }
}

Configuration

This middleware can be configured using following configuration options:

  • DefaultBlockLevel defines default action when IP address is not listed. Can be configured to None or All. Default value is All.
  • HttpStatusCode defines status code that is returned to client when IP address is forbidden. Default value is 404 (Not Found).
  • Whitelist defines list of IP address ranges that are allowed for request.
  • Blacklist defines list of IP address ranges that are forbidden for request.
  • IgnoredPaths defines list of paths with HTTP Verb to be ignored from IP filtering. * means all HTTP Verbs for given path will be ignored. Format {VERB}:{PATH} (no space after :). This configuration is case insensitive.
  • PathOptions defines list of paths with HTTP Verb to be processed with custom rules. * means all HTTP Verbs for given path will be ignored. Format {VERB}:{PATH} (no space after :). This configuration is case insensitive.

IP Address Ranges

Whitelist and Blacklist can be defined as single IP address or IP address range. For parsing middleware is using extenal package: https://github.com/jsakamoto/ipaddressrange. Ranges can be defined in following formats:

  • 192.168.0.0/255.255.255.0
  • 192.168.0.10-192.168.10.20
  • fe80::/10

znetcs.aspnetcore.ipfiltering's People

Contributors

msmolka avatar v1rusyra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

znetcs.aspnetcore.ipfiltering's Issues

IP Filter

Any objections to me submitting a pull request that adds IP filtering as a MVC filter? This would bring in a new dependencies of Microsoft.AspNetCore.Mvc.Abstractions.

My thoughts here would be an attribute that could be applied either at the class or method level. Something like [IPFilter(Policy = "MyPolicy")] This would allow for either white listing, black listing at a more granular level than at the middle ware level.

Thanks!

Ignoring paths separately for each Black-listed Ip

I have two Ips which I've black-listed:

"Blacklist": [ "127.0.0.1", "192.168.0.1" ]

I want to ignore paths separately for each of them:

i.e. for "127.0.0.1"
"IgnoredPaths": [ "POST:/*" ]

and for "192.168.0.1"
"IgnoredPaths": [ "GET:/*" ]

Is there any way to do that?

Fatal error

@msmolka I got a fatal error as follows:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at AspNetCoreRateLimit.Bits.GetBitMask(Int32 sizeOfBuff, Int32 bitLen)
   at AspNetCoreRateLimit.IpAddressRange..ctor(String ipRangeString)
   at AspNetCoreRateLimit.IpAddressUtil.ContainsIp(List`1 ipRules, String clientIp)
   at AspNetCoreRateLimit.IpParser.ContainsIp(List`1 ipRules, String clientIp)
   at AspNetCoreRateLimit.IpRateLimitProcessor.IsWhitelisted(ClientRequestIdentity requestIdentity)
   at AspNetCoreRateLimit.RateLimitMiddleware`1.Invoke(HttpContext context)
   at ZNetCS.AspNetCore.IPFiltering.IPFilteringMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

DI resolution error during startup.

netcoreapp2.0 where I followed the setup, but gets:

Cannot resolve scoped service 'Microsoft.Extensions.Options.IOptionsSnapshot`1[ZNetCS.AspNetCore.IPFiltering.IPFilteringOptions]' from root provider.

Uses:

Just parse IP ranges once

This library appears to parse the allowed IP ranges on every call to IPAddressChecker.IsAllowed:

var whitelist = optWhitelist.Select(IPAddressRange.Parse).ToList();
var blacklist = optBlacklist.Select(IPAddressRange.Parse).ToList();

However, the config will very rarely change between requests, so it'd be more efficient to only parse these once and reuse the same objects across requests.

Ip Proxy Reverse

Thanks for your contribution, I have a configuration where the web api receives a request only from a reverse proxy, but in the console it shows me the IP of the final client and I want to validate the IP of the proxy in this case, is it possible?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.