Thursday, March 23, 2006

RE: Viewing SecurityExceptions

Shawn Farkas notes here that you can't display some of the information available in SecurityException when not running in fully trusted code (like an ASP.Net host). Then along comes Dominick Baier with the fix. I smell a setup.

In any case, the trick is to put a fully-trusted assembly (in the GAC, of course!) to handle the extraction of this information, and pass the unmangled SecurityException in. If the trusted assembly's method asserts the needed ControlEvidence and ControlPolicy then you can get the extra goodies in ToString().
Cool!

using System;
using System.Security.Permissions;
using System.Security;

[assembly: AllowPartiallyTrustedCallers]
namespace LeastPrivilege
{
  [
   SecurityPermission(SecurityAction.Assert, 
   ControlEvidence=true, ControlPolicy=true)
  ]

  public class SecurityExceptionViewer
  {
    public static string[] ViewException(SecurityException ex)
    {
      return new string[] {
        ex.ToString(),
        ex.Demanded.ToString(),
        ex.GrantedSet.ToString() 
      };
    }
  }
}
[Via www.leastprivilege.com]

1 comment:

Anonymous said...

it does not necessarily need to be in the GAC - you could also use ~/bin and write a policy file that grants the assembly the necessary permission..

GAC is just the easiest...