April 24, 2008

ASP code to block multiple ranges of IP’s from your site

It wasn’t long before I needed to expand upon banning a few IP’s. I needed to be able to ban whole networks so here’s the Q&D solution:-

First create a text file called ipsec.txt and enter some IP’s you wish to ban, to ban a network just leave off the end of the IP class number, for example:-

10.20.30.40
10.50

In the above example the first is a specific IP that you wish to ban, the second will ban all IP addresses that start 10.50 (for example 10.50.20.1 and 10.50.100.1 will both be banned). Enter as many as you like, one per line.

Now create or edit your global.asa file and add the following code to the session_onstart sub procedure:

sub session_onstart
  remote_ip = request.servervariables("Remote_Addr")
  ipsec     = server.mappath("/ipsec.txt")
  ips       = getFileContents(ipsec)
  ips       = split(ips,vbcrlf)
 
  for each ip in ips
    if len(trim(ip)) > 0 then
      ip_parts        = split(ip,".")
      remote_ip_parts = split(remote_ip,".")
      found = true
      for x = 0 to ubound(ip_parts)
        if ip_parts(x) <> remote_ip_parts(x) then
          found = false
          exit for
        end if
      next
      If found then
        response.redirect "/redir.html?ip=" & remote_ip
      end if
    end if
  Next
end sub

Replace /redir.html with a file or location you want to redirect banned ip’s too.

As this code runs in the session_onstart section of the global.asa it will be run only once for each visitor, this means that during the session they could return and this code would be bypased. If that is a concern modify the code to be a common function and place it strategically, perhaps in a common file called throughout the website.

Post a Comment