Sunday, October 28, 2012

Programmatically remove HTTP response headers

By default, all the responses of your server will be sent with some embarrassing details...


For an ASP.NET MVC web application, you have these headers :


  • Server: which is added by IIS.
  • X-AspNet-Version: which is added at the time of Flush in HttpResponse.
  • X-AspNetMvc-Version:which is  added by MvcHandler in System.Web.dll.
  • X-Powered-By: which is added by IIS.

Hackers will be happy to know the exact version of the used Framework: if your server has not been updated for a while and a major security vulnerability was found for the version of the Framework you are using, you will help them...

Moreover, these headers add a weight to all your responses (a few bytes, but I like optimizing...)

If you want to remove these headers, here are the steps to follow:

1) Removing the Server header: go to Global.asax.cs, add the Application_PreSendRequestHeaders event with this code:


   1:  protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
   2:  {
   3:      var app = sender as HttpApplication;
   4:      if (app == null || !app.Request.IsLocal || app.Context == null)
   5:          return;
   6:      var headers = app.Context.Response.Headers;
   7:      headers.Remove("Server");
   8:  }

2) Removing the X-AspNetMvc-Version header: go to Global.asax.cs, modify the Application_Start event with this code:


   1:  protected void Application_Start()
   2:  {
   3:      ...
   4:      MvcHandler.DisableMvcResponseHeader = true;
   5:      ...
   6:  }

3) Removing the X-AspNet-Version header: edit the web.config and add this element in the system.web section:


   1:  <system.web>
   2:      ...
   3:      <httpRuntime enableVersionHeader="false" />
   4:      ...
   5:  </system.web>

4) Removing the X-Powered-By header: edit the web.config and add this code in the system.webServer:

   1:  <system.webServer>
   2:      ...
   3:      <httpProtocol>
   4:          <customHeaders>
   5:              <remove name="X-Powered-By" />
   6:          </customHeaders>
   7:      </httpProtocol>
   8:      ...
   9:  </system.webServer>


The work is done, the responses of your server will be lighter and will not give important information about its versions.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.