RegistryHelper::makeWritable
void RegistryHelper::makeWritable(wstring key)
{
HKEY keyHandle = openKey(key, READ_CONTROL | WRITE_DAC | KEY_WOW64_64KEY);
DWORD descriptorSize = 0;
RegGetKeySecurity(keyHandle, DACL_SECURITY_INFORMATION, NULL, &descriptorSize);
PSECURITY_DESCRIPTOR oldSd = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, descriptorSize);
LSTATUS status = RegGetKeySecurity(keyHandle, DACL_SECURITY_INFORMATION, oldSd, &descriptorSize);
if (status != ERROR_SUCCESS)
throw RegistryException(L"Error while getting security information for registry key " + key + L": " + StringHelper::getSystemErrorString(status));
BOOL aclPresent, aclDefaulted;
PACL oldAcl = NULL;
if (!GetSecurityDescriptorDacl(oldSd, &aclPresent, &oldAcl, &aclDefaulted))
throw RegistryException(L"Error in GetSecurityDescriptorDacl while ensuring writability");
PSID sid = NULL;
SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY;
if (!AllocateAndInitializeSid(&authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &sid))
throw RegistryException(L"Error in AllocateAndInitializeSid while ensuring writability");
EXPLICIT_ACCESS ea;
ea.grfAccessPermissions = KEY_ALL_ACCESS;
ea.grfAccessMode = SET_ACCESS;
ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea.Trustee.ptstrName = (LPWSTR)sid;
PACL acl = NULL;
if (ERROR_SUCCESS != SetEntriesInAcl(1, &ea, oldAcl, &acl))
throw RegistryException(L"Error in SetEntriesInAcl while ensuring writability");
PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if (NULL == sd)
throw RegistryException(L"Error in LocalAlloc while ensuring writability");
if (!InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION))
throw RegistryException(L"Error in InitializeSecurityDescriptor while ensuring writability");
if (!SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE))
throw RegistryException(L"Error in SetSecurityDescriptorDacl while ensuring writability");
status = RegSetKeySecurity(keyHandle, DACL_SECURITY_INFORMATION, sd);
if (status != ERROR_SUCCESS)
throw RegistryException(L"Error while setting security information for registry key " + key + L": " + StringHelper::getSystemErrorString(status));
FreeSid(sid);
LocalFree(acl);
HeapFree(GetProcessHeap(), 0, oldSd);
LocalFree(sd);
}
随手分享,手有余香