RegistryAccessRule Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет набор разрешенных или запрещенных прав доступа для пользователя или группы. Этот класс не наследуется.
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
- Наследование
- Атрибуты
Примеры
В следующем примере кода показаны правила доступа с наследованием и распространением. В примере создается RegistrySecurity объект, а затем создаются и добавляются два правила с флагом ContainerInherit . Первое правило не имеет флагов распространения, в то время как второй имеет NoPropagateInherit и InheritOnly.
Программа отображает правила в объекте RegistrySecurity , а затем использует объект для создания подраздела. Программа создает дочерний подраздел и подраздел grandchild, а затем отображает безопасность для каждого подраздела. Наконец, программа удаляет тестовые ключи.
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
Комментарии
Класс RegistryAccessRule является одним из наборов классов, которые платформа .NET Framework предоставляет для управления безопасностью управления доступом Windows в разделах реестра. Общие сведения об этих классах и их отношениях с базовыми структурами управления доступом Windows см. в разделе RegistrySecurity.
Note
Windows безопасность управления доступом может применяться только к разделам реестра. Его нельзя применить к отдельным парам ключей и значений, хранящимся в ключе.
Чтобы получить список правил, применяемых к разделу реестра, используйте метод для получения объекта, а затем используйте RegistryKey.GetAccessControl его RegistrySecurity метод для получения GetAccessRules коллекции RegistryAccessRule объектов.
RegistryAccessRule объекты не сопоставляют один к одному с записями управления доступом в базовом списке управления доступом (DACL). При получении набора всех правил доступа для раздела реестра набор содержит минимальное количество правил, необходимых для выражения всех записей управления доступом.
Note
Базовые записи управления доступом изменяются при применении и удалении правил. Сведения в правилах объединяются, если это возможно, для поддержания наименьшего количества записей управления доступом. Таким образом, при чтении текущего списка правил он может не выглядеть точно так же, как список всех добавленных правил.
Используйте RegistryAccessRule объекты, чтобы указать права доступа, чтобы разрешить или запретить пользователю или группе. Объект RegistryAccessRule всегда представляет разрешенный или запрещенный доступ, никогда не оба.
Чтобы применить правило к разделу реестра, используйте RegistryKey.GetAccessControl метод для получения RegistrySecurity объекта. Измените RegistrySecurity объект с помощью его методов, чтобы добавить правило, а затем используйте RegistryKey.SetAccessControl метод для повторного кэширования объекта безопасности.
Important
Изменения, внесенные в RegistrySecurity объект, не влияют на уровни доступа раздела реестра, пока не вызовете RegistryKey.SetAccessControl метод, чтобы назначить измененный объект безопасности разделу реестра.
RegistryAccessRule объекты неизменяемы. Безопасность раздела реестра изменяется с помощью методов RegistrySecurity класса для добавления или удаления правил. По мере этого изменяются базовые записи управления доступом.
Конструкторы
| Имя | Описание |
|---|---|
| RegistryAccessRule(IdentityReference, RegistryRights, AccessControlType) |
Инициализирует новый экземпляр RegistryAccessRule класса, указывая пользователя или группу, к которым применяется правило, права доступа и разрешены ли указанные права доступа или запрещены. |
| RegistryAccessRule(IdentityReference, RegistryRights, InheritanceFlags, PropagationFlags, AccessControlType) |
Инициализирует новый экземпляр RegistryAccessRule класса, указывая пользователя или группу, к которым применяется правило, права доступа, флаги наследования, флаги распространения и разрешены ли указанные права доступа или запрещены. |
| RegistryAccessRule(String, RegistryRights, AccessControlType) |
Инициализирует новый экземпляр RegistryAccessRule класса, указывая имя пользователя или группы, к которым применяется правило, права доступа и разрешены ли указанные права доступа или запрещены. |
| RegistryAccessRule(String, RegistryRights, InheritanceFlags, PropagationFlags, AccessControlType) |
Инициализирует новый экземпляр RegistryAccessRule класса, указав имя пользователя или группы, к которым применяется правило, права доступа, флаги наследования, флаги распространения, а также разрешены или запрещены указанные права доступа. |
Свойства
| Имя | Описание |
|---|---|
| AccessControlType |
Возвращает значение, связанное AccessControlType с этим AccessRule объектом. (Унаследовано от AccessRule) |
| AccessMask |
Возвращает маску доступа для этого правила. (Унаследовано от AuthorizationRule) |
| IdentityReference |
Возвращает значение IdentityReference , к которому применяется это правило. (Унаследовано от AuthorizationRule) |
| InheritanceFlags |
Получает значение флагов, определяющих, как это правило наследуется дочерними объектами. (Унаследовано от AuthorizationRule) |
| IsInherited |
Возвращает значение, указывающее, задано ли это правило явным образом или наследуется от родительского объекта контейнера. (Унаследовано от AuthorizationRule) |
| PropagationFlags |
Возвращает значение флагов распространения, определяющих, как наследование этого правила распространяется на дочерние объекты. Это свойство имеет значение, только если значение перечисления InheritanceFlags не Noneявляется. (Унаследовано от AuthorizationRule) |
| RegistryRights |
Возвращает права, разрешенные или запрещенные правилом доступа. |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |