Hidden variable in closure in .Net

145 views Asked by At

I have some C# code. It has some configuration settings that stored as auto property or private fields. In theory the person who uses it can modify private variables via Reflection.

Is there a way to deny it? I can use readonly static fields, and then they can't be modified. But the reference to that class itself still can be replaced to another one with malicious settings.

I thought about anonymous method and variable in closures. But in that case, the link to that delegate still can be replaced.

Also I've tried to specify SecurityCriticalAttribute for my fields, as caller may not have FullTrust access, but seems it doesn't verify access for fields. Just for methods\classes itselfs

UPDATE

I fixed it in such way:

  • Initialize all variables via constructor
  • All variables has readonly definition
  • I've added CAS attribute to constructor, so no one without FullTrust can't modify it

    [PermissionSetAttribute(SecurityAction.Demand, Unrestricted = true)]
    

So to update variables, a user needs to create new instance of that class. And then CAS validation will verify caller.

I don't like this approach too much, and if you have better way, I'll appreciate it

1

There are 1 answers

1
Nicole Calinoiu On BEST ANSWER

Unfortunately, the readonly modifiers on your fields will not prevent post-construction modification via reflection. There is no way to prevent code with private reflection permissions from making modifications to in-memory application state. In fact, ReflectionPermission is considered one of the "dangerous" permissions, for which a grant is essentially analogous to a full trust grant (http://msdn.microsoft.com/en-us/library/wybyf7a0.aspx).

In other words, you might as well not bother sandboxing at all if you're going to grant private reflection permissions in the sandbox...