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}");
    }
}
PREVIEWING: aliciascott/DOCS-9725-Cloudcraft