RegistryAccessRule Classe

Definição

Representa um conjunto de direitos de acesso permitidos ou negados para um usuário ou grupo. Essa classe não pode ser herdada.

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
Herança
RegistryAccessRule
Atributos

Exemplos

O exemplo de código a seguir demonstra regras de acesso com herança e propagação. O exemplo cria um RegistrySecurity objeto e, em seguida, cria e adiciona duas regras que têm o ContainerInherit sinalizador. A primeira regra não tem sinalizadores de propagação, enquanto a segunda tem NoPropagateInherit e InheritOnly.

O programa exibe as regras no RegistrySecurity objeto e usa o objeto para criar uma subchave. O programa cria uma subchave filho e uma subchave de neto e exibe a segurança de cada subchave. Por fim, o programa exclui as chaves de teste.


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

Comentários

A RegistryAccessRule classe é uma de um conjunto de classes que o .NET Framework fornece para gerenciar Windows segurança de controle de acesso em chaves do Registro. Para obter uma visão geral dessas classes e sua relação com as estruturas de controle de acesso Windows subjacentes, consulte RegistrySecurity.

Observação

Windows segurança do controle de acesso só pode ser aplicada às chaves do Registro. Ele não pode ser aplicado a pares de chave/valor individuais armazenados em uma chave.

Para obter uma lista das regras atualmente aplicadas a uma chave do Registro, use o RegistryKey.GetAccessControl método para obter um RegistrySecurity objeto e, em seguida, use seu GetAccessRules método para obter uma coleção de RegistryAccessRule objetos.

RegistryAccessRule os objetos não mapeiam um para um com entradas de controle de acesso na DACL (lista de acesso de controle discricionário) subjacente. Quando você obtém o conjunto de todas as regras de acesso para uma chave do Registro, o conjunto contém o número mínimo de regras atualmente necessárias para expressar todas as entradas de controle de acesso.

Observação

As entradas de controle de acesso subjacentes são alteradas à medida que você aplica e remove regras. As informações nas regras são mescladas, se possível, para manter o menor número de entradas de controle de acesso. Portanto, quando você lê a lista atual de regras, ela pode não se parecer exatamente com a lista de todas as regras que você adicionou.

Use RegistryAccessRule objetos para especificar direitos de acesso para permitir ou negar a um usuário ou grupo. Um RegistryAccessRule objeto sempre representa acesso permitido ou acesso negado, nunca ambos.

Para aplicar uma regra a uma chave do Registro, use o RegistryKey.GetAccessControl método para obter o RegistrySecurity objeto. Modifique o RegistrySecurity objeto usando seus métodos para adicionar a regra e use o RegistryKey.SetAccessControl método para reanexar o objeto de segurança.

Importante

As alterações feitas em um RegistrySecurity objeto não afetam os níveis de acesso da chave do Registro até que você chame o RegistryKey.SetAccessControl método para atribuir o objeto de segurança alterado à chave do Registro.

RegistryAccessRule os objetos são imutáveis. A segurança de uma chave do Registro é modificada usando os métodos da RegistrySecurity classe para adicionar ou remover regras; à medida que você faz isso, as entradas de controle de acesso subjacentes são modificadas.

Construtores

RegistryAccessRule(IdentityReference, RegistryRights, AccessControlType)

Inicializa uma nova instância da classe RegistryAccessRule, especificando o usuário ou grupo ao qual a regra se aplica, os direitos de acesso e se estes são permitidos ou negados.

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

Inicializa uma nova instância da classe RegistryAccessRule, especificando o usuário ou grupo ao qual a regra se aplica, os direitos de acesso, os sinalizadores de herança, os sinalizadores de propagação e se os direitos de acesso especificados são permitidos ou negados.

RegistryAccessRule(String, RegistryRights, AccessControlType)

Inicializa uma nova instância da classe RegistryAccessRule, especificando o nome do usuário ou do grupo ao qual a regra se aplica, os direitos de acesso e se eles são permitidos ou negados.

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

Inicializa uma nova instância da classe RegistryAccessRule, especificando o nome do usuário ou grupo ao qual a regra se aplica, os direitos de acesso, os sinalizadores de herança, os sinalizadores de propagação e se os direitos de acesso especificados são permitidos ou negados.

Propriedades

AccessControlType

Obtém o valor de AccessControlType associado a esse objeto AccessRule.

(Herdado de AccessRule)
AccessMask

Obtém a máscara de acesso para essa regra.

(Herdado de AuthorizationRule)
IdentityReference

Obtém o IdentityReference ao qual essa regra se aplica.

(Herdado de AuthorizationRule)
InheritanceFlags

Obtém o valor de sinalizadores que determinam como a essa regra é herdada por objetos filhos.

(Herdado de AuthorizationRule)
IsInherited

Obtém um valor que indica se esta regra é definida explicitamente ou é herdada de um objeto de contêiner pai.

(Herdado de AuthorizationRule)
PropagationFlags

Obtém o valor dos sinalizadores de propagação, que determinam como a herança dessa regra é propagada a objetos filho. Esta propriedade é significativa somente quando o valor de enumeração InheritanceFlags não é None.

(Herdado de AuthorizationRule)
RegistryRights

Obtém os direitos permitidos ou negados pela regra de acesso.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a