How does .NET security really work?

I just saw this question:

Understanding the .NETA "SecurityAction" parameter for permissions

And I have a question. With the following code:

private void button1_Click(object sender, EventArgs e)
{
    Layer1();
    MessageBox.Show("OK");
}

private void Layer1()
{
    try
    {
        Layer2();
    }
    catch (SecurityException)
    {
        MessageBox.Show("Caught");
    }
    Layer2b();
}

private void Layer2()
{
    new System.Security.Permissions.FileIOPermission(PermissionState.Unrestricted).Deny();
    GC.Collect();
    Layer3();
}

private void Layer2b()
{
    Layer3();
}

[FileIOPermission(SecurityAction.LinkDemand, Write=@"C:\temp")]
private void Layer3()
{
    using (FileStream stream = new FileStream(@"C:\temp\test.txt", FileMode.Create))
    {
    }
}

      

why is the code throwing a security exception with a call Layer2

? How the permission object is handled, I would assume that the garbage collector will destroy the object since I don't have an active reference to it, but the code says Caught and then OK, so it's clear that the permission denied is in effect to be called through Layer2.

What gives? What am I missing? I admit that I am a newbie when it comes to security / permissions in .NET, so forgive me if this question is really basic.

Is it a security permission or denial, like this flag, stack or whatever? Otherwise, why doesn't it work for Layer2b? This is the same thread, so clearly, until it is killed by garbage collection, it gets deleted / destroyed / cleaned up at some point.

+1


source to share


2 answers


Calling .Deny () on CodeAccessPermission will cause the .NET Security runtime to set the deny flag on the security object for the current frame stack for that permission. So even if you call GC.Collect () after calling .Deny () it doesn't really matter, the resolution will remain in effect. A permission object is simply a representation of the state of a piece of the .NET runtime at a point in time (a stack frame).



Just use .NET Reflector to find out more.

+3


source


On first viewing, I would assume the permission object is still in scope, since it is defined inside the method, it falls out of scope after the Layer2 method completes, allowing the last line of your application to be used.



As noted by the accepted answer, this is because it is in the scope of the current stack, which is in the scope of a standard object, you just do not control the link. This is the best way to remember him.

0


source







All Articles