1

I have a task to mitigate host header injection in an MVC app. Among other things, I want to implement a whitelist check by creating a HTTP Module.

So far, I am using something like this:

web.config entry:

  <system.webServer>
    <modules>
      <add name="TestHttpModule" type="MVC5TestApp.MyHttpModule, MVC5TestApp" />
    </modules>
  </system.webServer>

HTTP Module class:

public class MyHttpModule: IHttpModule 
{

    public MyHttpModule() {}

    public void Init(HttpApplication application) 
    {
        application.BeginRequest += new EventHandler(this.context_BeginRequest);
        application.EndRequest += new EventHandler(this.context_EndRequest);
    }

    public void context_BeginRequest(object sender, EventArgs e) 
    {
        CheckForHostHeaderInjection();
    }

    public void context_EndRequest(object sender, EventArgs e) 
    {
        // some code
    }

    public void Dispose() {}

    private void CheckForHostHeaderInjection()
    {
        // Currently, I am just comparing the following two ServerVariables.
        // I will add a method to compare "HTTP_HOST" value against a whitelist later.
        var httpHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
        var serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];

        if (!string.Equals(httpHost, serverName))
        {
            // What do I do in order to send back to the client a 400 Bad Request??
        }
    }
}
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
Kershaw
  • 1,124
  • 1
  • 7
  • 18

1 Answers1

0

For MVC, the cleaner solution would be to implement an IActionFilter to perform your validation. In OnActionExecuting you can perform your header checks and force the response (your HTTP 400) there to short circuit the rest of the request flow.

Your OnActionExecuting implementation would look like the following.

if(!ValidateWhiteListedHeaders(context.HttpContext.Request.Headers)){
  context.Result = new StatusCodeResult(400);
  return;
}

See https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs#understanding-action-filters

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
  • I had considered this approach as well and will follow up on it. Do you know the best way to force the HTTP 400? – Kershaw Nov 07 '19 at 18:52