Strengthen Json Injection in .NET.

I am using Newtonsoft.Json to deserialize a json string, but fortify complained that I am using unvalidated json. Then I added the check using Newtonsoft.Json.Schema, but now it 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 tips on how to check a Json string?

On line 23, the DeserializeObject () method writes unvalidated input to JSON. This call may allow an attacker to insert arbitrary elements or attributes into a JSON object.

+7
source share
3 answers

Apologizing for the late reply, I managed to fix / trick the fortification. 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

+10
source

It appears that in your case, Fortify complains that you are using json from an untrusted source, this is what the Fortify documentation says:

The semantics of documents and JSON messages can be changed if the application creates JSON from unapproved input. In a relatively benign case, an attacker can insert extraneous elements that cause the application to throw an exception when parsing a JSON document or request. In a more serious case, for example, using JSON injection, an attacker can insert extraneous elements that allow the predictable manipulation of business-critical values ​​in a document or JSON request.

If you get json from a web service that you own, you can probably ignore the Fortify warning. However, keep in mind that you are calling JArray.Parse() on the input and assume that it will be a valid array, but if it is not, you will get a JsonReaderException . Also, you really don't check JSON for a schema, please see the JSON.NET example to find out how to specify a JSON schema.

Honestly, I would be interested to know how Fortify expects it to be able to verify the JSON received from third-party web services.

+4
source

If someone is still looking for a solution, I did the following, and this seems to work as expected.

1 Get a sample JSON and output the circuit using online tools.

2 Add a separate method to validate JSON before parsing or deserializing it.

3 After verifying the JSON using the schema, then go on to the normal operation, whatever you want to do.

0
source

All Articles