.NET Framework 2.0 Security Guidelines - Serialization

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Chaitanya Bijwe


Do not serialize sensitive data

If you must serialize your class and it contains sensitive data, avoid serializing the fields that contain the sensitive data. Either implement ISerializable to control the serialization behavior or decorate fields that contain sensitive data with the [NonSerialized] attribute. By default, all private and public fields are serialized. This is important because serialization places the data in memory, often in preparation for sending it over a network, making it easier for an attacker to gain access to it.

The following example shows how to use the [NonSerialized] attribute to ensure that a specific field which contains sensitive data cannot be serialized.


[Serializable]
public class Employee {
 // OK for name to be serialized
 private string name;
 // Prevent salary being serialized
 [NonSerialized] private double annualSalary;
 . . .
}
 

Alternatively, implement the ISerializable interface and explicitly control the serialization process. If you must serialize the sensitive item or items of data, consider encrypting the data first. The code that de-serializes your object must have access to the decryption key.


Validate serialized data streams

Serialized data should not be considered trusted data. Subject it to the same level of scrutiny that you would subject any other untrusted file, network, or user input. To avoid potentially damaging data being injected into the object, validate each field as it is reconstituted as shown in the following example.


public void DeserializationMethod(SerializationInfo info, StreamingContext cntx)
{
 string someData = info.GetString("someName");
 // Use input validation techniques to validate this data.
}
Personal tools