Search code examples
c#serializationbinaryformatter

BinaryFormatter deserialise malicious code?


I've heard there are safety questions over the BinaryFormatter.

I send user-generated files to the server from the client. These are serialized classes that are then read by the server.

From my understanding of the above link, this is dangerous. But I've tried sending disposable classes, and even tried a class that implemented ISerilizable. But both were rejected due to the server not knowing the source assembly.

[Serializable]
public class Ship : ISerializable
{
    public Ship()
    {

    }

    public Ship(SerializationInfo info, StreamingContext context)
    {
        Console.WriteLine("test");
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {

    }
}

So how could a client successfully get code into my server via this vector? By faking the namespace name and public key causing the server to try deserialise it, thus running the above code? Or are there more subtle ways to do it?

This feature is a core fundamental to my game unfortunately so I want to be careful.


Solution

  • Serialization works on data, not code. A deserializer extracts the data from the payload you provide, consturcts a new object instance and sets the object's values from the extracted data. It does NOT extract any code from the payload.

    If your code is vulnerable to malicious input in the first place, then yes, deserialization could be another way to attack it - just like any other way of injecting malicious data.

    For example, if you construct SQL statements by concatenating strings, you will be vulnerable to SQL injection attack whether the strings come from user input or deserialized data. The way to fix this is to use parameterized queries, not avoid deserialization or try to sanitize the user's input.

    In any case the answers to the original post were mostly speculation, comments on Java serialization that's not really relevant to .NET or really contrived examples.