Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegSaveKey returns ERROR_PRIVILEGE_NOT_HELD

Tags:

winapi

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_MACHINE, L"Software\\MyProduct", 0, KEY_ACCESS_ALL, &key);
result = RegSaveKey(key, L"c:\\temp\\saved.reg", NULL);

However, RegSaveKey() is returning ERROR_PRIVILEGE_NOT_HELD. The SDK documentation says that "The calling process must have the SE_BACKUP_NAME privilege enabled". The process is running as either a local administrator or as a service.

Any ideas?

like image 293
Jeff Stong Avatar asked Dec 19 '08 14:12

Jeff Stong


People also ask

Why does the regsavekey function fail to work?

If the file already exists, the function fails with the ERROR_ALREADY_EXISTS error. If hKey represents a key on a remote computer, the path described by lpFile is relative to the remote computer. The RegSaveKey function saves only nonvolatile keys. It does not save volatile keys.

What is the purpose of the regsavekey alias?

The winreg.h header defines RegSaveKey as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors.

How do I use a file created by regsavekey?

You can use the file created by RegSaveKey in subsequent calls to the RegLoadKey , RegReplaceKey, or RegRestoreKey functions. If RegSaveKey fails part way through its operation, the file will be corrupt and subsequent calls to RegLoadKey , RegReplaceKey, or RegRestoreKey for the file will fail.

Why can't I save a registry key?

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.


1 Answers

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.

like image 81
reuben Avatar answered Oct 24 '22 03:10

reuben