Forum Discussion
Configure registry permissions
Hi
I have strange problem to set specific permission to a registry key.
According to Microsoft's https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.registrysecurity?view=net-10.0, it should work like this:
private static RegistryKey CreateRegistryKey(RegistryKey parentPath) {
RegistryKey childKey = parentPath.CreateSubKey("myKey");
RegistryAccessRule rule = new RegistryAccessRule(
new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
RegistryRights.ReadKey | RegistryRights.Delete,
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow);
RegistrySecurity childACL = childKey.GetAccessControl();
childACL.AddAccessRule(rule);
ShowSecurity(childACL);
childKey.SetAccessControl(childACL);
return childKey;
}As I expectedBut if the code is executed in a windows service, I missing my permission!?
How can this be? Am I doing something wrong? Have I overlooked something?
1 Reply
- Harold-PicadoTin Contributor
Hi, my guess is that you are definitely overlooking how Windows handles service permissions.
When you run this code as an interactive user, Windows is lenient and lets you create a key and then modify its permissions afterward using SetAccessControl(). But when running as a Windows Service (under LocalSystem), the handle returned by CreateSubKey doesn't have the rights to change permissions, so your SetAccessControl call is blocked and fails silently.
To fix this, you have to pass the RegistrySecurity directly into CreateSubKey so the permissions are applied at birth, and use both inheritance flags so it actually applies to registry values as well.
Here is the code that will actually work inside your service:
private static RegistryKey CreateRegistryKey(RegistryKey parentPath) { RegistrySecurity childACL = new RegistrySecurity(); RegistryAccessRule rule = new RegistryAccessRule( new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), RegistryRights.ReadKey | RegistryRights.Delete, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); childACL.AddAccessRule(rule); return parentPath.CreateSubKey("myKey", RegistryKeyPermissionCheck.ReadWriteSubTree, childACL); }