RegistryAccessRule Clase

Definición

Representa un conjunto de derechos de acceso concedidos o denegados para un usuario o grupo. Esta clase no puede heredarse.

public ref class RegistryAccessRule sealed : System::Security::AccessControl::AccessRule
public sealed class RegistryAccessRule : System.Security.AccessControl.AccessRule
[System.Security.SecurityCritical]
public sealed class RegistryAccessRule : System.Security.AccessControl.AccessRule
type RegistryAccessRule = class
    inherit AccessRule
[<System.Security.SecurityCritical>]
type RegistryAccessRule = class
    inherit AccessRule
Public NotInheritable Class RegistryAccessRule
Inherits AccessRule
Herencia
RegistryAccessRule
Atributos

Ejemplos

En el ejemplo de código siguiente se muestran las reglas de acceso con herencia y propagación. En el ejemplo se crea un RegistrySecurity objeto y, a continuación, se crean y se agregan dos reglas que tienen la ContainerInherit marca . La primera regla no tiene marcas de propagación, mientras que la segunda tiene NoPropagateInherit y InheritOnly.

El programa muestra las reglas en el RegistrySecurity objeto y, a continuación, usa el objeto para crear una subclave. El programa crea una subclave secundaria y una subclave secundaria y, a continuación, muestra la seguridad de cada subclave. Por último, el programa elimina las claves de prueba.


using System;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Security;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        const string TestKey = "TestKey3927";
        RegistryKey cu = Registry.CurrentUser;

        string user = Environment.UserDomainName + 
            "\\" + Environment.UserName;

        // Create a security object that grants no access.
        RegistrySecurity mSec = new RegistrySecurity();

        // Add a rule that grants the current user the right
        // to read and enumerate the name/value pairs in a key, 
        // to read its access and audit rules, to enumerate
        // its subkeys, to create subkeys, and to delete the key. 
        // The rule is inherited by all contained subkeys.
        //
        RegistryAccessRule rule = new RegistryAccessRule(user, 
           RegistryRights.ReadKey | RegistryRights.WriteKey 
               | RegistryRights.Delete, 
           InheritanceFlags.ContainerInherit, 
           PropagationFlags.None, 
           AccessControlType.Allow
        );
        mSec.AddAccessRule(rule);

        // Add a rule that allows the current user the right
        // right to set the name/value pairs in a key. 
        // This rule is inherited by contained subkeys, but
        // propagation flags limit it to immediate child 
        // subkeys.
        rule = new RegistryAccessRule(user, 
            RegistryRights.ChangePermissions, 
            InheritanceFlags.ContainerInherit, 
            PropagationFlags.InheritOnly | 
                PropagationFlags.NoPropagateInherit, 
            AccessControlType.Allow);
        mSec.AddAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);

        // Create the test key using the security object.
        //
        RegistryKey rk = cu.CreateSubKey(TestKey, 
            RegistryKeyPermissionCheck.ReadWriteSubTree, mSec);

        // Create a child subkey and a grandchild subkey, 
        // without security.
        RegistryKey rkChild = rk.CreateSubKey("ChildKey", 
            RegistryKeyPermissionCheck.ReadWriteSubTree);
        RegistryKey rkGrandChild = 
            rkChild.CreateSubKey("GrandChildKey", 
                RegistryKeyPermissionCheck.ReadWriteSubTree);

        Show(rk);
        Show(rkChild);
        Show(rkGrandChild);

        rkGrandChild.Close();
        rkChild.Close();
        rk.Close();

        cu.DeleteSubKeyTree(TestKey);
    }

    private static void Show(RegistryKey rk)
    {
        Console.WriteLine(rk.Name);
        ShowSecurity(rk.GetAccessControl());
    }

    private static void ShowSecurity(RegistrySecurity security)
    {
        Console.WriteLine("\r\nCurrent access rules:\r\n");

        foreach( RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)) )
        {

            Console.WriteLine("        User: {0}", ar.IdentityReference);
            Console.WriteLine("        Type: {0}", ar.AccessControlType);
            Console.WriteLine("      Rights: {0}", ar.RegistryRights);
            Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
            Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
            Console.WriteLine("   Inherited? {0}", ar.IsInherited);
            Console.WriteLine();
        }
    }
}

/* This code example produces output similar to following:

Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: SetValue, CreateSubKey, Delete, ReadKey
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? False

        User: TestDomain\TestUser
        Type: Allow
      Rights: ChangePermissions
 Inheritance: ContainerInherit
 Propagation: NoPropagateInherit, InheritOnly
   Inherited? False

HKEY_CURRENT_USER\TestKey3927

Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: SetValue, CreateSubKey, Delete, ReadKey
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? False

        User: TestDomain\TestUser
        Type: Allow
      Rights: ChangePermissions
 Inheritance: ContainerInherit
 Propagation: NoPropagateInherit, InheritOnly
   Inherited? False

HKEY_CURRENT_USER\TestKey3927\ChildKey

Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: SetValue, CreateSubKey, Delete, ReadKey
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? True

        User: TestDomain\TestUser
        Type: Allow
      Rights: ChangePermissions
 Inheritance: None
 Propagation: None
   Inherited? True

HKEY_CURRENT_USER\TestKey3927\ChildKey\GrandChildKey

Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: SetValue, CreateSubKey, Delete, ReadKey
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? True
 */
Option Explicit
Imports System.Security.AccessControl
Imports System.Security.Principal
Imports System.Security
Imports Microsoft.Win32

Public Class Example

    Public Shared Sub Main()

        Const TestKey As String = "TestKey3927"
        Dim cu As RegistryKey = Registry.CurrentUser

        Dim user As String = Environment.UserDomainName _ 
            & "\" & Environment.UserName

        ' Create a security object that grants no access.
        Dim mSec As New RegistrySecurity()

        ' Add a rule that grants the current user the right
        ' to read and enumerate the name/value pairs in a key, 
        ' to read its access and audit rules, to enumerate
        ' its subkeys, to create subkeys, and to delete the key. 
        ' The rule is inherited by all contained subkeys.
        '
        Dim rule As New RegistryAccessRule(user, _
            RegistryRights.ReadKey Or RegistryRights.WriteKey _
                Or RegistryRights.Delete, _
            InheritanceFlags.ContainerInherit, _
            PropagationFlags.None, _
            AccessControlType.Allow)
        mSec.AddAccessRule(rule)

        ' Add a rule that allows the current user the right
        ' right to set the name/value pairs in a key. 
        ' This rule is inherited by contained subkeys, but
        ' propagation flags limit it to immediate child 
        ' subkeys.
        rule = New RegistryAccessRule(user, _
            RegistryRights.ChangePermissions, _
            InheritanceFlags.ContainerInherit, _
            PropagationFlags.InheritOnly Or PropagationFlags.NoPropagateInherit, _
            AccessControlType.Allow)
        mSec.AddAccessRule(rule)

        ' Display the rules in the security object.
        ShowSecurity(mSec)

        ' Create the test key using the security object.
        '
        Dim rk As RegistryKey = cu.CreateSubKey(TestKey, _
            RegistryKeyPermissionCheck.ReadWriteSubTree, _
            mSec)

        ' Create a child subkey and a grandchild subkey, 
        ' without security.
        Dim rkChild As RegistryKey= rk.CreateSubKey("ChildKey", _
            RegistryKeyPermissionCheck.ReadWriteSubTree)
        Dim rkGrandChild As RegistryKey = _
            rkChild.CreateSubKey("GrandChildKey", _
                RegistryKeyPermissionCheck.ReadWriteSubTree)

        Show(rk)
        Show(rkChild)
        Show(rkGrandChild)

        rkGrandChild.Close()
        rkChild.Close()
        rk.Close()

        cu.DeleteSubKeyTree(TestKey)
    End Sub 

    Private Shared Sub Show(ByVal rk As RegistryKey)
        Console.WriteLine(rk.Name)            
        ShowSecurity(rk.GetAccessControl())
    End Sub

    Private Shared Sub ShowSecurity(ByVal security As RegistrySecurity)
        Console.WriteLine(vbCrLf & "Current access rules:" & vbCrLf)

        For Each ar As RegistryAccessRule In _
            security.GetAccessRules(True, True, GetType(NTAccount))

            Console.WriteLine("        User: {0}", ar.IdentityReference)
            Console.WriteLine("        Type: {0}", ar.AccessControlType)
            Console.WriteLine("      Rights: {0}", ar.RegistryRights)
            Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags)
            Console.WriteLine(" Propagation: {0}", ar.PropagationFlags)
            Console.WriteLine("   Inherited? {0}", ar.IsInherited)
            Console.WriteLine()
        Next

    End Sub
End Class 

'This code example produces output similar to following:
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: SetValue, CreateSubKey, Delete, ReadKey
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? False
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: ChangePermissions
' Inheritance: ContainerInherit
' Propagation: NoPropagateInherit, InheritOnly
'   Inherited? False
'
'HKEY_CURRENT_USER\TestKey3927
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: SetValue, CreateSubKey, Delete, ReadKey
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? False
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: ChangePermissions
' Inheritance: ContainerInherit
' Propagation: NoPropagateInherit, InheritOnly
'   Inherited? False
'
'HKEY_CURRENT_USER\TestKey3927\ChildKey
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: SetValue, CreateSubKey, Delete, ReadKey
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? True
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: ChangePermissions
' Inheritance: None
' Propagation: None
'   Inherited? True
'
'HKEY_CURRENT_USER\TestKey3927\ChildKey\GrandChildKey
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: SetValue, CreateSubKey, Delete, ReadKey
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? True

Comentarios

La RegistryAccessRule clase es uno de un conjunto de clases que el .NET Framework proporciona para administrar Windows seguridad de control de acceso en las claves del Registro. Para obtener información general sobre estas clases y su relación con las estructuras de control de acceso subyacentes Windows, consulte RegistrySecurity.

Nota

Windows seguridad de control de acceso solo se puede aplicar a las claves del Registro. No se puede aplicar a pares clave-valor individuales almacenados en una clave.

Para obtener una lista de las reglas aplicadas actualmente a una clave del Registro, use el RegistryKey.GetAccessControl método para obtener un RegistrySecurity objeto y, a continuación, use su GetAccessRules método para obtener una colección de RegistryAccessRule objetos.

RegistryAccessRule Los objetos no asignan uno a uno con entradas de control de acceso en la lista de acceso de control discrecional subyacente (DACL). Cuando se obtiene el conjunto de todas las reglas de acceso para una clave del Registro, el conjunto contiene el número mínimo de reglas necesarias actualmente para expresar todas las entradas de control de acceso.

Nota

Las entradas de control de acceso subyacentes cambian a medida que se aplican y quitan reglas. La información de las reglas se combina si es posible, para mantener el menor número de entradas de control de acceso. Por lo tanto, al leer la lista actual de reglas, es posible que no parezca exactamente la lista de todas las reglas que ha agregado.

Use RegistryAccessRule objetos para especificar derechos de acceso para permitir o denegar a un usuario o grupo. Un RegistryAccessRule objeto siempre representa el acceso permitido o el acceso denegado, nunca ambos.

Para aplicar una regla a una clave del Registro, use el RegistryKey.GetAccessControl método para obtener el RegistrySecurity objeto . Modifique el RegistrySecurity objeto mediante sus métodos para agregar la regla y, a continuación, use el RegistryKey.SetAccessControl método para volver a adjuntar el objeto de seguridad.

Importante

Los cambios realizados en un RegistrySecurity objeto no afectan a los niveles de acceso de la clave del Registro hasta que llame al RegistryKey.SetAccessControl método para asignar el objeto de seguridad modificado a la clave del Registro.

RegistryAccessRule Los objetos son inmutables. La seguridad de una clave del Registro se modifica mediante los métodos de la RegistrySecurity clase para agregar o quitar reglas; al hacerlo, se modifican las entradas de control de acceso subyacentes.

Constructores

RegistryAccessRule(IdentityReference, RegistryRights, AccessControlType)

Inicializa una nueva instancia de la clase RegistryAccessRule, que especifica el usuario o grupo al que se aplica la regla, los derechos de acceso y si se conceden o deniegan los derechos de acceso especificados.

RegistryAccessRule(IdentityReference, RegistryRights, InheritanceFlags, PropagationFlags, AccessControlType)

Inicializa una nueva instancia de la clase RegistryAccessRule, que especifica el usuario o grupo al que se aplica la regla, los derechos de acceso, los marcadores de herencia y de propagación, y si se conceden o deniegan los derechos de acceso especificados.

RegistryAccessRule(String, RegistryRights, AccessControlType)

Inicializa una nueva instancia de la clase RegistryAccessRule, que especifica el nombre del usuario o grupo al que se aplica la regla, los derechos de acceso y si se conceden o deniegan los derechos de acceso especificados.

RegistryAccessRule(String, RegistryRights, InheritanceFlags, PropagationFlags, AccessControlType)

Inicializa una nueva instancia de la clase RegistryAccessRule, que especifica el nombre del usuario o grupo al que se aplica la regla, los derechos de acceso, los marcadores de herencia y de propagación y si se conceden o deniegan los derechos de acceso especificados.

Propiedades

AccessControlType

Obtiene el valor de AccessControlType asociado a este objeto AccessRule.

(Heredado de AccessRule)
AccessMask

Obtiene la máscara de acceso de esta regla.

(Heredado de AuthorizationRule)
IdentityReference

Obtiene el IdentityReference al que se aplica esta regla.

(Heredado de AuthorizationRule)
InheritanceFlags

Obtiene el valor de los indicadores que determinan cómo heredan esta regla los objetos secundarios.

(Heredado de AuthorizationRule)
IsInherited

Obtiene un valor que indica si esta regla se establece explícitamente o se hereda de un objeto contenedor primario.

(Heredado de AuthorizationRule)
PropagationFlags

Obtiene el valor de las marcas de propagación que determinan cómo se propaga la herencia de esta regla a los objetos secundarios. Esta propiedad es importante solo cuando el valor de la enumeración InheritanceFlags no es None.

(Heredado de AuthorizationRule)
RegistryRights

Obtiene los derechos concedidos o denegados por la regla de acceso.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a