RegistryHelper::takeOwnership

0 0 2025-05-29 本文地址:http://www.pnpon.com/fun/detail-25.html
void RegistryHelper::takeOwnership(wstring key)
{
    HANDLE tokenHandle;
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tokenHandle))
        throw RegistryException(L"Error in OpenProcessToken while taking ownership");

    LUID luid;
    if (!LookupPrivilegeValue(NULL, SE_TAKE_OWNERSHIP_NAME, &luid))
        throw RegistryException(L"Error in LookupPrivilegeValue while taking ownership");

    TOKEN_PRIVILEGES tp;
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!AdjustTokenPrivileges(tokenHandle, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
        throw RegistryException(L"Error in AdjustTokenPrivileges while taking ownership");

    HKEY keyHandle = openKey(key, WRITE_OWNER | KEY_WOW64_64KEY);

    PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
    if (NULL == sd)
        throw RegistryException(L"Error in SetPrivilege while taking ownership");

    if (!InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION))
        throw RegistryException(L"Error in InitializeSecurityDescriptor while taking ownership");

    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 taking ownership");

    if (!SetSecurityDescriptorOwner(sd, sid, FALSE))
        throw RegistryException(L"Error in SetSecurityDescriptorOwner while taking ownership");

    LSTATUS status = RegSetKeySecurity(keyHandle, OWNER_SECURITY_INFORMATION, sd);
    if (status != ERROR_SUCCESS)
        throw RegistryException(L"Error while setting security information for registry key " + key + L": " + StringHelper::getSystemErrorString(status));

    tp.Privileges[0].Attributes = 0;

    if (!AdjustTokenPrivileges(tokenHandle, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
        throw RegistryException(L"Error in AdjustTokenPrivileges while taking ownership");

    FreeSid(sid);
    LocalFree(sd);
}
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

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

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