3

I have read in multiple places that the correct way to prevent XSS is not to sanitize the input, but instead html encode the output before displaying it.

However, I think I have come across the exception to the rule. I have some data that will be stored in a database that is consumed by other legacy applications that I don't have control over and these applications may or may not be encoding the output.

1
  • 1
    I'd just come across this post and was interested in why you wouldn't sanitise your inputs. It turns out, after a bit of Googling, that the reason is so that you're not restricting use of your data by encoding it for one use (i.e. display in HTML). By letting the data hit the database in it's raw state, you can add APIs and use the data in other ways without having to reverse the HTML encoding. Commented Apr 28, 2016 at 9:08

1 Answer 1

5

First create an ActionFilterAttribute:

using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Microsoft.Security.Application;

/// <summary>
/// Sanitizes (HTML encodes) all strings on the model.
/// </summary>
/// <remarks>Use sparingly. Ideally don't use this and instead encode when outputting the values.
/// This is used because we don't have control of other applications that may consume the data.</remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class SanitizeInputAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ActionArguments != null && actionContext.ActionArguments.Count == 1)
        {
            var requestParam = actionContext.ActionArguments.First();
            var properties = requestParam.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(x => x.CanRead && x.CanWrite && x.PropertyType == typeof(string) && x.GetGetMethod(true).IsPublic && x.GetSetMethod(true).IsPublic);
            foreach (var propertyInfo in properties)
            {
                propertyInfo.SetValue(requestParam.Value, Encoder.HtmlEncode(propertyInfo.GetValue(requestParam.Value) as string));
            }
        }
    }
}

Then simply register it on the class or action like this:

[HttpPost]
[SanitizeInput]
public Response Post(Object model)
{...}
1
  • You need also decode when you pass data back to client. Owervise the data will be Encoded each time when pass data. forums.asp.net/t/…
    – Slava
    Commented Sep 7, 2015 at 14:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.