CA2112: защищенные типы не должны предоставлять поля

Товар Значение
Идентификатор правила CA2112
Категория Microsoft.Security
Критическое изменение Критическое

Причина

Общедоступный или защищенный тип содержит общедоступные поля и защищается запросами ссылки.

Примечание.

Это правило устарело. Дополнительные сведения см. в разделе "Устаревшие правила".

Описание правила

Если код имеет доступ к экземпляру типа, защищенного запросом компоновки, то для получения доступа к полям типа коду не требуется удовлетворять запросу компоновки.

Устранение нарушений

Чтобы устранить нарушение этого правила, сделайте поля неопубликованными и добавьте общедоступные свойства или методы, возвращающие данные поля. Безопасность LinkDemand проверка для типов защищает доступ к свойствам и методам типа. Однако безопасность доступа к коду не применяется к полям.

Когда лучше отключить предупреждения

Как для проблем безопасности, так и для хорошей разработки необходимо устранить нарушения, сделав общедоступные поля неопубликованными. Вы можете отключить предупреждение из этого правила, если поле не содержит сведения, которые должны оставаться защищенными, и вы не полагаетесь на содержимое поля.

Пример

Следующий пример состоит из типа библиотеки () с незащищенными полями, тип (SecuredTypeWithFieldsDistributor), который может создавать экземпляры типа библиотеки и ошибочно передает экземпляры типам не имеют разрешения на их создание, и код приложения, который может считывать поля экземпляра, даже если у него нет разрешения, которое защищает тип.

Следующий код библиотеки нарушает правило.

using System;
using System.Reflection;
using System.Security;
using System.Security.Permissions;

namespace SecurityRulesLibrary
{
   // This code requires immediate callers to have full trust.
   [System.Security.Permissions.PermissionSetAttribute(
       System.Security.Permissions.SecurityAction.LinkDemand, 
       Name="FullTrust")]
   public class SecuredTypeWithFields 
   {
      // Even though the type is secured, these fields are not.
      // Violates rule: SecuredTypesShouldNotExposeFields.
      public double xValue;
      public double yValue;
      
      public SecuredTypeWithFields (double x, double y) 
      {
         xValue = x;
         yValue = y;
         Console.WriteLine(
            "Creating an instance of SecuredTypeWithFields.");
      }
      public override string ToString()
      {
          return String.Format (
            "SecuredTypeWithFields {0} {1}", xValue, yValue);
      }
   }
}

Пример 1

Приложение не может создать экземпляр из-за требования ссылки, которая защищает защищенный тип. Следующий класс позволяет приложению получить экземпляр защищенного типа.

using System;
using System.Reflection;
using System.Security;
using System.Security.Permissions;

// This assembly executes with full trust. 

namespace SecurityRulesLibrary
{
   // This type creates and returns instances of the secured type.
   // The GetAnInstance method incorrectly gives the instance 
   // to a type that does not have the link demanded permission.

   public class Distributor
   {
      static SecuredTypeWithFields s = new SecuredTypeWithFields(22,33);
      public static SecuredTypeWithFields GetAnInstance ()
      {
            return s;
      }

      public static void DisplayCachedObject ()
      {
         Console.WriteLine(
            "Cached Object fields: {0}, {1}", s.xValue , s.yValue);
      }
   }
}

Пример 2

В следующем приложении показано, как без разрешения на доступ к методам защищенного типа код может получить доступ к его полям.

using System;
using System.Security;
using System.Security.Permissions;
using SecurityRulesLibrary;

// This code executes with partial trust.
[assembly: System.Security.Permissions.PermissionSetAttribute(
   System.Security.Permissions.SecurityAction.RequestRefuse,
   Name = "FullTrust")]
namespace TestSecurityExamples
{
    public class TestLinkDemandOnField
    {
        [STAThread]
        public static void Main()
        {
            // Get an instance of the protected object.
            SecuredTypeWithFields secureType = Distributor.GetAnInstance();

            // Even though this type does not have full trust,
            // it can directly access the secured type's fields.
            Console.WriteLine(
               "Secured type fields: {0}, {1}",
               secureType.xValue,
               secureType.yValue);
            Console.WriteLine("Changing secured type's field...");
            secureType.xValue = 99;

            // Distributor must call ToString on the secured object.
            Distributor.DisplayCachedObject();

            // If the following line is uncommented, a security 
            // exception is thrown at JIT-compilation time because 
            // of the link demand for full trust that protects 
            // SecuredTypeWithFields.ToString().

            // Console.WriteLine("Secured type {0}",secureType.ToString());
        }
    }
}

В примере получается следующий вывод.

Creating an instance of SecuredTypeWithFields.
Secured type fields: 22, 33
Changing secured type's field...
Cached Object fields: 99, 33

См. также