Search code examples
c#jsonjson.netfortify

Fortify Json Injection in .NET


I am using Newtonsoft.Json for deserializing a json string but fortify complained that I am using unvalidated json. i then added a check using Newtonsoft.Json.Schema but it now complains even more

var schema = JsonSchema.Parse(JsonConvert.SerializeObject(typeof(T)));
JToken token = JArray.Parse(json); -- Vulnerability
IList<string> errors;
if (token.IsValid(schema, out errors))
{
    return JsonConvert.DeserializeObject<T>(json); -- Vulnerability
}

Any advice on how to validate Json string?

On line 23 of , the method DeserializeObject() writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.


Solution

  • Apologies for the late response, I managed to fix/deceive fortify. Here is the fix

    byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
    using (var stream = new MemoryStream(jsonBytes))
    {
        output = Deserialize<List<T>>(stream);
    }
    
     public TResult Deserialize<TResult>(Stream responseStream)
        {
            using (var sr = new StreamReader(responseStream))
            {
                using (var reader = new JsonTextReader(sr))
                {
                    var serializer = new JsonSerializer
                    {
                        MissingMemberHandling =
                            EnforceMissingMemberHandling ? MissingMemberHandling.Error : MissingMemberHandling.Ignore,
                        NullValueHandling = IgnoreNullValues ? NullValueHandling.Ignore : NullValueHandling.Include
                    };
    
                    return serializer.Deserialize<TResult>(reader);
                }
            }
        }
    

    Hope this helps someone