0

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");
}
Georgi Filipov
  • 332
  • 2
  • 18

1 Answers1

1

No, that code won't help. Moreover it can be really problematic for users behind a proxy: the HTTP requests will be issued by the proxy server, so the client IP will be the same for every PC behind it.

The DoS prevention is done on the infrastructure, outside your application's code. See this article as an example on IIS: http://m.windowsitpro.com/windows/q-does-microsoft-iis-70-include-feature-protect-iis-web-server-denial-service-dos-attacks-do

So, in short, the DoS prevention is normally done by the hosting provider.

Manuel Spezzani
  • 1,041
  • 7
  • 15
  • People behind the proxy are a small part of the traffic that comes to my site and I do not worry about them. The truth is that I have no access to the IIS manager-a to set Dynamic IP Restrictions module. Once my hosting plan is over I will switch to more .net oriented hosting. I will start new ticket but I don't believe I will have success. – Georgi Filipov Mar 22 '14 at 09:15
  • Have you already faced a dos attack? Are you really sure your hosting provider doesn't take that eventuality into account (they can work at multiple level on the infrastructure, not only on IIS)? It will be really really strange... In that case my only advice is, as you already said, to change provider as fast as you can! :) – Manuel Spezzani Mar 22 '14 at 10:45