Skip to content

Serialization Constructor

Serialization Constructor should be protected

What does this mean ?

Because serialization constructors allocate and initialize objects, the same security tests that apply to normal constructors must also apply to serialization constructors. When a type implements the System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, is defined in an assembly that supports partly trusted callers, and has a constructor that accepts a System.Runtime.Serialization.Serializable object and a System. Runtime.Serialization.Streaming Context object that is not protected by a security check but is secured by one or more of the type's usual constructors.

What can happen ?

Failure to do so would allow callers who could not ordinarily create an instance to do so by using the serialization constructor.

Recommendation

Security checks that are present on standard constructors must also be included on a serialization constructor.

Sample Code

Vulnerable :

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 MyLibrary
{
    [Serializable]
    public class Foo : ISerializable
    {
        private int n;

        [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
        public Foo()
        {
          n = -1;
        }

        protected Foo(SerializationInfo info, StreamingContext context) // Noncompliant
        {
          n = (int)info.GetValue("n", typeof(int));
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
          info.AddValue("n", n);
        }
    }
}

Non Vulnerable :

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 MyLibrary
{
    [Serializable]
    public class Foo : ISerializable
    {
        private int n;

        [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
        public Foo()
        {
          n = -1;
        }

        [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
        protected Foo(SerializationInfo info, StreamingContext context)
        {
          n = (int)info.GetValue("n", typeof(int));
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
          info.AddValue("n", n);
        }
    }
}

References