CA2151: Fields with critical types should be security critical

Item Value
RuleId CA2151
Category Microsoft.Security
Breaking change Breaking

Cause

A security transparent field or a safe critical field is declared. Its type is specified as security critical. For example:

[assembly: AllowPartiallyTrustedCallers]

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

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

In this example, m_field is a security transparent field of a type that is security critical.

Note

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

Rule description

To use security critical types, the code that references the type must be either security critical or security safe critical. This is true even if the reference is indirect. For example, when you reference a transparent field that has a critical type, your code must be either security critical or security safe. Therefore, having a security transparent or security safe critical field is misleading because transparent code will still be unable to access the field.

How to fix violations

To fix a violation of this rule, mark the field with the SecurityCriticalAttribute attribute, or make the type that is referenced by the field either security transparent or safe critical.

// 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
   }

When to suppress warnings

Do not suppress a warning from this rule.

Code

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