0

I'm trying to add some access rules to registry key to which I've no rights, but I'm an administrator and using "Run as administrator" command at right mouse button menu.
Unfortunately exception is being thrown (System.UnauthorizedAccessException).
When running regedit.exe as administrator I can change rights to this key w/o any problems.
How to add any access rule to this key in my application?

RegistryKey root = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\some_key", RegistryKeyPermissionCheck.ReadWriteSubTree);
RegistrySecurity security = new RegistrySecurity();
SecurityIdentifier sec = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
RegistryAccessRule rule = new RegistryAccessRule(sec, RegistryRights.ReadKey | RegistryRights.QueryValues, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
security.AddAccessRule(rule);
root.SetAccessControl(security);
root.Close();
Dawid Moś
  • 827
  • 2
  • 12
  • 18
  • Old thread, but for those who find this thread (as I did) see work-around solution at: [S.O. setting owner on a registry key](http://stackoverflow.com/questions/24742115/asp-net-vb-setting-owner-on-a-registry-key) – JayRO-GreyBeard Jul 21 '14 at 16:41

3 Answers3

0

I know this is an old thread, but I've encountered this problem before. I found that you need to first open the key with RegistryRights.ChangePermissions, then you can modify the access control.

Try opening the key like this:

    RegistryKey root = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\some_key",
RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);

And then modifying the AccessControl rules.

ksun
  • 1,369
  • 2
  • 13
  • 21
0

I think you should use the GetAccessControl() method to get a RegistrySecurity object:

RegistryKey root = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\some_key", RegistryKeyPermissionCheck.ReadWriteSubTree);
RegistrySecurity security = root.GetAccessControl();

You probably get the exception because you are trying to overwrite the security rules, instead of modifying them.

Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74
  • This object (key) has no security rules set, and inheritance is disabled, so how to get any? Even if I remove all lines of code except RegistryKey root = Registry.LocalMachine.CreateSubKey(...) and root.Close(); the program crashes too. – Dawid Moś Mar 29 '11 at 10:37
  • @daftu, perhaps the problem is in @"SOFTWARE\some_key". Try to first get the SOFTWARE key with write permission, using the OpenSubKey(). And then call CreateSubKey on the returned key. – Edwin de Koning Mar 29 '11 at 10:57
0

The documentation is pretty clear:

UnauthorizedAccessException: The current RegistryKey object represents a key with access control security, and the caller does not have RegistryRights.ChangePermissions rights.

See also the documentation for RegistryRights.

Jon
  • 428,835
  • 81
  • 738
  • 806