0

I'm trying to add a value to this windows key while running elevated (Administrator):

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing

By default, Administrator only has read permissions to this key. I was thinking of using AddAccessRule() to add myself to that key temporarily, but I cannot do this because in order to use AddAccessRule(), I first need to open the key with "write" access, hence I'm caught in a loop here. These are the current permissions:

enter image description here

This is the code that doesn't work, obviously, because OpenSubkey() fails.

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing", true))
{
   var current = key.GetAccessControl();
   var user = ...;
   current.AddAccessRule(new RegistryAccessRule(user, RegistryRights.WriteKey, AccessControlType.Allow));
   key.SetAccessControl(current);
   key.SetValue("TestValue", 1);
}

How should I work myself into that key, so I can write a value there?

Will I Am
  • 2,614
  • 3
  • 35
  • 61
  • The key probably requires some priviledges, see this https://stackoverflow.com/questions/5467909/how-to-write-in-a-registry-key-own-by-trustedinstaller and this for .NET https://stackoverflow.com/questions/5528888/how-to-enable-the-secreateglobalprivilege-in-net-without-resorting-to-p-invoke – Simon Mourier Aug 14 '23 at 17:46

1 Answers1

1

You need to take ownership of the key.

In windows each process has a token that determines the operations the process can perform. By default some privileges are disabled (even when the process is running as elevated) and must be enabled explicitly. The [SeTakeOwnershipPrivilege] (https://learn.microsoft.com/en-us/windows/win32/secauthz/privilege-constants) is disabled by default.

The answer to that question explains how to change acquire the privilege to change ownership: How do I programmatically give ownership of a Registry Key to Administrators?. It uses a TokenManipulator class mentioned in another answer: How do you take file ownership with PowerShell?

After acquiring the SeTakeOwnershipPrivilege you can call SetOwner method then AddAccessRule

Sherif Elmetainy
  • 4,034
  • 1
  • 13
  • 22