Alex Rivera | Logout

Json.NET SerializeObject escape values to prevent XSS

Asked 2012-05-25T14:29:25.170
30

Using Json.NET

JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" })

returns

{"Property":"<script>alert('o hai');</script>"}

Is it possible for the value to be escaped by SerializeObject to prevent a hostile script from executing? I'd prefer not to make changes to the object itself.

Edit: Ideally I'd like to integrate the sanitizing into the SerializeObject call without having to process the object before or after SerializeObject.

Edit: The string output from JsonConvert.SerializeObject is assigned to a global variable in a script block, which I believe is where the XSS issue is.

Edit
Report

1 Answer

18

This may not be ideal but this is my solution (for now, at least):

JsonConvert.SerializeObject(new { Property = "<script>alert('o hai');</script>" }, new HtmlEncodeStringPropertiesConverter());

with a simple JsonConverter that performs HtmlEncode on the value if it is a string

public class HtmlEncodeStringPropertiesConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(Encoder.HtmlEncode(value.ToString()));
    }
}

(Encoder is Microsoft.Security.Application.Encoder from the AntiXSS library)

answered 2012-05-29T18:15:14.520

Your Answer