Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityPermission in a Serializable Method in C#

What is the importance of using SecurityPermission in a Serializable class?

In an article on [Microsoft's Site][1], they suggest that you write a Serializable class as follows:

[Serializable]
public class PleaseSaveMe : ISerializable
{
    public readonly int Age;
    public readonly string Name;
    public int KarateSkills;

    public PleaseSaveMe(int Age, string Name)
    {
        this.Age  = Age;
        this.Name = Name;
    }

    // Serialization Methods
    protected PleaseSaveMe(SerializationInfo info, StreamingContext context)
    {
        Age = info.GetInt32("Age");
        Name = info.GetString("Name");
        KarateSkills = info.GetInt32("KarateSkills");
    }

    [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)]
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Age", Age);
        info.AddValue("Name", Name);
        info.AddValue("KarateSkills", KarateSkills);
    }
}

But in the documentation of SecurityAction.LinkDemand, it says specifically to NOT use it in .NET 4.0 (which is what I am using). What should I use instead? Is that attribute even necessary?

William

like image 500
William Avatar asked May 08 '12 16:05

William


1 Answers

Well, with the [Serializable] attribute, you explicitly permit code to mess with your private parts. Without the security attribute, any code running in your process could create an instance of your class that is deserialized from data that wasn't necessarily saved by your serialization code. Possibly creating an object of your class that is in an inconsistent state that might thus be exploitable.

With the attribute, you can explicitly deny code that you don't trust well enough to do this. Which of course is a Good Thing.

And yes, CAS was deprecated in .NET 4, largely because so many programmers had basic questions like yours. CAS is definitely hard to understand and security that's difficult to comprehend is usually unsecure. It was replaced by a sandboxing model, the MSDN article is here. A backgrounder magazine article is here. In general, you only worry about this when you permit code to load in your process that came from a source you can't control or trust. Think plugins or insufficiently secured storage locations for assemblies.

like image 170
Hans Passant Avatar answered Oct 09 '22 00:10

Hans Passant