PrincipalPermission and Finalizers


Nicole Calinoiu, one of our developer security MVPs, has just posted a good description of the problems that occur when using PrincipalPermission with impersonation and finalizers.  The key thing to take away from this is that impersonation occurs on a per-thread basis and finalizers run on a thread that the GC controls, not on the main thread of your application.  This means that if you’re impersonating on your application’s thread, your finalizers will not run under the impersonated context.


While Nicole gives a general solution to the problem, she also points out that if you’re doing something that requires impersonation on the finalizer thread you might want to think about the design of your class.  Definitely worth a read.

Comments (3)

  1. chris seary says:

    The article mentions using PrincipalPermission attributes.

    Wouldn’t it be better to use a programmatic call to the principal permission class, rather than using attributes?

    Two problems with attributes:

    they don’t do much error trapping – the full security exception is thrown back to the caller, holding a lot of potentially useful info to a hacker

    you can’t change the domain part of the role or user name in an attribute (eg. "MYDOMAINuser" – this means you can’t move your code to different environments without recompiling (eg. moving from test to production)

  2. shawnfa says:

    Hi Chris,

    There are certainly tradeoffs between using imperative and declarative security. Depending upon your requirements you certainly might want to be using imperative security instead.

    -Shawn

  3. chris seary says:

    Actually, thinking about this, it may be an idea to wrap the principal permission (and its attribute) in new permission classes that both:
    logs the exception and throws a vanilla exception;
    allows appending of the domain part of the user or role name.