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