C#
BinaryFormatter
BinaryFormatter is a class available in .NET to serialize an object, or a graph of them, into a binary format. We will create a class that will be serialized and then read back, and another class that won’t be serialized.
|
|
Notice how LogWriter
writes the logs when it’s disposed. If we change the SerializableClass.dat to instead be a serialization of a modified version of LogWriter
, we can write a file with the contents we want anywhere the program has write access to.
I’ll change the following:
private string _path = "C:/log2.txt";
public string Contents { get; set; } = "Hello"
I will then serialize the file as SerializableClass.dat. When the program runs it will try to deserialize the file, an exception will be thrown when trying to cast the object to SerializableClass
. This will lead to the Dispose method being called, and thus we will write “Hello” into “C:/log2.txt”.
Json.NET
When using Json.NET, some ways of doing deserialization can lead to code execution.
This is an issue if you use TypeNameHandling setting with a value other than None
and try to deserialize JSON using either:
- a dynamic type
- an object type
- the non generic version of DeserializeObject
Here’s some JSON that will open a calculator:
|
|
We could run any application, and there are other ways to do it. In this case we used the ObjectDataProvider
class.
|
|
This is not a security issue in Json.NET, but it shows how improper configuration can lead to code execution.
Conclusion
Deserialization attacks are a real risk if you deserialize untrusted data, and some forms of it such as BinaryFormatter are inherently unsafe.
You can mitigate this by signing files, and for Json.NET, never using TypeNameHandling
in the aforementioned ways.