共用方式為


CA2120:必須保護序列化建構函式

型別名稱

SecureSerializationConstructors

CheckId

CA2120

分類

Microsoft.Security

中斷變更

中斷

原因

型別會實作 ISerializable 介面、不是委派 (Delegate) 或介面,而且會在允許有部分信任呼叫端的組件中宣告。該型別具有採用 SerializationInfo 物件和 StreamingContext 物件 (序列化建構函式的簽章) 的建構函式。這個建構函式未受到安全性檢查的保護,但型別中有一個或多個規則建構函式是受到保護的。

規則描述

此規則會與支援自訂序列化的型別相關。如果型別會實作 ISerializable 介面,就表示會支援自訂序列化。您需要有序列化建構函式,用以還原序列化或是重新建立已使用 ISerializable.GetObjectData 方法序列化的物件。因為序列化建構函式會配置和初始化物件,所以序列化建構函式上同樣必須存在標準建構函式上的安全性檢查。如果您違反此規則,無法以其他方式建立執行個體的呼叫端就會利用序列化建構函式以建立執行個體。

如何修正違規

若要修正此規則的違規情形,請以保護其他建構函式的相同安全性要求,保護序列化建構函式。

隱藏警告的時機

請勿隱藏此規則的違規。

範例

下列範例顯示違反規則的型別。

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:請實作序列化建構函式

CA2237:必須以 SerializableAttribute 標記 ISerializable 類型

請參閱

參考

ISerializable

SerializationInfo

StreamingContext