使用MVC Razor进行输入消毒 - 如何安全?

jth*_*eis 2 xss razor asp.net-mvc-4

如果我有一个带有文本字段的标准注册表单,并且我在其中键入脚本标记,MVC会发回一个错误,指出"从客户端检测到一个潜在危险的Request.Form值".这只是一个调试错误吗?我的用户会在实际网站上看到这个吗?

是否有一种安全而简单的方法来静默接受和编码/清理字段中的输入,这样MVC不会引发可怕的错误,但输入是无害的?

显然我也想确保我的输出被编码,但Razor在大多数情况下都会照顾它,而且我很小心@Html.Raw.我们也已经通过使用参数化查询来处理数据库输入,因此SQL注入不应该是一种威胁.

小智 5

"从客户端检测到一个潜在危险的Request.Form值"异常不仅仅是一个调试错误,而且是一个将在部署服务器上传播的错误.因此,您的用户将在实时服务器上看到此错误(或您的自定义错误页面).

要允许未清理的HTML成功绑定到您的模型,您可以执行以下任何操作:

  1. 使用该[AllowHtml]属性装饰您的SignUp模型属性
  2. 使用[ValidateInput( false )]属性装饰您的SignUp控制器操作
  3. 如果您正在使用MVC v4.0,请在web.config中包含以下内容:

    <location path="Accounts/SignUp"> <system.web> <pages validateRequest="false" /> <httpRuntime requestValidationMode="2.0" /> </system.web> </location>

我再说一遍,以上所有内容都允许将未经过清理的HTML绑定到您的模型.这意味着没有"从客户端检测到有潜在危险的Request.Form值"错误,但您的输入将不会被清理,并且仍然可能包含可能有害的标记.

为了允许将已清理的输入绑定到模型,您可以通过属性调整PropertyBindAttribute实现从Customizing属性绑定,以允许您使用属性来装饰模型[AllowSanitizedHtml]属性,您希望在清理后允许接受HTML输入的功能.对于清理,您可以使用Microsoft.Security.Application.Encoder.Encode()帮助方法(NuGet包名称:'AntiXSS')

首先,提供用于自然绑定的基类的属性:

[AttributeUsage( AttributeTargets.Property , AllowMultiple = false )]
public abstract class AbstractPropertyBinderAttribute :
    Attribute
{

    public abstract bool BindProperty(
        ControllerContext controllerContext ,
        ModelBindingContext bindingContext ,
        PropertyDescriptor propertyDescriptor
        );

}
Run Code Online (Sandbox Code Playgroud)

然后,知道此属性的自定义模型绑定器,以便模型绑定可以处理属性属性绑定的特殊情况:

public class CustomModelBinder : 
    DefaultModelBinder
{

    protected override void BindProperty(
        ControllerContext controllerContext ,
        ModelBindingContext bindingContext , 
        PropertyDescriptor propertyDescriptor )
    {
        if( propertyDescriptor.Attributes.OfType<AbstractPropertyBinderAttribute>().Any() )
        {
            var modelBindAttr = propertyDescriptor.Attributes.OfType<AbstractPropertyBinderAttribute>().FirstOrDefault();

            if( modelBindAttr.BindProperty(
                    controllerContext ,
                    bindingContext ,
                    propertyDescriptor ) )
            {
                return;
            }
        }

        base.BindProperty(
            controllerContext ,
            bindingContext ,
            propertyDescriptor
            );
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将以下代码添加到Global.asax中,以允许将CustomModelBinder用作默认值:

System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
Run Code Online (Sandbox Code Playgroud)

最后,AllowSanitizedHtmlAttribute:

public class AllowSanitizedHtmlAttribute :
    AbstractPropertyBinderAttribute ,
    IMetadataAware
{

    public override bool BindProperty(
        ControllerContext controllerContext ,
        ModelBindingContext bindingContext ,
        PropertyDescriptor propertyDescriptor )
    {
        if( propertyDescriptor.PropertyType == typeof( string ) )
        {
            var unvalidatedValueProvider = bindingContext.ValueProvider as IUnvalidatedValueProvider;
            var result = unvalidatedValueProvider.GetValue(
                propertyDescriptor.Name ,
                true 
                );

            if( result != null )
            {
                propertyDescriptor.SetValue(
                    bindingContext.Model ,
                    Encoder.HtmlEncode( result.AttemptedValue )
                    );
                return true;
            }
        }

        return false;
    }


    #region IMetadataAware Members

    public void OnMetadataCreated( ModelMetadata metadata )
    {
        if( metadata == null )
            throw new ArgumentNullException( "metadata" );

        metadata.RequestValidationEnabled = false;
    }

    #endregion

}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用属性安全地装饰需要在SignUp表单中进行清理的模型[AllowSanitizedHtml]属性.这将允许在清理后以静默方式绑定模型属性的输入.