简体   繁体   English

.net mvc 主机 header 注入 - http 模块 - 400 错误请求

[英].net mvc host header injection - http module - 400 Bad Request

I have a task to mitigate host header injection in an MVC app.我的任务是减轻 MVC 应用程序中的主机 header 注入。 Among other things, I want to implement a whitelist check by creating a HTTP Module.除其他外,我想通过创建 HTTP 模块来实现白名单检查。

So far, I am using something like this:到目前为止,我正在使用这样的东西:

web.config entry: web.config 条目:

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

HTTP Module class: HTTP 模块 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??
        }
    }
}

For MVC, the cleaner solution would be to implement an IActionFilter to perform your validation.对于 MVC,更简洁的解决方案是实现IActionFilter来执行验证。 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.OnActionExecuting中,您可以执行 header 检查并强制响应(您的 HTTP 400)以短路请求流的 rest。

Your OnActionExecuting implementation would look like the following.您的OnActionExecuting实现如下所示。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM