【问题标题】:ASP.NET MVC XSS ValidationASP.NET MVC XSS 验证
【发布时间】:2015-05-18 16:08:40
【问题描述】:

我们正在使用 ASP.NET MVC 5.0 构建网站。如果我在保存时输入一些 javascript 文本框,我会得到一个“检测到可能不安全的输入”错误页面 - 太好了。

然而,我们的一些屏幕使用 ajax 提交将 json 直接传递给控制器​​,这似乎跳过了上面的验证。

有没有办法在控制器中调用模型(或模型中的每个文本字段)的标准验证,以便抛出上述错误。 即类似

 public override ActionResult Create(MyModel myModel)
 {
     /* Any dubious input this should throw an error*/
     AntiXSS.ValidateInput(myModel);
     ...

【问题讨论】:

    标签: xss asp.net-mvc


    【解决方案1】:

    我遇到了类似的问题,正如 cmets 在其他答案中所指出的,我们让 JQuery 使用 $.ajax 将 JSON 发布到 MVC 操作。默认模型绑定器不会验证已发布的 JSON,从而允许针对我们的操作发布不安全的 XSS。

    为了解决这个问题,我发现RequestValidator 有一个静态方法InvokeIsValidRequestString 允许

    public class ValidateJsonXssAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext?.Request;
            if (request != null && "application/json".Equals(request.ContentType, StringComparison.OrdinalIgnoreCase))
            {
                if (request.ContentLength > 0 && request.Form.Count == 0) // 
                {
                    if (request.InputStream.Position > 0)
                        request.InputStream.Position = 0; // InputStream has already been read once from "ProcessRequest"
                    using (var reader = new StreamReader(request.InputStream))
                    {
                        var postedContent = reader.ReadToEnd(); // Get posted JSON content
                        var isValid = RequestValidator.Current.InvokeIsValidRequestString(HttpContext.Current, postedContent,
                            RequestValidationSource.Form, "postedJson", out var failureIndex); // Invoke XSS validation
                        if (!isValid) // Not valid, so throw request validation exception
                            throw new HttpRequestValidationException("Potentially unsafe input detected");
                    }
                }
            }
        }
    }
    

    然后,您可以装饰相关的 MVC 操作,期待可能绕过标准 XSS 预防的 JSON 发布数据:

    [HttpPost]
    [ValidateJsonXss]
    public ActionResult PublishRecord(RecordViewModel vm) { ... }
    

    您可以通过扩展 RequestValidator 对象来查看使用 OWASP .NET 建议自定义请求验证的其他选项,该对象公开了由 MVC 自动用于查询字符串、表单集合和 cookie 的其他场景的 ValidateInput 完成的字符串验证价值观。

    欲了解更多信息:https://www.owasp.org/index.php/ASP.NET_Request_Validation

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 我仍然可以在输入中输入脚本标签。验证输入似乎没有帮助。
      • 进一步的研究表明,问题在于 JsonValueProviderFactory 被用于对不运行验证的绑定进行建模。
      • 同意杰克。看看这个:weblogs.asp.net/imranbaloch/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多