RegistryKey.SetAccessControl(RegistrySecurity) 메서드

정의

Windows 액세스 제어 보안을 기존 레지스트리 키에 적용합니다.

public:
 void SetAccessControl(System::Security::AccessControl::RegistrySecurity ^ registrySecurity);
public void SetAccessControl (System.Security.AccessControl.RegistrySecurity registrySecurity);
member this.SetAccessControl : System.Security.AccessControl.RegistrySecurity -> unit
Public Sub SetAccessControl (registrySecurity As RegistrySecurity)

매개 변수

registrySecurity
RegistrySecurity

현재 하위 키에 적용할 액세스 제어 보안입니다.

예외

현재 RegistryKey 개체가 액세스 제어 보안이 적용된 키를 나타내고 호출자에게 ChangePermissions 권한이 없는 경우

registrySecurity이(가) null인 경우

조작할 RegistryKey가 닫힌 경우. 닫힌 키는 액세스할 수 없습니다.

예제

다음 코드 예제에서는 테스트 키를 만듭니다. 현재 사용자는 허용 ReadKey 되며 Delete 권한은 허용되지만 거부되고 WriteKey 권한이 부여됩니다ChangePermissions. 이러한 권한에 따라 키를 조작하려는 후속 시도가 성공하거나 실패합니다.

키를 삭제하기 전에 코드가 일시 중지됩니다. 레지스트리 편집기로 전환하고 레지스트리 편집기를 사용하여 키에 액세스할 때 동일한 액세스 권한이 적용되는지 확인할 수 있습니다. (명령줄의 RunAs 를 사용하여 레지스트리 편집기와 샘플 코드를 관리자 권한이 없는 로컬 사용자로 실행하는 경우에 가장 적합합니다. 레지스트리 편집기에서는 특정 관리자가 해당 권한이 거부된 경우에도 관리자가 항상 권한을 변경할 수 있습니다. TestUser라는 로컬 사용자를 정의한 경우 명령은 runas /user:TestUser cmd 레지스트리 편집기를 실행한 다음 샘플 코드를 실행할 수 있는 명령 창을 엽니다.)

using namespace System;
using namespace System::Reflection;
using namespace Microsoft::Win32;
using namespace System::Security::AccessControl;
using namespace System::Security;

int 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 (InvalidOperationException^ ex)
    {
        Console::WriteLine(
            "{0}Unable to delete key: it appears to have child subkeys:{0}{1}", 
            Environment::NewLine, ex);
        return 0;
    }
    catch (SecurityException^ ex)
    {
        Console::WriteLine("{0}You do not have the permissions required " +
            "to delete this key:{0}{1}", Environment::NewLine, ex);
        return 0;
    }

    String^ user = Environment::UserDomainName + "\\" + Environment::UserName;

    RegistrySecurity^ regSecurity = gcnew RegistrySecurity();

    // Allow the current user to read and delete the key.
    //
    regSecurity->AddAccessRule(gcnew 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.
    regSecurity->AddAccessRule(gcnew RegistryAccessRule(user,
        RegistryRights::WriteKey | RegistryRights::ChangePermissions,
        InheritanceFlags::None,
        PropagationFlags::None,
        AccessControlType::Deny));

    // Create the example key with registry security.
    RegistryKey^ createdKey = nullptr;
    try
    {
        createdKey = Registry::CurrentUser->CreateSubKey(
            "RegistryRightsExample", RegistryKeyPermissionCheck::Default,
            regSecurity);
        Console::WriteLine("{0}Example key created.", Environment::NewLine);
        createdKey->SetValue("ValueName", "StringValue");
    }
    catch (SecurityException^ ex)
    {
        Console::WriteLine("{0}You do not have the permissions required " +
            "to create the example key:{0}{1}", Environment::NewLine, ex);
        return 0;
    }
    if (createdKey != nullptr)
    {
        createdKey->Close();
    }

    RegistryKey^ openedKey;

    // Open the key with read access.
    openedKey = Registry::CurrentUser->OpenSubKey("RegistryRightsExample",
        false);
    Console::WriteLine("{0}Retrieved value: {1}",
        Environment::NewLine, openedKey->GetValue("ValueName"));
    openedKey->Close();

    // Attempt to open the key with write access.
    try
    {
        openedKey = Registry::CurrentUser->OpenSubKey("RegistryRightsExample",
            true);
    }
    catch (SecurityException^ ex)
    {
        Console::WriteLine("{0}You do not have the permissions required " +
            "to write to the example key:{0}{1}", Environment::NewLine, ex);
    }
    if (openedKey != nullptr)
    {
        openedKey->Close();
    }

    // Attempt to change permissions for the key.
    try
    {
        regSecurity = gcnew RegistrySecurity();
        regSecurity->AddAccessRule(gcnew RegistryAccessRule(user,
            RegistryRights::WriteKey,
            InheritanceFlags::None,
            PropagationFlags::None,
            AccessControlType::Allow));
        openedKey = Registry::CurrentUser->OpenSubKey("RegistryRightsExample",
            false);
        openedKey->SetAccessControl(regSecurity);
        Console::WriteLine("{0}Example key permissions were changed.", 
            Environment::NewLine);
    }
    catch (UnauthorizedAccessException^ ex)
    {
        Console::WriteLine("{0}You are not authorized to change " +
            "permissions for the example key:{0}{1}", Environment::NewLine, ex);
    }
    if (openedKey != nullptr)
    {
        openedKey->Close();
    }

    Console::WriteLine("{0}Press Enter to delete the example key.", 
        Environment::NewLine);
    Console::ReadLine();

    try
    {
        Registry::CurrentUser->DeleteSubKey("RegistryRightsExample");
        Console::WriteLine("Example key was deleted.");
    }
    catch(SecurityException^ ex)
    {
        Console::WriteLine("{0}You do not have the permissions required to "
            + "delete the example key:{0}{1}", Environment::NewLine, ex);
    }
}
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.

설명

레지스트리 키에 대한 권한을 수정하려면 메서드를 사용하여 GetAccessControl 기존 Windows 액세스 제어 보안을 나타내는 개체를 가져오 RegistrySecurity 고, 해당 개체를 RegistrySecurity 수정한 다음, 메서드를 사용하여 SetAccessControl 키에 대한 보안을 업데이트합니다.

주의

RegistrySecurityregistrySecurity 지정된 개체는 레지스트리 키에 대한 기존 보안을 대체합니다. 새 사용자에 대한 권한을 추가하려면 메서드를 GetAccessControl 사용하여 기존 액세스 제어 보안을 가져온 다음 수정합니다.

적용 대상