CS.SV.SER_CTOR

Secure serialization constructors.

This rule is relevant for types that support custom serialization. A type supports custom serialization if it implements the System.Runtime.Serialization.ISerializable interface. The serialization constructor is required and is used to de-serialize, or re-create objects that have been serialized using the ISerializable.GetObjectData method. Because the serialization constructor allocates and initializes objects, security checks that are present on regular constructors must also be present on the serialization constructor. If you violate this rule, callers that could not otherwise create an instance could use the serialization constructor to do this.

Mitigation and prevention

To fix a violation of this rule, protect the serialization constructor with security demands that are identical to those protecting other constructors.

Vulnerable code example

Copy
 using System;
 using System.IO;
 using System.Runtime.Serialization;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.Security;
 using System.Security.Permissions;
 
 [assembly: AllowPartiallyTrustedCallersAttribute()]
 namespace SecurityRulesLibrary
 {   
     [Serializable]
     public class SerializationConstructorsRequireSecurity : ISerializable 
     {
         private   int n1;
         // This is a regular constructor secured by a demand.
         [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
         public SerializationConstructorsRequireSecurity ()
         {
            n1 = -1;
         }
         // This is the serialization constructor. 
         // Violates rule: SecureSerializationConstructors. 
         protected SerializationConstructorsRequireSecurity (SerializationInfo info, StreamingContext context)
         {
            n1 = (int) info.GetValue("n1", typeof(int));
         }
         void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
         {
            info.AddValue("n1", n1);
         }
     }
 
  }

The example shows a type that violates the rule.