다음을 통해 공유


CA5122 P/Invoke declarations should not be safe critical

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName PInvokesShouldNotBeSafeCriticalFxCopRule
CheckId 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.

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

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.