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}");}}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- csharp-security # Rules to enforce C# security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines