.NET Framework 1.1 Security Guidelines - Serialization

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

Do Not Serialize Sensitive Data

Ideally, if your class contains sensitive data, do not support serialization. If you must be able to serialize your class and it contains sensitive data, avoid serializing the fields that contain the sensitive data. To do this, 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.

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

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

When you create an object instance from a serialized data stream, do not assume the stream contains valid data. To avoid potentially damaging data being injected into the object, validate each field as it is reconstituted as shown in the following code sample.

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

For more information about input validation techniques, see "Input Validation" in Chapter 10, "Building Secure ASP.NET Pages and Controls." at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh10.asp

Personal tools