Web. config:
<HttpModules>
<! -Url rewriting->
<Add type = "UrlRewriter. RewriterHttpModule, UrlRewriter" name = "UrlRewriter"/>
<! -Anti-DDOS->
<Add type = "UrlRewriter. DDosAttackModule, UrlRewriter" name = "DDosAttackModule"/>
</HttpModules>
Code:
Copy to ClipboardReference: [www.bkjia.com] using System;
Using System. Web;
Using System. Collections. Generic;
Using System. Collections. Specialized;
Using System. Timers;
Namespace UrlRewriter
{
Using System. IO;
/// <Summary>
/// Block the response to attacking IP addresses.
/// </Summary>
Public class DDosAttackModule: IHttpModule
{
# Region IHttpModule Members
Void IHttpModule. Dispose ()
{
// Nothing to dispose;
}
Void IHttpModule. Init (HttpApplication context)
{
Context. BeginRequest + = new EventHandler (context_BeginRequest );
}
# Endregion
# Region Private fields
Private static Dictionary <string, short> _ IpAdresses = new Dictionary <string, short> ();
Private static Stack <string> _ Banned = new Stack <string> ();
Private static Timer _ Timer = CreateTimer ();
Private static Timer _ BannedTimer = CreateBanningTimer ();
# Endregion
Private const int BANNED_REQUESTS = 10;
Private const int REDUCTION_INTERVAL = 1000; // 1 second
Private const int RELEASE_INTERVAL = 5x60*1000; // 5 minutes
Private void context_BeginRequest (object sender, EventArgs e)
{
// Determine whether the request is a page path
System. text. regularExpressions. regex reg = new System. text. regularExpressions. regex (@ "^ (/. + (\. aspx | \. ashx | \. axd )(\?. + )?) $ ", System. Text. RegularExpressions. RegexOptions. IgnoreCase );
System. Text. RegularExpressions. Match match Match = reg. Match (HttpContext. Current. Request. Url. LocalPath );
If (match. Success)
{
// Website access signature, site + IP Address
String code = HttpContext. Current. Request. ServerVariables ["SERVER_NAME"] + "|" + GetIP ();
If (_ Banned. Contains (code ))
{
HTTP context. Current. Response. StatusCode = 403;
HttpContext. Current. Response. End ();
}
CheckIpAddress (code );
}
}
/// <Summary>
/// Checks the requesting IP address in the collection
/// And bannes the IP if required.
/// </Summary>
Private static void CheckIpAddress (string code)
{
If (! _ IpAdresses. ContainsKey (code ))
{
_ IpAdresses [code] = 1;
}
Else if (_ IpAdresses [code] = BANNED_REQUESTS)
{
WriteCC (code); // record CC suspicious IP addresses
_ Banned. Push (code );
_ IpAdresses. Remove (code );
}
Else
{
_ IpAdresses [code] ++;
}
}
/// <Summary>
/// Write the suspicious CC attack IP address to the file
/// </Summary>
/// <Param name = "ip"> </param>
Private static void WriteCC (string code)
{
String dir = HttpContext. Current. Server. MapPath ("~ /CC /");
If (! Directory. Exists (dir ))
{
Directory. CreateDirectory (dir );
}
StreamWriter sw = new StreamWriter (dir + DateTime. Now. ToString ("yyyy-MM-dd") + ". txt", true );
Sw. Write (code + "" + DateTime. Now. ToString () + "\ n ");
Sw. Close ();
}
/// <Summary>
/// Obtain the Client IP Address
/// </Summary>
/// <Returns> </returns>
Public static string GetIP ()
{
String result = String. Empty;
Result = HttpContext. Current. Request. ServerVariables ["HTTP_X_FORWARDED_FOR"];
If (null = result | result = String. Empty)
{
Result = HttpContext. Current. Request. ServerVariables ["REMOTE_ADDR"];
}
If (null = result | result = String. Empty)
{
Result = HttpContext. Current. Request. UserHostAddress;
}
If (null = result | result = String. Empty |! System. Text. RegularExpressions. Regex. IsMatch (result, @ "^ (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) \.) {3} (2 [0-4] \ d | 25 [0-5] | [01]? \ D ?) $ "))
{
Return "0.0.0.0 ";
}
Return result;
}
# Region Timers
/// <Summary>
/// Creates the timer that substract a request
/// From the _ IpAddress dictionary.
/// </Summary>
Private static Timer CreateTimer ()
{
Timer timer = GetTimer (REDUCTION_INTERVAL );
Timer. Elapsed + = new ElapsedEventHandler (TimerElapsed );
Return timer;
}
/// <Summary>
/// Creates the timer that removes 1 banned IP address
/// Everytime the timer is elapsed.
/// </Summary>
/// <Returns> </returns>
Private static Timer CreateBanningTimer ()
{
Timer timer = GetTimer (RELEASE_INTERVAL );
Timer. Elapsed + = delegate {_ Banned. Pop ();};
Return timer;
}
/// <Summary>
/// Creates a simple timer instance and starts it.
/// </Summary>
/// <Param name = "interval"> The interval in milliseconds. </param>
Private static Timer GetTimer (int interval)
{
Timer timer = new Timer ();
Timer. Interval = interval;
Timer. Start ();
Return timer;
}
/// <Summary>
/// Substracts a request from each IP address in the collection.
/// </Summary>
Private static void TimerElapsed (object sender, ElapsedEventArgs e)
{
Try
{
Foreach (string key in _ IpAdresses. Keys)
{
_ IpAdresses [key] --;
If (_ IpAdresses [key] = 0)
_ IpAdresses. Remove (key );
}
}
Catch {}
}
# Endregion
}
}