Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get permissions to write to registry keys?

Tags:

windows

winapi

I am trying to write some registry keys under the HKLM portion of the registry. I use RegCreateKeyEx() and RegSetValueEx() in a way similar to some of the MSDN examples I have seen.

However, the RegSetValueEx() call fails with error 5, which FormatMessage() says is 'Access is denied'

I think I need to request elevated permissions, but I am unaware of the API calls needed to do this?

Here is my code:

HKEY hk;
DWORD dwDisp;
LONG result = RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\MyApp"), 0, NULL,
    REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hk, &dwDisp);
if(result == ERROR_SUCCESS)
{       
    BYTE value[] = "Hello world!";

    result = RegSetValueEx(hk, _T("MyValue"), 0, REG_EXPAND_SZ, value, strlen((char*)value)+1);
    if(result != ERROR_SUCCESS)
    {
        DBG_PRINT2("RegSetValueEx failed with code: %d\n", result);
    }

    RegCloseKey(hk);
}
like image 267
samoz Avatar asked Feb 18 '23 11:02

samoz


1 Answers

In order to have write access to HKLM, your process needs to run as a user with admin rights. In addition, on systems which include UAC (Vista and up), your process will need to run elevated. To achieve that specify requireAdministrator in your application manifest.

It is important that you don't run your application with elevated rights unless it is strictly necessary. You can move the portion of the application that needs to write to HKLM into a one time only operation, e.g. your install program. Or you can separate your application into two parts: the large part that runs with normal rights, and the small part that requires elevation.

The reason that you may need to split your application into smaller parts is that the user token is assigned at process startup and cannot be modified during the life of the process. So, if you want some parts of your application to be elevated, and others not, you need to have two distinct processes.

like image 78
David Heffernan Avatar answered Feb 24 '23 23:02

David Heffernan