Sdílet prostřednictvím


CA2151: Pole s kritickými typy by měla být kritická pro zabezpečení

TypeName

CheckId

CA2151

Kategorie

Microsoft.Security

Narušující změna

Narušující

příčina

Je deklarováno z hlediska zabezpečení transparentní pole nebo bezpečně kritické pole.Jeho typ je určen jako kritický z hlediska zabezpečení.Příklad:

[assembly: AllowPartiallyTrustedCallers]

   [SecurityCritical]
   class Type1 { } // Security Critical type

   class Type2 // Security transparent type
   {
      Type1 m_field; // CA2151, transparent field of critical type
   }

V tomto příkladu představuje m_field bezpečnostně transparentní pole typu, který je kritický z hlediska zabezpečení.

Popis pravidla

Chcete-li používat typy kritické z hlediska zabezpečení, musí být kód, který odkazuje na typ, buď kritický z hlediska zabezpečení, nebo bezpečně kritický z hlediska zabezpečení.To platí i v případě, že je odkaz nepřímý.Například při odkazu na transparentní pole kritického typu musí být váš kód buď kritický z hlediska zabezpečení, nebo bezpečný z hlediska zabezpečení.Proto je existence transparentního pole kritického z hlediska zabezpečení nebo transparentního pole bezpečně kritického z hlediska zabezpečení zavádějící, jelikož transparentní kód nebude mít k poli přístup.

Jak vyřešit porušení

Chcete-li opravit porušení tohoto pravidla, označte pole s atributem SecurityCriticalAttribute nebo změňte typ, na který se odkazuje v tomto poli, buď na transparentní z hlediska zabezpečení, nebo na bezpečně kritický.

// Fix 1: Make the referencing field security critical
[assembly: AllowPartiallyTrustedCallers]

   [SecurityCritical]
   class Type1 { } // Security Critical type

   class Type2 // Security transparent type
   {
      [SecurityCritical]
      Type1 m_field; // Fixed: critical type, critical field
   }

// Fix 2: Make the referencing field security critical
[assembly: AllowPartiallyTrustedCallers]

   
   class Type1 { } // Type1 is now transparent

   class Type2 // Security transparent type
   {
      [SecurityCritical]
      Type1 m_field; // Fixed: critical type, critical field
   }

Kdy potlačit upozornění

Nepotlačujte upozornění na toto pravidlo.

Kód

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

namespace TransparencyWarningsDemo
{

    public class SafeNativeMethods
    {
        // CA2145 violation - transparent method marked SuppressUnmanagedCodeSecurity.  This should be fixed by 
        // marking this method SecurityCritical.
        [DllImport("kernel32.dll", SetLastError = true)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool Beep(uint dwFreq, uint dwDuration);
    }
}