Asp.net anti-DDOS (CC attack) Code

Source: Internet
Author: User

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
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.