软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > asp.net防类似DDOS攻击(CC攻击)代码

asp.net防类似DDOS攻击(CC攻击)代码

Web.config:

<httpModules>
<!–Url重写–>
<add type=”UrlRewriter.RewriterHttpModule, UrlRewriter” name=”UrlRewriter”/>
<!–防类似DDOS攻击–>
<add type=”UrlRewriter.DDosAttackModule, UrlRewriter” name=”DDosAttackModule”/>
</httpModules>

代码:

Copy to ClipboardLiehuo.Net Codes引用的内容:[www.veryhuo.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 = 5 * 60 * 1000; // 5 minutes
private void context_BeginRequest(object sender, EventArgs e)
{
//判断请求的是否为页面路径
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^(/.+(\.aspx|\.ashx|\.axd)(\?.+)?)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Match match = reg.Match(HttpContext.Current.Request.Url.LocalPath);
if (match.Success)
{
//访问站点特征码,站点 + IP地址
string code = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "|" + GetIP();
if (_Banned.Contains(code))
{
HttpContext.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);//记录CC可疑IP
_Banned.Push(code);
_IpAdresses.Remove(code);
}
else
{
_IpAdresses[code]++;
}
}
/// <summary>
/// 将可疑CC攻击IP写到文件中
/// </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>
/// 获取客户端IP地址
/// </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\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\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
}
}
    相关阅读
    栏目导航
    推荐软件