Thursday, November 7, 2013

MVC4: Remove unnecessary headers

For some reason, Microsoft by default loves to advertise that you are running their products.  This is probably so that they can skew the webserver stats in their favour.

Even so, it is a good idea to hide these headers, or use them to provide misleading information.

In an MVC application, there are generally  3 headers you are going to want to target.

The first one is the server header.  This one is IIS specific.  Unfortunately, MS has not provided an easy way to change this header.  The two options you have are to use a WAF that will mask it for you, or to change it in code.  The code option involves creating a http module and adding it to the pipeline in the appropriate place.


    public class CustomServerHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        private void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Set("Server","Jetty(6.0.x)");
        }

        public void Dispose()
        {
            
        }
    }

In the above case, I am setting the server header similar to that of Jetty.  Why?  Well, why not?

The second one you will want to target is the x-powered-by header.  I mean, who cares what powers your site.  Oh wait, an attacker does.  In any event, this a custom header that is set in one of the .config files that IIS reads.  You can override this by adding a clear tag.


<httpProtocol>
  <customHeaders>
    <clear />
  </customHeaders>
<httpProtocol>

The last one is the X-AspNetMvc-Version. Once again, I'm not sure why you would want to advertise this to anyone.  Luckily this one can easily be disabled by code.  In the application start of your global.asax simply add the following line.


MvcHandler.DisableMvcResponseHeader = true;

Trying to minimize the amount of information leaked by your application is always a good thing.

No comments:

Post a Comment