CA2138:透明方法不可以使用 SuppressUnmanagedCodeSecurity 屬性呼叫方法

型別名稱

TransparentMethodsMustNotCallSuppressUnmanagedCodeSecurityMethods

CheckId

CA2138

分類

Microsoft.Security

中斷變更

中斷

原因

安全性透明方法會呼叫標示 SuppressUnmanagedCodeSecurityAttribute 屬性的方法。

規則描述

任何直接呼叫原生程式碼的透明方法都會引發此規則,例如使用透過 P/Invoke (平台叫用) 呼叫。 標記 SuppressUnmanagedCodeSecurityAttribute 屬性的 P/Invoke 和 COM Interop 方法會針對呼叫方法完成 LinkDemand。 由於安全性透明的程式碼無法滿足 LinkDemands,所以程式碼也無法呼叫標示 SuppressUnmanagedCodeSecurity 屬性的方法,或是標示 SuppressUnmanagedCodeSecurity 屬性的類別方法。 此方法將失敗,或要求將轉換為完全要求。

違反這個規則會在層級 2安全性透明模型中導致 MethodAccessException,並且在層級 1 透明模型中導致對 UnmanagedCode 的完整需求。

如何修正違規

若要修正此規則的違規情形,請移除 SuppressUnmanagedCodeSecurityAttribute 屬性,並在方法標記 SecurityCriticalAttributeSecuritySafeCriticalAttribute 屬性。

隱藏警告的時機

請勿隱藏此規則的警告。

範例

using System;
using System.Runtime.InteropServices;
using System.Security;


namespace TransparencyWarningsDemo
{

    public class CallSuppressUnmanagedCodeSecurityClass
    {
        [SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool Beep(uint dwFreq, uint dwDuration);

        public void CallNativeMethod()
        {
            // CA2138 violation - transparent method calling a method marked with SuppressUnmanagedCodeSecurity
            // (this is also a CA2149 violation as well, since this is a P/Invoke and not an interface call).
            Beep(10000, 1);
        }
    }

}