Using RegSetKeySecurity to avoid registry redirection

偶尔善良 提交于 2019-12-11 10:33:22

问题


In order to avoid registry redirection to Wow64 keys, how to translate the following code that uses Microsoft.Win32 APIs

public void SetKeyAccessControl(
            RegistryKey rootKey, string subKeyName, string identity, 
            RegistryRights rights, InheritanceFlags inheritanceFlags,
            PropagationFlags propagationFlags, AccessControlType accessType)
{
   using (RegistryKey regKey = rootKey.OpenSubKey(subKeyName, true))
   {
       RegistrySecurity acl = new RegistrySecurity();
       RegistryAccessRule rule = new RegistryAccessRule(identity, rights, inheritanceFlags, propagationFlags, accessType);
       acl.AddAccessRule(rule);

       regKey.SetAccessControl(acl);
   }            
}

into using advapi32 RegSetKeySecurity API

[DllImport(@"advapi32.dll", EntryPoint = "RegSetKeySecurity", SetLastError = true)]
internal static extern int RegSetKeySecurity(IntPtr handle, uint securityInformation, IntPtr pSecurityDescriptor);

回答1:


To avoid Registry redirection, you could do something like this...

SafeRegistryHandle handle = rootKey.Handle;

RegistryKey rootKey32 = RegistryKey.FromHandle(handle, RegistryView.Registry32);

RegistryKey rootKey64 = RegistryKey.FromHandle(handle, RegistryView.Registry64);

You can then use rootKey32 or rootKey64 to open a subkey and you'll get the subkey of the view requested.

At least it works in the few test cases I've tried. And, according to the documentation for FromHandle...

The view parameter for this method is used in subsequent operations, such as opening subkeys




回答2:


Another native method needs to be involved and given an SDDL, the following code sets ACLs on the right registry key:


[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Auto)]
internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string stringSecurityDescriptor, int stringSDRevision, out IntPtr ppSecurityDescriptor, ref int securityDescriptorSize);

string sddl = "...";
IntPtr secDescriptor = IntPtr.Zero;
int size = 0;
ConvertStringSecurityDescriptorToSecurityDescriptor
   (
      sddl,
      1,                              // revision 1
      out secDescriptor,
      ref size
   );

// get handle with RegOpenKeyEx

RegSetKeySecurity
(
     handle,
     0x00000004,                      // DACL_SECURITY_INFORMATION
     secDescriptor
);


来源:https://stackoverflow.com/questions/6851961/using-regsetkeysecurity-to-avoid-registry-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!