Friday, 26 August 2011

Block IP addresses from your website

Recently, one of my readers asked me how to block certain IP addresses from accessing his ASP.NET website. It was a good question that could be answered in multiple correct ways. My answer was a plug ‘n play HttpModule that could be reused in any ASP.NET application. When an IP address is blocked it stops the response and sends a “403 Forbidden” header.

Even though it’s almost impossible to block someone from accessing your website, this is a simple way to make it much harder to do. For the regular web users this is probably enough to keep them out.
#Region "Using"

Imports System.Web
Imports System.Configuration
Imports System.Collections.Specialized

#End Region

''' <summary>
''' Block the response to certain IP addresses
''' </summary>
Public Class IpBlockingModule
    Implements IHttpModule

#Region "IHttpModule Members"

    Private Sub IHttpModule_Dispose() Implements IHttpModule.Dispose
        ' Nothing to dispose;
    End Sub

    Private Sub IHttpModule_Init(ByVal context As HttpApplication) Implements IHttpModule.Init
        AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
    End Sub

#End Region

    ''' <summary>
    ''' Checks the requesting IP address in the collection
    ''' and block the response if it's on the list.
    ''' </summary>
    Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim ip As String = HttpContext.Current.Request.UserHostAddress
        If _IpAdresses.Contains(ip) Then
            HttpContext.Current.Response.StatusCode = 403
        End If
    End Sub

    Private Shared _IpAdresses As StringCollection = FillBlockedIps()

    ''' <summary>
    ''' Retrieves the IP addresses from the web.config
    ''' and adds them to a StringCollection.
    ''' </summary>
    ''' <returns>A StringCollection of IP addresses.</returns>
    Private Shared Function FillBlockedIps() As StringCollection
        Dim col As New StringCollection()
        Dim raw As String = ConfigurationManager.AppSettings.[Get]("blockip")
        raw = raw.Replace(",", ";")
        raw = raw.Replace(" ", ";")

        For Each ip As String In raw.Split(";"c)

        Return col
    End Function

End Class


Download the IpBlockingModule.cs below and add it to the App_Code folder. Then add the following line to the <system.web> section of the web.config.
< httpModules >
  < add type = " IpBlockingModule " name = " IpBlockingModule " />
</ httpModules >
Then add the IP addresses you want to block, separated by commas, to the appSettings in web.config.
< appSettings >
  < add key = " blockip " value = ", " />
</ appSettings >