RegistryHelper::makeWritable

0 0 2025-05-29 本文地址:http://www.pnpon.com/fun/detail-24.html
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);
}
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

您的支持,是我们前进的动力!