0

I have a code that takes messages of any type and serialize them into the DB, while saving the type of the message and the serialized json string. I have a side process that should deserialize the messages later on and send them to the queue.

To perform the serialization and deserialization I use JsonConvert of Newtonsoft.Json:

  1. For deserialization I use the following method:
object? DeserializeObject(string value, Type type)
  1. For serialization I use the following method:
string SerializeObject(object? value)

I have the following questions:

A. I saw that in case DeserializeObject receives a wrong type name it still deserialize the object but his type is Newtonsoft.Json.Linq.JObject and not the type I passed into the method, I expected it will throw an exception, this behavior is very bad for us, is there any way to cause the deserialize to throw exception in this scenario?

B. Is the code below secured? I saw that the library has variabilities such as depicted here

private void StackOverflowQuestion()
{
   Bus.Employees.Messages.LevelCreated levelCreated = new Bus.Employees.Messages.LevelCreated
   {
      Name = "director",
   };

   //var messageType = levelCreated.GetType().AssemblyQualifiedName;
   string messageData = JsonConvert.SerializeObject(levelCreated);

   //Deserialize with type that is not correct
   object deserializeMessaged = DeserializeMessage("my cool type which does not exists!", messageData);
   string theType = deserializeMessaged.GetType().FullName;//theType = Newtonsoft.Json.Linq.JObject
}

private object DeserializeMessage(string messageType, string messageSerializedData)
{
   Type type = Type.GetType(messageType);
   return JsonConvert.DeserializeObject(value: messageSerializedData, type);
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • B. The danger in deserializing a type received via a message is in construction of an unwanted and unexpected ***attack gadget***. See [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182) and [External json vulnerable because of Json.Net TypeNameHandling auto?](https://stackoverflow.com/q/49038055/3744182). Your risk here is the same as using `JsonConvert.DeserializeObject()` with [`TypeNameHandling.All`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm) enabled. – dbc Oct 14 '21 at 00:44
  • A. Is a separate, unrelated question. The rule on stack overflow is to ask [one question per post](https://meta.stackexchange.com/q/222735), so you should ask another question. – dbc Oct 14 '21 at 00:46
  • For more on attack gadgets in .NET see https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf – dbc Oct 14 '21 at 00:47

0 Answers0