6

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?

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
  • 1
    What is the usage scenario? MethodImplOptions.ForwardRef is quite unusual and normally only appears in C++ code. Which is never verifiable. CAS is unusual as well, deprecated at .NET 4 and replaced by a sandboxing model. – Hans Passant May 23 '19 at 20:53
  • The actual method body is implemented in CIL directly. The CIL is not verifiable, but that is by design. @HansPassant Does the new sandboxing model mean I do not have to annotate the method with any attributes at all? Will security issues automatically be handled by the framework / execution engine? – Thomas Flinkow May 23 '19 at 20:56

1 Answers1

2

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]

Barr J
  • 10,636
  • 1
  • 28
  • 46
  • Thank you very much for your answer! Before also awarding the bounty, I would be very happy if you could answer two more questions that arose when I read your answer: 1. is the "transparency model" the same thing Hans Passant called "sandboxing model"? Is what you describe the up-to-date way of CAS or was it also obsoleted with .NET 4? 2. Do I really need to mark all callers of the `[SecurityCritical]` method `[SecurityCritical]` as well? – Thomas Flinkow May 31 '19 at 07:11