次の方法で共有


CA2120: Secure serialization constructors

Item Value
RuleId CA2120
Category Microsoft.Security
Breaking change Breaking

Cause

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.

Note

This rule has been deprecated. For more information, see Deprecated rules.

Rule description

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

How to fix violations

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

When to suppress warnings

Do not suppress a violation of the rule.

Example

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

 }

CA2229: Implement serialization constructors

CA2237: Mark ISerializable types with SerializableAttribute

See also