欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

降权启动应用

最后更新 2022-04-02 22:09:39   阅读量 655

如果应用是管理员权限,它再去启其他进程时也会是管理员权限,那么怎样降权呢?让它以普通用户的权限来启动,下面代码提供了一种实现方法。

注意!!!
WTSQueryUserToken在普通会话下调用总是失败,但是在session 0上的服务是可以调用成功的。

下面是MSDN的官方文档说明:
Obtains the primary access token of the logged-on user specified by the session ID. To call this function successfully, the calling application must be running within the context of the LocalSystem account and have the SE_TCB_NAME privilege.

Caution WTSQueryUserToken is intended for highly trusted services. Service providers must use caution that they do not leak user tokens when calling this function. Service providers must close token handles after they have finished using them.

BOOL runProcessAsUser(const std::string& command, bool isShow) {

HANDLE hToken = NULL;
unsigned long sessionId = 0;
if (!getCurrentSessionId(sessionId)) {
    std::cout << "getCurrentSessionId error";
    return FALSE;
}

if (FALSE == ::WTSQueryUserToken(sessionId, &hToken)) {
    std::cout << "WTSQueryUserToken error";
    return FALSE;
}

PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

LPVOID pPEB;
CreateEnvironmentBlock(&pPEB, hToken, TRUE);

STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.lpDesktop = TEXT("winsta0\\default");
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = isShow ? SW_SHOW : SW_HIDE;

BOOL result = FALSE;
LPSTR pcmd = _strdup(command.c_str());
if (::CreateProcessAsUser(hToken, NULL, pcmd, NULL, NULL, FALSE,
    NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, pPEB, NULL, &si, &pi)) {
    result = TRUE;
} else {
    std::cout << "CreateProcessAsUser error:" << GetLastError() << std::endl;
}

free(pcmd);
DestroyEnvironmentBlock(pPEB);
CloseHandle(hToken);
return result;

}

此代码没有经过严谨的测试,仅供参考。

(转载本站文章请注明作者和出处:泞途 - ningto.com)

下一篇 – beast websocket demo
上一篇 – QProcess 7z.exe 解压进度

  1. Windows

toningto@outlook.com

标签云

IOS Qt Life Linux Java MongoDB Boost MQ Node.js Mac C/C++ Tools Design Python Bug Others Javascript Tips React Android Web Mobile Shell Product Go Database Windows

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2