asp.Net防類似DDOS攻撃(CC攻撃)コード


Web.config

 
 
コード:
using System

;

using System .Web ;
using System .Collections .Generic ;
using System .Collections .Specialized ;
using System .Timers ;

namespace UrlRewriter
{
/// <summary>
/// IP
/// </summary>
public class DosAttackModule : IHttpModule
{
void IHttpModule.Dispose ( ) { }

void IHttpModule.Init ( HttpApplication context)
{
context.BeginRequest += new EventHandler( context_BeginRequest) ;
}

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( ) ;

private const int BANNED_REQUESTS = 1 ; //
private const int REDUCTION_INTERVAL = 1000 ; // 1 ( )
private const int RELEASE_INTERVAL = 5 * 60 * 1000 ; // 5 ( IP )

private void context_BeginRequest( object sender, EventArgs e)
{
string ip = HttpContext.Current .Request .UserHostAddress ;
if ( _Banned.Contains ( ip) )
{
HttpContext.Current .Response .StatusCode = 403 ;
HttpContext.Current .Response .End ( ) ;
}

CheckIpAddress( ip) ;
}

/// <summary>
/// IP
/// </summary>
private static void CheckIpAddress( string ip)
{
if ( ! _IpAdresses.ContainsKey ( ip) ) // IP 1
{
_IpAdresses[ ip] = 1 ;
}
else if ( _IpAdresses[ ip] == BANNED_REQUESTS) // IP “ ”
{
_Banned.Push ( ip) ;
_IpAdresses.Remove ( ip) ;
}
else // 1
{
_IpAdresses[ ip] ++;
}
}

#region Timers

/// <summary>
/// , _IpAddress 。
/// </summary>
private static Timer CreateTimer( )
{
Timer timer = GetTimer( REDUCTION_INTERVAL) ;
timer.Elapsed += new ElapsedEventHandler( TimerElapsed) ;
return timer;
}

/// <summary>
/// , IP
/// </summary>
/// <returns></returns>
private static Timer CreateBanningTimer( )
{
Timer timer = GetTimer( RELEASE_INTERVAL) ;
timer.Elapsed += delegate { _Banned.Pop ( ) ; } ; // IP
return timer;
}

/// <summary>
/// ,
/// </summary>
/// <param name="interval"> </param>
private static Timer GetTimer( int interval)
{
Timer timer = new Timer ( ) ;
timer.Interval = interval;
timer.Start ( ) ;

return timer;
}

/// <summary>
/// IP
/// </summary>
private static void TimerElapsed( object sender, ElapsedEventArgs e)
{
foreach ( string key in _IpAdresses.Keys )
{
_IpAdresses[ key] --;
if ( _IpAdresses[ key] == 0 )
_IpAdresses.Remove ( key) ;
}
}

#endregion

}
}