Building a Basic IP BlackList Filter in ASP.NET

I have always loved the freedom of the Internet, but there is one true fact about life my mother embedded in me about the time I got my driver's license. She told me she was not worried about me, she knew I would be responsible (she knew I did not want to pay for any damages to other cars and my own :>) but she was scared to death about the other drivers on the road. Well the Internet is much the same way and we have to be careful of the bad citizens out there trying to hurt us.

These bad Internet citizens come in many forms, most commonly it would be a SPAMMER or a hacker. One of the ways we can combat them is to block their IP addresses from accessing our site and our resources. For those of you who are not aware every computer or node on the Internet has a public IP or Internet Protocol address. It is in the form of four octets separated by a period, XXX.XXX.XXX.XXX.

The numbers in each octet can range from 1 to 255. Each octet represents what we call a class, so a C class is the 255 IP addresses represented by the last octet. A B Class represents the 65025 IP addresses of the last two octets. Many blacklist will block entire classes of IP addresses when they notice consistent malicious traffic from a large number of IPs in their range. Typically this is represented with an *; XXX.XXX.XXX.*.

Enough of that, the rules you employ to build a blacklist can vary. You need to be aware that many IP addresses exhibit bad behavior for a limited time as the owner resolves the problem or maybe the IP address gets reassigned to another computer on the Internet. For this reason many blacklist set a blackout window for an IP in the list. While this is sort of arbitrary the rule should be consistent for all the IPs you decide to block.

The criteria used to add IP addresses to your list should also be pretty concrete and you should be fairly certain an IP is bad before you add it. Remember sometimes you will get false positives to your rules and you need to have some sort of tolerance for these situations, but there will always be collateral damage. For example the stronger the SPAM blacklist have gotten the more clients I have that seem to have IP addresses on these blacklist.

There are really two ways to add IP addresses to a blacklist for in ASP.NET. Rick Strahl does a really good write up on how to block IP addresses programatically in IIS. But often ASP.NET developers do not have the proper permissions to perform this task with our sites. Whether it is the network security policies or our site is hosted on a shared server at a large impersonal hosting company, the rights you have as developer may be very limited. For this reason I opt to build a custom httpModule.

This is the code from the first pass at the technique. From here I plan on implementing a much more robust system that I can probably share among all the sites hosted on my server. This example assumes we just have a local file that contains all the bad IP addresses we have found. So this is an ultra simplistic approach for now. Imagine applying the overall technique against a dynamic list that may be built by another thread of logic in our Web site or background application.

Example IP Blocking httpModule

Imports Microsoft.VisualBasic

Public Class IpBlocker
    Implements IHttpModule

    Private _Context As HttpApplication

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
        RemoveHandler _Context.AuthorizeRequest, AddressOf CheckRequest
    End Sub

    Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
        _Context = context

        AddHandler context.AuthorizeRequest, AddressOf CheckRequest

    End Sub

    Sub CheckRequest(ByVal sender As Object, ByVal e As EventArgs)

        If CheckIP() Then
            HttpContext.Current.RewritePath('~/Banned.htm')
        End If

    End Sub

    Public Function CheckIP() As Boolean

        Dim fileContents As String = My.Computer.FileSystem.ReadAllText( _
        HttpContext.Current.Server.MapPath('') & '\badIps.dat')

        'OK I am going to cheat for demonstration purposes and add an extra check against a querystring parameter for an IP address
        Dim sIP As String = String.Empty

        If Not IsNothing(HttpContext.Current.Request.QueryString('IPcheck')) Then
            sIP = HttpContext.Current.Request.QueryString('IPcheck').ToString
        Else
            sIP = HttpContext.Current.Request.UserHostAddress.ToString
        End If

        If fileContents.Contains(sIP)  Then
            Return True
        Else
            Return False
        End If

    End Function

End Class

The first thing you will notice is the registration of an event handler on the AuthorizeRequest event. This event handler calls a CheckIP function to see if the requesting IP address is on the blacklist or not. If it is then the actual path is rewritten to a stock page we have to let the visitor know they are coming from a banned IP address. This technique will block all unwanted access from anything on the site, well except this message page of course.

The CheckIP function reads the text from the file containing the bad IP addresses and compares the incoming IP address to the list. For this example and demo purposes I set things up so I could pass an IP address in the QueryString. This would not be the way it will be implemented in real list, just for testing purposes.

Of course in the Dispose method we Remove the event handler to help out the garbage collector.

This is a real simple example of how to leverage an httpModule to block unwanted visitors by IP address. The technique shows how to redirect the bad visitor to a page to let them know they are banned using the RewritePath method. All other requests proceed normally.

kick it on DotNetKicks.com

Share This Article With Your Friends!