Remove a 'Deny' rule (permission) from the 'UserChoice' key in the Registry via C#

对着背影说爱祢 提交于 2019-12-04 11:36:47
DavidRR

Your code example and the revisions suggested in the answer by @ali lead me to a solution for overcoming the security setting that Windows places on the UserChoice key which enabled me to delete that key.

My solution presumes that the UserChoice key is present in the HKEY_CURRENT_USER (HKCU) hive. If that is the case, the user owns the UserChoice key and therefore has the necessary privileges to change the security settings on that key and ultimately delete it. (This means that the user does not need to be a member of the Administrators group.)

The extensionKey parameter of this method is the parent key of the UserChoice key.

static void DeleteUserChoiceKey(RegistryKey extensionKey)
{
    const string userChoiceKeyName = "UserChoice";

    using (RegistryKey userChoiceKey =
        extensionKey.OpenSubKey(userChoiceKeyName,
            RegistryKeyPermissionCheck.ReadWriteSubTree,
            RegistryRights.ChangePermissions))
    {
        if (userChoiceKey == null) { return; }
        string userName = WindowsIdentity.GetCurrent().Name;
        RegistrySecurity security = userChoiceKey.GetAccessControl();

        AuthorizationRuleCollection accRules =
            security.GetAccessRules(true, true, typeof(NTAccount));

        foreach (RegistryAccessRule ar in accRules)
        {
            if (ar.IdentityReference.Value == userName &&
                ar.AccessControlType == AccessControlType.Deny)
            {
                security.RemoveAccessRuleSpecific(ar); // remove the 'Deny' permission
            }
        }

        userChoiceKey.SetAccessControl(security); // restore all original permissions
                                                  // *except* for the 'Deny' permission
    }

    extensionKey.DeleteSubKeyTree(userChoiceKeyName, true);
}

A quick thought. Does it work if you take ownership og the regKey, before changing the rules on it

public static void ShowSecurity(RegistryKey regKeyRoot, string user) 
{

regKeyRoot.OpenSubKey("", RegistryKeyPermissionCheck.ReadWriteSubTree,
                    RegistryRights.ChangePermissions);

RegistrySecurity security = regKeyRoot.GetAccessControl(AccessControlSections.All);

security.SetGroup( new NTAccount("Administrators") );
security.SetOwner( new NTAccount("ali") ); //Your account name
security.SetAccessRuleProtection(true, false);
regKeyRoot.SetAccessControl(security);

//---------

  foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount))) 
  {
    if (ar.IdentityReference.Value.Contains(User) && ar.AccessControlType ==  AccessControlType.Deny )
       security.RemoveAccessRuleSpecific(ar);
  }

regKeyRoot.SetAccessControl(security);


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