RegSaveKey returns ERROR_PRIVILEGE_NOT_HELD

I am trying to save the contents of a specific registry key in a file using the RegSaveKey () API:

HKEY key;
LRESULT result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\MyProduct", 0, KEY_ACCESS_ALL, &key);
result = RegSaveKey(key, L"c:\\temp\\saved.reg", NULL);

However, RegSaveKey () returns ERROR_PRIVILEGE_NOT_HELD. The SDK documentation says that "the calling process must have privilege SE_BACKUP_NAME." The process runs as a local administrator or as a service.

Any ideas?

+5
source share
2 answers

Although it works as a local administrator or as a service, you probably do not have the default Backup privilege. You must enable this privilege before attempting to save the registry key.

MSDN , C/++: http://msdn.microsoft.com/en-us/library/aa446619(VS.85).aspx. , , :

HANDLE ProcessToken;

if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &ProcessToken)) {

    SetPrivilege(ProcessToken, SE_BACKUP_NAME, TRUE);

    // Save reg key now...
    ...
}

VB .

+8

, SetPrivilege() reuben , MSDN, ...

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;
}
+3

All Articles