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.
usingSystem;usingSystem.IO;usingSystem.Runtime.Serialization.Formatters.Binary;[Serializable]publicclassUser{publicstringUsername{get;set;}publicstringPassword{get;set;}}classProgram{staticvoidMain(string[]args){// Serializing the objectUseruser=newUser{Username="admin",Password="password123"};BinaryFormatterformatter=newBinaryFormatter();using(FileStreamstream=newFileStream("user.dat",FileMode.Create)){formatter.Serialize(stream,user);}// Deserializing the objectusing(FileStreamstream=newFileStream("user.dat",FileMode.Open)){UserdeserializedUser=(User)formatter.Deserialize(stream);Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");}}}
Compliant Code Examples
usingSystem;usingSystem.IO;usingSystem.Text.Json;[Serializable]publicclassUser{publicstringUsername{get;set;}publicstringPassword{get;set;}}classProgram{staticvoidMain(string[]args){// Serializing the objectUseruser=newUser{Username="admin",Password="password123"};varoptions=newJsonSerializerOptions{WriteIndented=true};stringjsonString=JsonSerializer.Serialize(user,options);File.WriteAllText("user.json",jsonString);// Deserializing the objectstringreadJsonString=File.ReadAllText("user.json");UserdeserializedUser=JsonSerializer.Deserialize<User>(readJsonString);Console.WriteLine($"Username: {deserializedUser.Username}, Password: {deserializedUser.Password}");}}
シームレスな統合。 Datadog Code Security をお試しください
Datadog Code Security
このルールを試し、Datadog Code Security でコードを解析する
このルールの使用方法
1
2
rulesets:- csharp-security # Rules to enforce C# security.