Do not use BinaryFormatter as it is insecure and vulnerable

Metadata

ID: csharp-security/avoid-binary-formatter

Language: C#

Severity: Error

Category: Security

CWE: 502

Description

This rule prevents the usage of BinaryFormatter for serialization due to its inherent security vulnerabilities. BinaryFormatter has been found to be susceptible to deserialization attacks, where a malicious actor can control the input to the deserialization operation and exploit this to execute arbitrary code, manipulate program execution, or induce application crashes.

This security risk makes it crucial to avoid BinaryFormatter. Instead, opt for safer alternatives for serialization and deserialization. An alternative is System.Text.Json, which is not only secure, but also offers better performance. Additional alternatives include DataContractSerializer, MessagePack, and protobuf-net.

Learn More:

Non-Compliant Code Examples

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Serializing the object
        User user = new User { Username = "admin", Password = "password123" };
        BinaryFormatter formatter = new BinaryFormatter();

        using (FileStream stream = new FileStream("user.dat", FileMode.Create))
        {
            formatter.Serialize(stream, user);
        }

        // Deserializing the object
        using (FileStream stream = new FileStream("user.dat", FileMode.Open))
        {
            User deserializedUser = (User)formatter.Deserialize(stream);
            Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");
        }
    }
}

Compliant Code Examples

using System;
using System.IO;
using System.Text.Json;

[Serializable]
public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // Serializing the object
        User user = new User { Username = "admin", Password = "password123" };
        var options = new JsonSerializerOptions { WriteIndented = true };

        string jsonString = JsonSerializer.Serialize(user, options);
        File.WriteAllText("user.json", jsonString);

        // Deserializing the object
        string readJsonString = File.ReadAllText("user.json");
        User deserializedUser = JsonSerializer.Deserialize<User>(readJsonString);

        Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis