我可以使用哪些工具或技术来保护我的ASP.NET Web应用程序免受拒绝服务攻击?
我可以使用哪些工具或技术来保护我的ASP.NET Web应用程序免受拒绝服务攻击?
当然,硬件解决方案是防止DOS攻击的最佳选择,但考虑到您无法访问硬件配置或IIS设置的情况下,这绝对是开发人员必须掌握的技能,以阻止或至少减少dos攻击的影响。
逻辑的核心概念依赖于FIFO(先进先出)集合,例如队列,但由于它有一些限制,因此我决定创建自己的集合。
不再讨论更多细节,这是我使用的完整代码:
public class AntiDosAttack
{
readonly static List<IpObject> items = new List<IpObject>();
public static void Monitor(int Capacity, int Seconds2Keep, int AllowedCount)
{
string ip = HttpContext.Current.Request.UserHostAddress;
if (ip == "")
return;
// This part to exclude some useful requesters
if(HttpContext.Current.Request.UserAgent != null && HttpContext.Current.Request.UserAgent == "Some good bots")
return;
// to remove old requests from collection
int index = -1;
for (int i = 0; i < items.Count; i++)
{
if ((DateTime.Now - items[i].Date).TotalSeconds > Seconds2Keep)
{
index = i;
break;
}
}
if (index > -1)
{
items.RemoveRange(index, items.Count - index);
}
// Add new IP
items.Insert(0, new IpObject(ip));
// Trim collection capacity to original size, I could not find a better reliable way
if (items.Count > Capacity)
{
items.RemoveAt(items.Count - 1);
}
// Count of currect IP in collection
int count = items.Count(t => t.IP == ip);
// Decide on block or bypass
if (count > AllowedCount)
{
// alert webmaster by email (optional)
ErrorReport.Report.ToWebmaster(new Exception("Blocked probable ongoing ddos attack"), "EvrinHost 24 / 7 Support - DDOS Block", "");
// create a response code 429 or whatever needed and end response
HttpContext.Current.Response.StatusCode = 429;
HttpContext.Current.Response.StatusDescription = "Too Many Requests, Slow down Cowboy!";
HttpContext.Current.Response.Write("Too Many Requests");
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}
}
internal class IpObject
{
public IpObject(string ip)
{
IP = ip;
Date = DateTime.Now;
}
public string IP { get; set; }
public DateTime Date { get; set; }
}
}
内部类旨在保存请求的日期。
自然地,DOS攻击请求会在每个请求上创建新的会话,而人类对网站的请求包含多个请求打包在一个会话中,因此该方法可以在Session_Start中调用。
使用方法:
protected void Session_Start(object sender, EventArgs e)
{
// numbers can be tuned for different purposes, this one is for a website with low requests
// this means: prevent a request if exceeds 10 out of total 30 in 2 seconds
AntiDosAttack.Monitor(30, 2, 10);
}
对于一个高请求量的网站,你可以将秒数改为毫秒,但要考虑此代码所引起的额外负载。
我不知道是否有更好的解决方法来阻止网站上的恶意攻击,因此我感谢任何评论和建议以改进代码。在那之前,我认为这是一种以编程方式预防ASP.NET网站DOS攻击的最佳实践。