RegistryAccessRule Classe

Definição

Representa um conjunto de direitos de acesso permitidos ou negados para um utilizador ou grupo. Esta 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 seguinte demonstra regras de acesso com herança e propagação. O exemplo cria um RegistrySecurity objeto, depois cria e adiciona duas regras que têm a ContainerInherit bandeira. A primeira regra não tem flags de propagação, enquanto a segunda tem NoPropagateInherit e InheritOnly.

O programa apresenta as regras no RegistrySecurity objeto e depois usa o objeto para criar uma subchave. O programa cria uma subchave filha e uma subchave neta, e depois apresenta a segurança de cada subchave. Finalmente, o programa elimina as teclas 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

Observações

A classe RegistryAccessRule é uma das classes que o .NET Framework fornece para gerir Windows a segurança do controlo de acessos nas chaves do registo. Para uma visão geral destas classes e da sua relação com as estruturas subjacentes de controlo de acesso Windows, veja RegistrySecurity.

Note

A segurança do controlo de acesso Windows só pode ser aplicada a chaves de registo. Não pode ser aplicado a pares de chave/valor individuais armazenados numa chave.

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

RegistryAccessRule os objetos não mapeiam um a um com entradas de controlo de acesso na lista de acesso discricionária subjacente (DACL). Quando se obtém o conjunto de todas as regras de acesso para uma chave de registo, o conjunto contém o número mínimo de regras atualmente necessárias para expressar todas as entradas de controlo de acesso.

Note

As entradas subjacentes ao controlo de acesso mudam à medida que aplicas e removes regras. A informação nas regras é fundida, se possível, para manter o menor número possível de entradas de controlo de acesso. Assim, ao ler a lista atual de regras, pode não parecer exatamente como a lista de todas as regras que adicionou.

Use RegistryAccessRule objetos para especificar direitos de acesso para permitir ou negar a um utilizador ou grupo. Um RegistryAccessRule objeto representa sempre ou o acesso permitido ou recusado, nunca ambos.

Para aplicar uma regra a uma chave de registo, use o RegistryKey.GetAccessControl método para obter o RegistrySecurity objeto. Modificar o RegistrySecurity objeto usando os seus métodos para adicionar a regra, e depois usar o RegistryKey.SetAccessControl método para voltar a anexar o objeto de segurança.

Importante

As alterações que faz a um RegistrySecurity objeto não afetam os níveis de acesso da chave do registo até chamar o RegistryKey.SetAccessControl método para atribuir o objeto de segurança alterado à chave do registo.

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

Construtores

Name Description
RegistryAccessRule(IdentityReference, RegistryRights, AccessControlType)

Inicializa uma nova instância da RegistryAccessRule classe, especificando o utilizador ou grupo a que a regra se aplica, os direitos de acesso e se os direitos de acesso especificados são permitidos ou negados.

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

Inicializa uma nova instância da RegistryAccessRule classe, especificando o utilizador ou grupo a que a regra se aplica, os direitos de acesso, os flags de herança, os flags 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 RegistryAccessRule classe, especificando o nome do utilizador ou grupo a que a regra se aplica, os direitos de acesso e se os direitos de acesso especificados são permitidos ou negados.

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

Inicializa uma nova instância da RegistryAccessRule classe, especificando o nome do utilizador ou grupo a que a regra se aplica, os direitos de acesso, os flags de herança, os flags de propagação e se os direitos de acesso especificados são permitidos ou recusados.

Propriedades

Name Description
AccessControlType

Obtém o AccessControlType valor associado a este AccessRule objeto.

(Herdado de AccessRule)
AccessMask

Recebe a máscara de acesso por causa desta regra.

(Herdado de AuthorizationRule)
IdentityReference

Percebe a IdentityReference que esta regra se aplica.

(Herdado de AuthorizationRule)
InheritanceFlags

Obtém o valor dos flags que determinam como esta regra é herdada pelos objetos filhos.

(Herdado de AuthorizationRule)
IsInherited

Recebe um valor que indica se esta regra está explicitamente definida ou é herdada de um objeto contentor pai.

(Herdado de AuthorizationRule)
PropagationFlags

Obtém o valor dos flags de propagação, que determinam como a herança desta regra é propagada para objetos filhos. Esta propriedade é significativa apenas quando o valor da InheritanceFlags enumeração não Noneé .

(Herdado de AuthorizationRule)
RegistryRights

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

Métodos

Name Description
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Aplica-se a