CA2120: Secure serialization constructors


For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

For the latest documentation on Visual Studio 2017, see CA2120: Secure serialization constructors on

Breaking ChangeBreaking

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 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.

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

Do not suppress 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
    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);


CA2229: Implement serialization constructors

CA2237: Mark ISerializable types with SerializableAttribute