.net - .net mvc 主机标头注入 - http 模块 - 400 错误请求
问题描述
我的任务是减轻 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??
}
}
}
解决方案
对于 MVC,更简洁的解决方案是实现一个IActionFilter
来执行您的验证。在OnActionExecuting
您可以执行您的标头检查并强制响应(您的 HTTP 400)在那里短路请求流的其余部分。
您的OnActionExecuting
实现如下所示。
if(!ValidateWhiteListedHeaders(context.HttpContext.Request.Headers)){
context.Result = new StatusCodeResult(400);
return;
}
推荐阅读
- python - 如何将代理与我的代码合并(Instaloader python 模块)
- mysql - 如何根据另一个表的选择在表的列中插入值
- c# - 使用 ParallelTask 和 ConcurrentStack 使用单声道导致 Android 崩溃
- c# - HeaderStringFormat 覆盖 Binding 之外的样式
- nativescript - 移动操作系统升级后 NativeScript 应用程序损坏
- .net - .NET 4 到 .NET 4.5.2 - PresentationFramework '方法'get_Command'
- bash - 使用带有破折号('-')的变量的whiptail
- python - 如何让 Flask request.form 返回有序的字典数据?
- google-sheets - 如何在谷歌表格单元格中放置一个href
- hlsl - HLSL 中的流控制