簡體   English   中英

.net mvc 主機 header 注入 - http 模塊 - 400 錯誤請求

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

我的任務是減輕 MVC 應用程序中的主機 header 注入。 除其他外,我想通過創建 HTTP 模塊來實現白名單檢查。

到目前為止,我正在使用這樣的東西:

web.config 條目:

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

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

對於 MVC,更簡潔的解決方案是實現IActionFilter來執行驗證。 OnActionExecuting中,您可以執行 header 檢查並強制響應(您的 HTTP 400)以短路請求流的 rest。

您的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM