Export (0) Print
Expand All
Expand Minimize

CA5122 P/Invoke declarations should not be safe critical

Visual Studio 2013

TypeName

PInvokesShouldNotBeSafeCriticalFxCopRule

CheckId

CA5122

Category

Microsoft.Security

Breaking Change

Breaking

A P/Invoke declaration has been marked with a SecuritySafeCriticalAttribute:

[assembly: AllowPartiallyTrustedCallers]

// ...
public class C
{
    [SecuritySafeCritical]
    [DllImport("kernel32.dll")]
    public static extern bool Beep(int frequency, int duration); // CA5122 – safe critical p/invoke
   }

In this example, C.Beep(...) has been marked as a security safe critical method.

Methods are marked as SecuritySafeCritical when they perform a security sensitive operation, but are also safe to be used by transparent code. One of the fundamental rules of the security transparency model is that transparent code may never directly call native code through a P/Invoke. Therefore, marking a P/Invoke as security safe critical will not enable transparent code to call it, and is misleading for security analysis.

To make a P/Invoke available to transparent code, expose a security safe critical wrapper method for it:

[assembly: AllowPartiallyTrustedCallers

class C
{
   [SecurityCritical]
   [DllImport(“kernel32.dll”, EntryPoint=”Beep”)]
   private static extern bool BeepPinvoke(int frequency, int duration); // Security Critical P/Invoke

   [SecuritySafeCritical]
   public static bool Beep(int frequency, int duration)
   {
      return BeepPInvoke(frequency, duration);
   }
}

Do not suppress a warning from this rule.

Show:
© 2014 Microsoft