I would like to change ownership, then permission to a registry key.
here the code I have so far :
var id = WindowsIdentity.GetCurrent();
if (!Win32.SetPrivilege(Win32.TakeOwnership, true))
throw new Exception();
if (!Win32.SetPrivilege(Win32.Restore, true))
throw new Exception();
var hklm = RegistryKey.OpenBaseKey(registryHive, is64Key ? RegistryView.Registry64 : RegistryView.Registry32);
using (RegKey = hklm.OpenSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership))
{
if (RegKey == null)
throw new Exception("clé de registre non trouvée");
_security = RegKey.GetAccessControl(AccessControlSections.All);
var oldId = _security.GetOwner(typeof (SecurityIdentifier));
_oldSi = new SecurityIdentifier(oldId.ToString());
_security.SetOwner(id.User);
RegKey.SetAccessControl(_security);
}
using (RegKey = hklm.OpenSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions))
{
_fullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
_security.AddAccessRule(_fullAccess);
RegKey.SetAccessControl(_security);
}
Everything works fine, but in regedit, the subkey right only contains my user, all others users are removed.
Before :
After :
It seems that inherited rights are removed.
I'm close to succeed, it must miss a parameter, but I don't see which one.
Try adding this:
_security.SetAccessRuleProtection(false, false);
Before you call this:
RegKey.SetAccessControl(_security);
Doing so will ensure that "protection from inheritance" is disabled (aka inheritance is allowed).