Amazon.com Widgets All posts tagged 'web services'

WilliaBlog.Net

I dream in code

About the author

Robert Williams is an internet application developer for the Salem Web Network.
E-mail me Send mail
Code Project Associate Logo
Go Daddy Deal of the Week: 30% off your order at GoDaddy.com! Offer expires 11/6/12

Recent comments

Archive

Authors

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.


Use Regex to block specific IP addresses or ranges

Perhaps your feedback page is being hammered by spammers, perhaps your customers are receiving a lot of scam emails from Nigeria, perhaps you are having trouble with stolen credit card information being entered on your site. You have identified some Bad IP addresses you need to block but how do you go about blocking them if you have your site hosted somewhere and you don't have access to the apache or IIS web server directly? I wrote the functions below for just this purpose.

using System;
using System.Data;
using System.Web;
using System.Web.Caching;
using System.Text.RegularExpressions;
namespace BlockIPs
{
public partial class _Default : System.Web.UI.Page
{
public Cache MyCache = HttpContext.Current.Cache;
private static readonly Object lock_object = new Object();
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(isIpBlocked(Request.ServerVariables["Remote_Addr"]));
}
/// <summary>
/// Compares the passed IP address to an external list of Bad IP Addresses
/// </summary>
/// <param name="strIP"></param>
/// <returns>boolean result</returns>
/// <remarks>some of the ips in the block list are like xxx.xxx.0.0 this means all Ips that start xxx.xxx should be blocked...</remarks>
bool isIpBlocked(string strIP)
{
if (!IsValidIP(strIP))
{
return false;
}
String CacheKey = "IPBlocklist";
DataSet DS = (DataSet)MyCache[CacheKey];
if (DS == null)
{
lock(lock_object) //If this file is being hit 1000s times per second only need to make 1 call to the file, the rest will wait until cache is ready.
{
DS = new DataSet();
DS.ReadXml(Server.MapPath("BlockedIPs.xml"));
DS.Tables[0].PrimaryKey = new DataColumn[] {DS.Tables[0].Columns["IP"]};
CacheDependency cd = new CacheDependency(Server.MapPath("BlockedIPs.xml"));
MyCache.Insert(CacheKey, DS, cd, System.DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
}
// first check to see if the ip is in the table
if (DS.Tables[0].Rows.Contains(strIP))
{
return true;
}
// split the incoming ip into octets
string [] octets = strIP.Split('.');
// set up some regex patterns
string pattern1 = String.Format(@"^{0}\.{1}\.{2}\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$", octets[0],octets[1], octets[2]);
string pattern2 = String.Format(@"^{0}\.{1}\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$", octets[0], octets[1]);
string pattern3 = String.Format(@"^{0}\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))\.([0-9]|[1-9][0-9]|1([0-9][0-9])|2([0-4][0-9]|5[0-5]))$", octets[0]);
//create our Regular Expression objects
Regex check1 = new Regex(pattern1); //Checks for xxx.xxx.xxx.0
Regex check2 = new Regex(pattern2); //Checks for xxx.xxx.0.0
Regex check3 = new Regex(pattern3); //Checks for checks for xxx.0.0.0
foreach (DataRow dr in DS.Tables[0].Rows)
{
if(IsValidIP(dr["IP"].ToString()))
{
string[] checkOctets = dr["IP"].ToString().Split('.');
if((checkOctets[1] == "0") && (checkOctets[2] == "0") && (checkOctets[3] == "0"))
{
if(check3.IsMatch(dr["IP"].ToString(),0))
{
return true;
}
}else if ((checkOctets[2] == "0") && (checkOctets[3] == "0"))
{
if (check2.IsMatch(dr["IP"].ToString(), 0))
{
return true;
}
}else if (checkOctets[3] == "0")
{
if (check1.IsMatch(dr["IP"].ToString(), 0))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// method to validate an IP address
/// using regular expressions. The pattern
/// being used will validate an ip address
/// with the range of 1.0.0.0 to 255.255.255.255
/// </summary>
/// <param name="addr" class="success">Address to validate</param>
/// <returns></returns>
public bool IsValidIP(string addr)
{
//create our match pattern
string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
//create our Regular Expression object
Regex check = new Regex(pattern);
//boolean variable to hold the status
bool valid = false;
//check to make sure an ip address was provided
if (addr == "")
{
//no address provided so return false
valid = false;
}
else
{
//address provided so use the IsMatch Method
//of the Regular Expression object
valid = check.IsMatch(addr, 0);
}
//return the results
return valid;
}
}
}

Download the complete ASP.Net 2.0 Solution which also includes the same functions presented as a Visual Basic Webservice and the xml file containing a starter set of known bad IP addresses to block that I found on this site. You could use this technique to check for bad IPs on Application Start in the Global.asax to block visitors to your site completely, or just on specific pages, or prior to processing a credit card transaction, or prior to posting a comment or feedback form, etc., etc.  


Posted by Williarob on Tuesday, November 20, 2007 9:48 AM
Permalink | Comments (0) | Post RSSRSS comment feed