Escalate Privilege at Runtime (Windows API C/C++)

て烟熏妆下的殇ゞ 提交于 2021-02-18 06:28:13

问题


My application does not always require "admin" privileges and most of the time would run as the current user. Is there any way, I can escalate privs by throwing up a UAC at runtime after my program is already running? This will only happen as and when I need privs. Rather than having to start with high privs.

I know the "runas" technique, manifest file etc. but all these are before the process is created and not at runtime, on-demand


回答1:


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

In a nutshell, you put the code that needs elevation in a separate COM object (that lives in a DLL), and then you create an elevated instance of it 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 Elevation:Administrator!new: prefix to the moniker name. This causes the elevation prompt to be triggered, and the resulting COM object will be created with an elevated token.



来源:https://stackoverflow.com/questions/26714673/escalate-privilege-at-runtime-windows-api-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!