Search code examples
c#code-access-security

Confusion regarding code access security with unverifiable code


I am confused about what I need to do in order to correctly "set up" my unverifiable method so that it conforms to code access security guidelines.


Given the following method

[MethodImpl(MethodImplOptions.ForwardRef)]
private extern void DoStuffUnverifiable();

which is deemed unverifiable by PEVerify, what attributes do I absolutely need to apply to the method definition?

  • [SecurityCritical]?
  • [SecuritySafeCritical]?

How do I decide between those two? Further,

  • do I need to set [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]?
  • If so, do I use SecurityAction.Demand or something else?

Are there any other attributes I definitely need to apply? Are there any that I could apply, although not neccessary?


Solution

  • In the transparency model, security-critical methods are marked with the [SecurityCritical] attribute:

    [SecurityCritical]
    public Key GetTVRoomKey() { ... }
    

    All “dangerous” methods (containing code that the CLR considers could breach security and allow an inmate to escape) must be marked with [SecurityCritical] or [SecuritySafeCritical]. This comprises:

    • Unverifiable (unsafe) methods
    • Methods that call unmanaged code via P/Invoke or COM interop

    • Methods that Assert permissions or call link-demanding methods

    • Methods that call [SecurityCritical] methods

    • Methods that override virtual [SecurityCritical] methods

    [SecurityCritical] means “this method could allow a partially trusted caller to escape a sandbox”. [SecuritySafeCritical] means “this method does security-critical things—but with appropriate safeguards and so is safe for partially trusted callers”.


    So yes, in your case - [SecurityCritical] is surely needed, if you want extra safety, use [SecuritySafeCritical]