Question

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");
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top