Rules / C#
SHIELD-CSHARP-006
Insecure deserialization via BinaryFormatter and similar formatters
What it detects
BinaryFormatter or a comparable formatter Deserialize call allows arbitrary type instantiation and remote code execution.
How to fix
Replace BinaryFormatter and similar formatters with a safe serializer such as System.Text.Json without type name handling.
Vulnerable — Shield flags thisSessionLoader.cs
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class SessionLoader
{
public Order Load(Stream stream)
{
return (Order)new BinaryFormatter().Deserialize(stream);
}
}
Fixed — scans cleanSessionLoader.cs
using System.Text.Json;
public class SessionLoader
{
public Order Load(string json)
{
return JsonSerializer.Deserialize<Order>(json);
}
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CSHARP-006, the fixed one does not.