Add security headers to help protection from injection attacks in c# asp.net

Viewed 14968

I have a C# asp.net application.It was sent to security assessment and below were the risks.

-Missing "Content-Security-Policy" header
-Missing "X-Content-Type-Options" header
-Missing "X-XSS-Protection" header 
-It was observed that server banner is getting disclosed in HTTP response.
-It was observed that service version is getting disclosed in HTTP response.

I have the below code in the web.cofig file

<httpProtocol>
<customHeaders>

<remove name="X-Powered-By"/>
<add name="X-Frame-Options" value="DENY"/>
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff "/>

</customHeaders>
</httpProtocol>

I thought this will add the headers. But the security team says the issue is not fixed. Is there any alternate for this.And for the Banner disclosure, I don't have access to server. can I fix this within the application. After research I found this: Inside Global.asax I have this code:

protected void Application_PreSendRequestHeaders()
    {
        // Response.Headers.Remove("Server");
        Response.Headers.Set("Server", "My httpd server");
        Response.Headers.Remove("X-AspNet-Version");
        Response.Headers.Remove("X-AspNetMvc-Version");
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var app = sender as HttpApplication;
        if (app != null && app.Context != null)
        {
            app.Context.Response.Headers.Remove("Server");
        }
    }

Is this the correct fix. Please help

3 Answers

Ensure you add the httpProtocol in the system.webServer as shown below:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="DENY" />
      <add name="X-Xss-Protection" value="1; mode=block" />
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

To remove the "server" header, add the code below in your Global.asax file

protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("Server");
}

You can add any header globally using web.config e.g.

<system.webServer>    
<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />        
    <add name="Cache-Control" value="no-store" />
    <add name="X-XSS-Protection" value="1; mode=block" />
    <add name="X-Content-Type-Options" value="nosniff" />
    <add name="Strict-Transport-Security" value="max-age=31536000" />        
  </customHeaders>
</httpProtocol>
</system.webServer>

Refer : Adding Custom Headers Globally

Related