RegSaveKey returns ERROR_PRIVILEGE_NOT_HELD

前端 未结 2 859
小鲜肉
小鲜肉 2021-01-19 01:57

I\'m trying to save the contents of a particular registry key to a file using the RegSaveKey() API:

HKEY key;
LRESULT result = RegOpenKeyEx(HKEY_LOCAL_MACHIN         


        
相关标签:
2条回答
  • 2021-01-19 02:15

    Despite running as a local administrator or as a service, you probably don't have the "Backup" privilege enabled by default. You'll need to enable this privilege before you try to save the registry key.

    MSDN has a good example on how to enable a security privilege in C/C++: http://msdn.microsoft.com/en-us/library/aa446619(VS.85).aspx. If you include the sample function defined on that page, you can then just call:

    HANDLE ProcessToken;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &ProcessToken)) {
    
        SetPrivilege(ProcessToken, SE_BACKUP_NAME, TRUE);
    
        // Save reg key now...
        ...
    }
    

    Alternatively, there's also a VB-based example on the wayback machine.

    0 讨论(0)
  • 2021-01-19 02:29

    Note that SetPrivilege() of reuben's answer is user-defined, according to MSDN, the function body goes thus...

    BOOL SetPrivilege(
        HANDLE hToken,          // access token handle
        LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
        BOOL bEnablePrivilege   // to enable or disable privilege
        )  
    {
    TOKEN_PRIVILEGES tp;
    LUID luid;
    
    if ( !LookupPrivilegeValue( 
            NULL,            // lookup privilege on local system
            lpszPrivilege,   // privilege to lookup 
            &luid ) )        // receives LUID of privilege
    {
        printf("LookupPrivilegeValue error: %u\n", GetLastError() ); 
        return FALSE; 
    }
    
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    if (bEnablePrivilege)
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    else
        tp.Privileges[0].Attributes = 0;
    
    // Enable the privilege or disable all privileges.
    
    if ( !AdjustTokenPrivileges(
           hToken, 
           FALSE, 
           &tp, 
           sizeof(TOKEN_PRIVILEGES), 
           (PTOKEN_PRIVILEGES) NULL, 
           (PDWORD) NULL) )
    { 
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); 
          return FALSE; 
    } 
    
    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
    
    {
          printf("The token does not have the specified privilege. \n");
          return FALSE;
    } 
    
    return TRUE;
    }
    
    0 讨论(0)
提交回复
热议问题