Export (0) Print
Expand All

Secure serialization constructors

TypeName

SecureSerializationConstructors

CheckId

CA2120

Category

Microsoft.Security

Breaking Change

Breaking

The type implements the System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, and is declared in an assembly that allows partially trusted callers. The type has a constructor that takes a System.Runtime.Serialization.SerializationInfo object and a System.Runtime.Serialization.StreamingContext object (the signature of the serialization constructor). This constructor is not secured by a security check, but one or more of the regular constructors in the type is secured.

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 System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) 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.

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

Do not exclude a violation of the rule.

The following example shows a type that violates the rule.

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);
        }
    }

 }

Community Additions

ADD
Show:
© 2014 Microsoft