如何使用反xss攻击清理web api中的输入数据

时间:2015-09-16 04:43:54

标签: c# xss asp.net-web-api modelbinder

以下是我的代码片段

模型类

// Customer.cs

using CommonLayer;

namespace Models
{
    public class Customer
    {
        public int Id { get; set; }

        [MyAntiXss]
        public string Name { get; set; }
    }
}

我想清理Model类的'Name'字段中的值,如下所示

// CutstomModelBinder.cs

 using Microsoft.Security.Application;
    using System.ComponentModel;
    using System.Linq;
    using System.Web.Mvc;

    namespace CommonLayer
    {
        public class CutstomModelBinder : DefaultModelBinder
        {
            protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
            {
                if (propertyDescriptor.Attributes.OfType<MyAntiXssAttribute>().Any())
                {
                    ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
                    string filteredValue = Encoder.HtmlEncode(valueResult.AttemptedValue);
                    propertyDescriptor.SetValue(bindingContext.Model, filteredValue);
                }
                else
                    base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
    }

我将'DefaultBinder'更改为我的'CutstomModelBinder',如下所示

// Global.asax.cs

using CommonLayer;
using System.Web.Http;
using System.Web;
using System.Web.Mvc;

namespace WebAPI
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            ModelBinders.Binders.DefaultBinder = new CutstomModelBinder();
        }
    }
}

我写了一个控制器类,如下所示

// CustomerController.cs

using Models;
using System.Collections.Generic;
using System.Web.Http;

namespace WebAPI.Controllers
{
    public class CustomerController : ApiController
    {
        public string Post([FromBody]Customer customer)
        {
            //customer.Name = Encoder.HtmlEncode(customer.Name);
            return string.Format("Id = {0}, Name = '{1}'", customer.Id, customer.Name);
        }
    }
}

当我调用上面控制器的类'Post'方法时,它按预期调用控制器类的'Post'方法。但它并没有在我的'CutstomModelBinder'类中调用'BindProperty'方法。

// Program.cs

using Models;
using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;

namespace Client
{
    public static class Program
    {
        public static void Main(params string[] args)
        {
            bool success = Post();
            Console.WriteLine("success = " + success);
            Console.Read();
        }

        private static HttpClient GetHttpClient()
        {
            HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:49295/") };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }

        private static bool Post()
        {
            Customer customer = new Customer { Id = 1, Name = "<br>Anivesh</br>" };
            HttpContent content = new ObjectContent<Customer>(customer, new JsonMediaTypeFormatter());

            HttpClient client = GetHttpClient();
            HttpResponseMessage response = client.PostAsync("Customer", content).Result;
            client.Dispose();

            if (response.IsSuccessStatusCode)
            {
                string expected = string.Format("Id = {0}, Name = '{1}'", customer.Id, customer.Name);
                string result = response.Content.ReadAsAsync<string>().Result;
                return expected == result;
            }
            else
                return false;
        }
    }
}

请让我知道使用'DataBinders'的正确方法,以便在接收控制器中的呼叫之前,我可以在公共场所清理输入数据。

3 个答案:

答案 0 :(得分:6)

要使用Web API以通用方式清理输入,您可以按我之前的答案中所述创建自己的ModelBinder,但更简单的方法可能是修改现有的JsonMediaTypeFormatter以在中包含所需的santization逻辑ReadFromStreamAsync 方法。

您可以尝试的一种方法如下:

首先,创建一个通用属性,用于装饰需要清理的DTO中的属性,即:

 [AttributeUsage(AttributeTargets.Property)]
 public sealed class SanitizeAttribute : Attribute
 { }

然后创建一个JsonMediaTypeFormatter的子类型来处理清理,即:

public sealed class SanitizingJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        Task<object> resultTask = base.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);

        var propertiesFlaggedForSanitization = type.GetProperties().Where(e => e.GetCustomAttribute<SanitizeAttribute>() != null).ToList();
        if (propertiesFlaggedForSanitization.Any())
        {
            var result = resultTask.Result;
            foreach (var propertyInfo in propertiesFlaggedForSanitization)
            {
                var raw = (string)propertyInfo.GetValue(result);
                if (!string.IsNullOrEmpty(raw))
                {
                    propertyInfo.SetValue(result, AntiXssEncoder.HtmlEncode(raw, true));
                }
            }
        }
        return resultTask;
    }
}

此实现只是检查生成的Type是否具有使用Sanitize属性修饰的任何属性,如果是,则使用内置的System.Web.Security.AntiXss.AntiXssEncoder(.NET 4.5及更高版本)进行消毒。

您可能希望优化此类,以便缓存类型和属性信息,这样您就不会对每个反序列化进行重量级反射调用。

此过程的最后一步是在WebAPI启动代码中用您自己的内置JSON媒体类型格式化程序替换:

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
config.Formatters.Remove(jsonFormatter);
config.Formatters.Add(new SanitizingJsonMediaTypeFormatter());

现在任何具有Sanitize属性修饰属性的DTO都会在DTO甚至命中你的控制器之前被正确编码。

答案 1 :(得分:0)

DefaultModelBinder位于 System.Web.ModelBinding 命名空间中,由MVC控制器使用。

对于WebAPI项目,您需要实现 System.Web.Http.ModelBinding.IModelBinder 接口。

直接从MSDN站点获取的示例模型绑定器如下:

public class GeoPointModelBinder : IModelBinder
{
    // List of known locations.
    private static ConcurrentDictionary<string, GeoPoint> _locations
        = new ConcurrentDictionary<string, GeoPoint>(StringComparer.OrdinalIgnoreCase);

    static GeoPointModelBinder()
    {
        _locations["redmond"] = new GeoPoint() { Latitude = 47.67856, Longitude = -122.131 };
        _locations["paris"] = new GeoPoint() { Latitude = 48.856930, Longitude = 2.3412 };
        _locations["tokyo"] = new GeoPoint() { Latitude = 35.683208, Longitude = 139.80894 };
    }

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(GeoPoint))
        {
            return false;
        }

        ValueProviderResult val = bindingContext.ValueProvider.GetValue(
            bindingContext.ModelName);
        if (val == null)
        {
            return false;
        }

        string key = val.RawValue as string;
        if (key == null)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, "Wrong value type");
            return false;
        }

        GeoPoint result;
        if (_locations.TryGetValue(key, out result) || GeoPoint.TryParse(key, out result))
        {
            bindingContext.Model = result;
            return true;
        }

        bindingContext.ModelState.AddModelError(
            bindingContext.ModelName, "Cannot convert value to Location");
        return false;
    }
}

可以在此处找到备份此示例的完整帖子:MSDN Model Binding

答案 2 :(得分:0)

.NetCore Web API 2.通过使用InputFormatter递归处理传入JSON的所有属性(在任何深度)。

[AttributeUsage(AttributeTargets.Property)]
public sealed class SanitizePropertyAttribute : Attribute
{
}

public class SanitizeTextInputFormatter: Microsoft.AspNetCore.Mvc.Formatters.TextInputFormatter
{
    private List<String> ExcludeTypes = new List<string>()
    {
        "System.DateTime",
        "System.Int32",
        "System.Int64",
        "System.Boolean",
        "System.Char",
        "System.Object"
    };

    private string CleanInput(string strIn)
    {
        // Replace invalid characters with empty strings.
        try
        {
            // [<>/] or @"[^\w\.@-]"
            return Regex.Replace(strIn, @"[<>/]", "",
                                 RegexOptions.None, TimeSpan.FromSeconds(1.5));
        }
        // If we timeout when replacing invalid characters, 
        // we should return Empty.
        catch (RegexMatchTimeoutException)
        {
            return String.Empty;
        }
    }

    public SanitizeTextInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json"));

        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }

    private bool ValidateSanitizeProperty(Type type, PropertyInfo PropertyInfo, List<PropertyInfo> orgTypes)
    {
        var listedProperty = orgTypes.Where(_ => _ == PropertyInfo).FirstOrDefault();
        if (PropertyInfo != null && listedProperty == null) orgTypes.Add(PropertyInfo);

        if (listedProperty != null) return false;

        if (type.FullName == "System.String" && PropertyInfo != null)
        {
            var sanitizePropertyAttribute = PropertyInfo.GetCustomAttribute<SanitizePropertyAttribute>();
            //var sanitizeClassAttribute = PropertyInfo.CustomAttributes.Where(e => e.AttributeType == typeof(SanitizePropertyAttribute)).FirstOrDefault();

            return sanitizePropertyAttribute != null;
        }

        var typeProperties = type.GetProperties().Where(_ => _.PropertyType.IsAnsiClass == true && !ExcludeTypes.Contains(_.PropertyType.FullName)).ToList();

        var doSanitizeProperty = false;
        typeProperties.ForEach(typeProperty =>
        {
            if (doSanitizeProperty == false)
                doSanitizeProperty = ValidateSanitizeProperty(typeProperty.PropertyType, typeProperty, orgTypes);
        });

        return doSanitizeProperty;

    }

    protected override bool CanReadType(Type type)
    {
        var result = ValidateSanitizeProperty(type, null, new List<PropertyInfo>());
        return result;
    }

    private object SanitizeObject(object obj, Type modelType)
    {
        if (obj != null)
        {
            List<PropertyInfo> propertiesFlaggedForSanitization = modelType.GetProperties().Where(e => e.GetCustomAttribute<SanitizePropertyAttribute>() != null).ToList();
            if (propertiesFlaggedForSanitization.Any())
            {
                foreach (var propertyInfo in propertiesFlaggedForSanitization)
                {
                    var raw = (string)propertyInfo.GetValue(obj);
                    if (!string.IsNullOrEmpty(raw))
                    {
                        propertyInfo.SetValue(obj, CleanInput(raw));
                        //propertyInfo.SetValue(obj, AntiXssEncoder.HtmlEncode(raw, true));
                        //propertyInfo.SetValue(obj, AntiXssEncoder.UrlEncode(raw));
                    }
                }
            }
        }

        modelType.GetProperties().ToList().Where(_ => _.PropertyType.IsAnsiClass == true && !ExcludeTypes.Contains(_.PropertyType.FullName)).ToList().ForEach(property =>
        {
            try
            {
                var nObj = property.GetValue(obj);
                if (nObj != null)
                {
                    var sObj = SanitizeObject(nObj, property.PropertyType);
                    property.SetValue(obj, sObj);
                }
            }
            catch(Exception ex)
            {   
            }
        });

        return obj;
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (encoding == null)
        {
            throw new ArgumentNullException(nameof(encoding));
        }

        using (var streamReader = context.ReaderFactory(context.HttpContext.Request.Body, encoding))
        {
            string jsonData = await streamReader.ReadToEndAsync();
            var nObj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonData, context.ModelType);
            var modelType = context.ModelType;

            try
            {
                var sbj = SanitizeObject(nObj, modelType);

                return await InputFormatterResult.SuccessAsync(sbj);
            }catch (Exception ex)
            {
                return await InputFormatterResult.FailureAsync();
            }
        }
    }
}

我们在 startup.cs类的public void ConfigureServices(IServiceCollection服务)函数,如下所示:

services.AddMvcCore(options => { options.InputFormatters.Add(new SanitizeTextInputFormatter()); })