Share via


CA2112: I tipi protetti non devono esporre campi

Articolo Valore
ID regola CA2112
Category Microsoft.Security
Modifica Interruzione

Causa

Un tipo pubblico o protetto contiene campi pubblici ed è protetto da richieste di collegamento.

Nota

Questa regola è stata deprecata. Per altre informazioni, vedere Regole deprecate.

Descrizione regola

Se il codice ha accesso a un'istanza di un tipo protetta da una richiesta di collegamento, non è necessario che il codice soddisfi la richiesta di collegamento per accedere ai campi del tipo.

Come correggere le violazioni

Per correggere una violazione di questa regola, impostare i campi non pubblici e aggiungere proprietà o metodi pubblici che restituiscono i dati del campo. I controlli di sicurezza LinkDemand sui tipi proteggono l'accesso alle proprietà e ai metodi del tipo. Tuttavia, la sicurezza dell'accesso al codice non si applica ai campi.

Quando eliminare gli avvisi

Sia per i problemi di sicurezza che per una buona progettazione, è consigliabile correggere le violazioni rendendo i campi pubblici non pubblici non pubblici. È possibile eliminare un avviso da questa regola se il campo non contiene informazioni che devono rimanere protette e non si fa affidamento sul contenuto del campo.

Esempio

L'esempio seguente è costituito da un tipo di libreria (SecuredTypeWithFields) con campi non protetti, un tipo (Distributor) che può creare istanze del tipo di libreria e passa erroneamente istanze ai tipi non dispone dell'autorizzazione per crearle e il codice dell'applicazione in grado di leggere i campi di un'istanza anche se non dispone dell'autorizzazione che protegge il tipo.

Il codice di libreria seguente viola la regola.

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

Esempio 1

L'applicazione non può creare un'istanza a causa della richiesta di collegamento che protegge il tipo protetto. La classe seguente consente all'applicazione di ottenere un'istanza del tipo protetto.

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

Esempio 2

L'applicazione seguente illustra come, senza l'autorizzazione per accedere ai metodi di un tipo protetto, il codice può accedere ai relativi campi.

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

Nell'esempio viene prodotto l'output seguente:

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

Vedi anche