在运行时提升权限(Windows API C/C++) [英] Escalate Privilege at Runtime (Windows API C/C++)
问题描述
我的应用程序并不总是需要管理员"权限,而且大部分时间会以当前用户身份运行.有什么办法,我可以通过在我的程序已经运行后在运行时抛出 UAC 来升级 privs 吗?这只会在我需要 privs 时发生.而不是必须从高权限开始.
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.
我知道runas"技术、清单文件等,但所有这些都是在进程创建之前而不是在运行时按需
I know the "runas" technique, manifest file etc. but all these are before the process is created and not at runtime, on-demand
推荐答案
恭喜,这正是 UAC 的设计方式,大多数应用程序开发人员要么太懒惰,要么太害怕,根本不敢考虑:)
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 :)
简而言之,您将需要提升的代码放在单独的 COM 对象(位于 DLL 中)中,然后使用描述的方法创建它的提升实例 此处.
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);
}
关键是名字的 Elevation:Administrator!new:
前缀.这会导致触发提升提示,并且将使用提升的令牌创建生成的 COM 对象.
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.
这篇关于在运行时提升权限(Windows API C/C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!