Increase privilege in Runtime (Windows API C / C ++)

My application does not always require admin privileges, and most of the time it will work as the current user. Is there a way I can escalate the identity by calling UAC at runtime after my program is already running? This will happen only when I need privileges. Instead of starting with high privileges.

I know the "runas" technique, manifest file, etc., but all this before the process is created, and not at run time, on request

+5
source share
1 answer

Congratulations, exactly how UAC is designed to work, and something that most application developers are either too lazy or too scared to ever look at :)

In a nutshell, you put the code that needs to be promoted in a separate COM object (which lives in the DLL), and then you create it with the elevated instance using the method described here .

HRESULT CoCreateInstanceAsAdmin(HWND hwnd, REFCLSID rclsid, REFIID riid, __out void ** ppv) { BIND_OPTS3 bo; WCHAR wszCLSID[50]; WCHAR wszMonikerName[300]; StringFromGUID2(rclsid, wszCLSID, sizeof(wszCLSID)/sizeof(wszCLSID[0])); HRESULT hr = StringCchPrintf(wszMonikerName, sizeof(wszMonikerName)/sizeof(wszMonikerName[0]),\ L"Elevation:Administrator!new:%s", wszCLSID); if (FAILED(hr)) return hr; memset(&bo, 0, sizeof(bo)); bo.cbStruct = sizeof(bo); bo.hwnd = hwnd; bo.dwClassContext = CLSCTX_LOCAL_SERVER; return CoGetObject(wszMonikerName, &bo, riid, ppv); } 

The key is the prefix Elevation:Administrator!new: to the nickname. This causes a raise request to be launched, and the resulting COM object will be created with a raised token.

+9
source

Source: https://habr.com/ru/post/1206089/


All Articles