【问题标题】:.net mvc host header injection - http module - 400 Bad Request.net mvc 主机标头注入 - http 模块 - 400 错误请求
【发布时间】:2019-11-07 18:36:33
【问题描述】:

我的任务是减轻 MVC 应用程序中的主机标头注入。除此之外,我想通过创建一个 HTTP 模块来实现白名单检查。

到目前为止,我正在使用这样的东西:

web.config 条目:

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

HTTP 模块类:

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??
        }
    }
}

【问题讨论】:

    标签: .net asp.net-mvc httpmodule header-injection


    【解决方案1】:

    对于 MVC,更简洁的解决方案是实现 IActionFilter 来执行验证。在OnActionExecuting 中,您可以执行标头检查并强制那里的响应(您的 HTTP 400)以短路请求流的其余部分。

    您的OnActionExecuting 实现如下所示。

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

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

    【讨论】:

    • 我也考虑过这种方法,并将跟进。你知道强制 HTTP 400 的最佳方法吗?
    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多