My site is hosted on shared hosting and if you spend 25% CPU for more than 90 seconds hosting company automatically disable application pool. I wonder if this code can offload server from a simple DoS attacks
void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = base.Context;
string ip = context.Request.UserHostAddress;
int activeRequests = (int)(context.Cache[ip] ?? 0);
activeRequests++;
if (activeRequests == 1)
{
context.Cache.Add(ip, activeRequests, null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}
if (activeRequests > 10)
{
log4net.Config.XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.WarnFormat("Blocked IP: {0}, ActiveRequests: {1}", ip, activeRequests);
Response.Clear();
Response.Redirect("~/Error500.html");
}
}
void Application_EndRequest(object sender, EventArgs e)
{
HttpContext context = base.Context;
string ip = context.Request.UserHostAddress;
int activeRequests = (int)(context.Cache[ip] ?? 0);
activeRequests--;
}
What I mean by a simple DoS attacks.
for (int i = 0; i < 100000; i++)
{
WebClient client = new WebClient();
client.DownloadString("http://example.com");
}