다음을 통해 공유


CA5122 P/Invoke declarations should not be safe critical

Item Value
RuleId CA5122
Category Microsoft.Security
Breaking change Breaking

Cause

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.

Note

This rule has been deprecated. For more information, see Deprecated rules.

Rule description

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 might 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.

How to fix violations

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);
   }
}

When to suppress warnings

Do not suppress a warning from this rule.