RegistryRights Enumeração
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Especifica os direitos de controlo de acesso que podem ser aplicados a objetos do registo.
Esta enumeração suporta uma combinação bit-a-bit dos respetivos valores membro.
public enum class RegistryRights
[System.Flags]
public enum RegistryRights
[<System.Flags>]
type RegistryRights =
Public Enum RegistryRights
- Herança
- Atributos
Campos
| Name | Valor | Description |
|---|---|---|
| QueryValues | 1 | O direito de consultar os pares nome/valor numa chave de registo. |
| SetValue | 2 | O direito de criar, eliminar ou definir pares nome/valor numa chave de registo. |
| CreateSubKey | 4 | O direito de criar subchaves de uma chave de registo. |
| EnumerateSubKeys | 8 | O direito de listar as subchaves de uma chave de registo. |
| Notify | 16 | O direito de solicitar notificação de alterações numa chave de registo. |
| CreateLink | 32 | Reservado para uso no sistema. |
| Delete | 65536 | O direito de apagar uma chave de registo. |
| ReadPermissions | 131072 | O direito de abrir e copiar as regras de acesso e as regras de auditoria para uma chave de registo. |
| WriteKey | 131078 | O direito de criar, eliminar e definir os pares nome/valor numa chave de registo, criar ou eliminar subchaves, solicitar notificação de alterações, enumerar as suas subchaves e ler as suas regras de acesso e regras de auditoria. |
| ExecuteKey | 131097 | O mesmo que ReadKey. |
| ReadKey | 131097 | O direito de consultar os pares nome/valor numa chave de registo, solicitar notificação de alterações, enumerar as suas subchaves e ler as suas regras de acesso e regras de auditoria. |
| ChangePermissions | 262144 | O direito de alterar as regras de acesso e as regras de auditoria associadas a uma chave de registo. |
| TakeOwnership | 524288 | O direito de mudar o proprietário de uma chave de registo. |
| FullControl | 983103 | O direito de exercer controlo total sobre uma chave de registo e de modificar as suas regras de acesso e de auditoria. |
Exemplos
O seguinte exemplo de código demonstra a utilização da RegistryRights enumeração. O código cria uma chave de teste, permitindo ao utilizador atual direitos de acesso ReadKey e Delete, mas negando os direitos de ChangePermissions e WriteKey. As tentativas subsequentes de manipular a chave têm sucesso ou falham dependendo dessas permissões.
Antes de a chave ser apagada, o código pausa. Pode mudar para o Editor do Registo (Regedit.exe ou Regedt32.exe) e verificar se os mesmos direitos de acesso se aplicam quando a chave é acedida usando o Editor do Registo.
Este exemplo funciona melhor se usares o RunAs da linha de comandos para executar o Editor do Registo e o código de exemplo como utilizador local sem direitos de administrador. Por exemplo, se definiu um utilizador local chamado TestUser, o comando runas /user:TestUser cmd abre uma janela de comandos a partir da qual pode executar o Editor do Registo e depois o código de exemplo.
using System;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using Microsoft.Win32;
public class Example
{
public static void Main()
{
// Delete the example key if it exists.
try
{
Registry.CurrentUser.DeleteSubKey("RegistryRightsExample");
Console.WriteLine("Example key has been deleted.");
}
catch (ArgumentException)
{
// ArgumentException is thrown if the key does not exist. In
// this case, there is no reason to display a message.
}
catch (Exception ex)
{
Console.WriteLine("Unable to delete the example key: {0}", ex);
return;
}
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistrySecurity rs = new RegistrySecurity();
// Allow the current user to read and delete the key.
//
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.ReadKey | RegistryRights.Delete,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
// Prevent the current user from writing or changing the
// permission set of the key. Note that if Delete permission
// were not allowed in the previous access rule, denying
// WriteKey permission would prevent the user from deleting the
// key.
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.WriteKey | RegistryRights.ChangePermissions,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Deny));
// Create the example key with registry security.
RegistryKey rk = null;
try
{
rk = Registry.CurrentUser.CreateSubKey("RegistryRightsExample",
RegistryKeyPermissionCheck.Default, rs);
Console.WriteLine("\r\nExample key created.");
rk.SetValue("ValueName", "StringValue");
}
catch (Exception ex)
{
Console.WriteLine("\r\nUnable to create the example key: {0}", ex);
}
if (rk != null) rk.Close();
rk = Registry.CurrentUser;
RegistryKey rk2;
// Open the key with read access.
rk2 = rk.OpenSubKey("RegistryRightsExample", false);
Console.WriteLine("\r\nRetrieved value: {0}", rk2.GetValue("ValueName"));
rk2.Close();
// Attempt to open the key with write access.
try
{
rk2 = rk.OpenSubKey("RegistryRightsExample", true);
}
catch (SecurityException ex)
{
Console.WriteLine("\nUnable to write to the example key." +
" Caught SecurityException: {0}", ex.Message);
}
if (rk2 != null) rk2.Close();
// Attempt to change permissions for the key.
try
{
rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(user,
RegistryRights.WriteKey,
InheritanceFlags.None,
PropagationFlags.None,
AccessControlType.Allow));
rk2 = rk.OpenSubKey("RegistryRightsExample", false);
rk2.SetAccessControl(rs);
Console.WriteLine("\r\nExample key permissions were changed.");
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("\nUnable to change permissions for the example key." +
" Caught UnauthorizedAccessException: {0}", ex.Message);
}
if (rk2 != null) rk2.Close();
Console.WriteLine("\r\nPress Enter to delete the example key.");
Console.ReadLine();
try
{
rk.DeleteSubKey("RegistryRightsExample");
Console.WriteLine("Example key was deleted.");
}
catch(Exception ex)
{
Console.WriteLine("Unable to delete the example key: {0}", ex);
}
rk.Close();
}
}
/* This code example produces the following output:
Example key created.
Retrieved value: StringValue
Unable to write to the example key. Caught SecurityException: Requested registry access is not allowed.
Unable to change permissions for the example key. Caught UnauthorizedAccessException: Cannot write to the registry key.
Press Enter to delete the example key.
Example key was deleted.
*/
Imports System.Reflection
Imports System.Security
Imports System.Security.AccessControl
Imports Microsoft.Win32
Public Class Example
Public Shared Sub Main()
' Delete the example key if it exists.
Try
Registry.CurrentUser.DeleteSubKey("RegistryRightsExample")
Console.WriteLine("Example key has been deleted.")
Catch ex As ArgumentException
' ArgumentException is thrown if the key does not exist. In
' this case, there is no reason to display a message.
Catch ex As Exception
Console.WriteLine("Unable to delete the example key: {0}", ex)
Return
End Try
Dim user As String = Environment.UserDomainName & "\" & Environment.UserName
Dim rs As New RegistrySecurity()
' Allow the current user to read and delete the key.
'
rs.AddAccessRule(new RegistryAccessRule(user, _
RegistryRights.ReadKey Or RegistryRights.Delete, _
InheritanceFlags.None, _
PropagationFlags.None, _
AccessControlType.Allow))
' Prevent the current user from writing or changing the
' permission set of the key. Note that if Delete permission
' were not allowed in the previous access rule, denying
' WriteKey permission would prevent the user from deleting the
' key.
rs.AddAccessRule(new RegistryAccessRule(user, _
RegistryRights.WriteKey Or RegistryRights.ChangePermissions, _
InheritanceFlags.None, _
PropagationFlags.None, _
AccessControlType.Deny))
' Create the example key with registry security.
Dim rk As RegistryKey = Nothing
Try
rk = Registry.CurrentUser.CreateSubKey("RegistryRightsExample", _
RegistryKeyPermissionCheck.Default, rs)
Console.WriteLine(vbCrLf & "Example key created.")
rk.SetValue("ValueName", "StringValue")
Catch ex As Exception
Console.WriteLine(vbCrLf & "Unable to create the example key: {0}", ex)
End Try
If rk IsNot Nothing Then rk.Close()
rk = Registry.CurrentUser
Dim rk2 As RegistryKey
' Open the key with read access.
rk2 = rk.OpenSubKey("RegistryRightsExample", False)
Console.WriteLine(vbCrLf & "Retrieved value: {0}", rk2.GetValue("ValueName"))
rk2.Close()
' Attempt to open the key with write access.
Try
rk2 = rk.OpenSubKey("RegistryRightsExample", True)
Catch ex As SecurityException
Console.WriteLine(vbCrLf & "Unable to write to the example key." _
& " Caught SecurityException: {0}", ex.Message)
End Try
If rk2 IsNot Nothing Then rk2.Close()
' Attempt to change permissions for the key.
Try
rs = New RegistrySecurity()
rs.AddAccessRule(new RegistryAccessRule(user, _
RegistryRights.WriteKey, _
InheritanceFlags.None, _
PropagationFlags.None, _
AccessControlType.Allow))
rk2 = rk.OpenSubKey("RegistryRightsExample", False)
rk2.SetAccessControl(rs)
Console.WriteLine(vbCrLf & "Example key permissions were changed.")
Catch ex As UnauthorizedAccessException
Console.WriteLine(vbCrLf & "Unable to change permissions for the example key." _
& " Caught UnauthorizedAccessException: {0}", ex.Message)
End Try
If rk2 IsNot Nothing Then rk2.Close()
Console.WriteLine(vbCrLf & "Press Enter to delete the example key.")
Console.ReadLine()
Try
rk.DeleteSubKey("RegistryRightsExample")
Console.WriteLine("Example key was deleted.")
Catch ex As Exception
Console.WriteLine("Unable to delete the example key: {0}", ex)
End Try
rk.Close()
End Sub
End Class
' This code produces the following output:
'
'Example key created.
'
'Retrieved value: StringValue
'
'Unable to write to the example key. Caught SecurityException: Requested registry access is not allowed.
'
'Unable to change permissions for the example key. Caught UnauthorizedAccessException: Cannot write to the registry key.
'
'Press Enter to delete the example key.
'
'Example key was deleted.
Observações
Use a RegistryRights enumeração para especificar direitos de acesso ao registo quando criar RegistrySecurity objetos. Para aplicar direitos de acesso a uma chave de registo, primeiro adiciona RegistryAccessRule objetos a um RegistrySecurity objeto, depois anexa o RegistrySecurity objeto à chave usando o RegistryKey.SetAccessControl método, ou uma sobrecarga apropriada do RegistryKey.CreateSubKey método.