4

I'm trying to set an registry access rule on a remote machine:

using (RegistryKey localMachineKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName))
{
  RegistrySecurity rs = new RegistrySecurity();
  rs.AddAccessRule(new RegistryAccessRule(userName, RegistryRights.FullControl, AccessControlType.Allow));

  using (RegistryKey subKey = localMachineKey.CreateSubKey(registryKey))
  {
    subKey.SetValue(name, value);
    subKey.SetAccessControl(rs);
  }
}

this produces the following exception:

    System.NotSupportedException: The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object.
   at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
   at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
   at System.Security.AccessControl.RegistrySecurity.Persist(SafeRegistryHandle hKey, String keyName)...

Does anyone know how to make this working? Thanks!

Matthias
  • 1,032
  • 8
  • 21
  • Are both computers on the same domain, and does the user you run your code under have access on the other machine? – Mikael Svenson May 31 '10 at 21:45
  • Yes, both computers are in the same domain. Yes, the user is in the built in Administrator group on both machines. – Matthias Jun 01 '10 at 11:06

1 Answers1

2

Using WinRM might be an option. How to access WinRM in C#

This link suggests that along with a bit more information:

http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/0beee366-ee8d-4052-b1b9-8ad9bf0f8ff0/

Part of the link suggests that it is not possible set this remotely. However, at the bottom, Shaka_01 mentions calling.SetAccessRuleProtection.

RegistryKey rk = RegistryKey.OpenRemoteBaseKey(...);
RegistrySecurity rs = rk.GetAccessControl(AccessControlSections.All);
rs.SetAccessRuleProtection(true, true); //this line you need to set  ACL on a remote machines registry key.
Community
  • 1
  • 1
Jason
  • 4,897
  • 2
  • 33
  • 40
  • Thank you Jason for your answer. At the moment, I cannot check, if your answer solves my problem, that's why I just upvote your answer. – Matthias Jun 09 '11 at 07:09
  • I confirm that SetAccessRuleProtection(true,true) does prevent the error. However be aware what this does. It turns off 'Include inheritable permissions from this object's parent'. You might not want to do that without understanding the implications. – richb Mar 21 '18 at 03:10