Using SuppressUnmanagedCodeSecurityAttribute

There is a performance aspect to asserting and then calling unmanaged code. For every such call, the security system automatically demands unmanaged code permission, resulting in a stack walk each time. If you assert and immediately call unmanaged code, the stack walk can be meaningless: it consists of your assert and your unmanaged code call.

A custom attribute called SuppressUnmanagedCodeSecurityAttribute can be applied to unmanaged code entry points to disable the normal security check that demands SecurityPermission with UnmanagedCode permission specified. Extreme caution must always be taken when doing this, because this action creates an open door into unmanaged code with no runtime security checks. It should be noted that even with SuppressUnmanagedCodeSecurityAttribute applied, there is a one-time security check that happens at just-in-time (JIT) compilation to ensure that the immediate caller has permission to call unmanaged code.

If you use the SuppressUnmanagedCodeSecurityAttribute, check the following points:

  • Make the unmanaged code entry point internal or otherwise inaccessible outside your code.

  • Any call into unmanaged code is a potential security hole. Make sure your code is not a portal for malicious code to indirectly call into unmanaged code and avoid a security check. Demand permissions, if appropriate.

  • Use a naming convention to explicitly identify when you are creating a dangerous path into unmanaged code, as described in Naming Convention for Unmanaged Code Methods.

Show: