2024年3月9日发(作者:)
CreateProcessAsUser
在微软的MSDN文档里,讲到用LogonUser+DuplicateTokenEx+CreateProcessAsUser来以一
个新用户身份去运行一个新线程,然而一个问题就是如果新用户是User组,而不是类似
Administrator等权限高的用户的时候,会运行时错误退出,原因是要附加一个
"winsta0default"以及桌面运行权限。For example, if the process that was started was trying to
create a window, the process would have to have DESKTOP_CREATEWINDOW access to the
desktop object. If the process has not been granted this access right, an error would occur in the
file, which would cause the system error box to appear and the process would fail to
start.
正确代码见下文。
但要注意的一点是,SetUserObjectSecurity may gives error code
ERROR_NOT_ENOUGH_QUOTA. If you call SetUserObjectSecurity millions.
所以使用类似代码的时候要格外小心,一个较好的办法是LogonUser得到的HTOKEN保存
起来,下次要使用相同的用户的时候就直接使用该HTOKEN,如果这样做,那么请不要对
HTOKEN使用CloseHandle,否则保存的值无效,但你就很可能在程序结束后也没有使用
CloseHandle,不过不关闭这个句柄会有什么后果就不太清楚。但如果不这样做,那么事实
上调用并不需要很多次(大约84次)就会出现 ERROR_NOT_ENOUGH_QUOTA的结果
以下代码来自MSDN,本人有改动
#define RTN_OK 0
#define RTN_ERROR 13
#define WINSTA_ALL (WINSTA_ACCESSCLIPBOARD |
WINSTA_ACCESSGLOBALATOMS |
WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS |
WINSTA_ENUMERATE | WINSTA_EXITWINDOWS |
WINSTA_READATTRIBUTES | WINSTA_READSCREEN |
WINSTA_WRITEATTRIBUTES | DELETE |
READ_CONTROL | WRITE_DAC |
WRITE_OWNER)
#define DESKTOP_ALL (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD |
DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP |
DESKTOP_WRITEOBJECTS | DELETE |
READ_CONTROL | WRITE_DAC |
WRITE_OWNER)
#define GENERIC_ACCESS (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE |
GENERIC_ALL)
#include
#include
#define __try for(int _n=0;_n==0;++_n)
#define __leave break
#define __finally ;
BOOL ObtainSid(
HANDLE hToken, // Handle to an process access token.
PSID *psid // ptr to the buffer of the logon sid
);
void RemoveSid(
PSID *psid // ptr to the buffer of the logon sid
);
BOOL AddTheAceWindowStation(
HWINSTA hwinsta, // handle to a windowstation
PSID psid // logon sid of the process
);
BOOL AddTheAceDesktop(
HDESK hdesk, // handle to a desktop
PSID psid // logon sid of the process
);
int main(void)
{
HANDLE hToken;
HDESK hdesk;
HWINSTA hwinsta;
PROCESS_INFORMATION pi;
PSID psid;
STARTUPINFO si;
if (!LogonUser(
"test",
NULL,
"onlinejudge",
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
&hToken))
{
return RTN_ERROR;
}
hwinsta = OpenWindowStation(
"winsta0",
FALSE,
READ_CONTROL | WRITE_DAC
);
if (hwinsta == NULL)
return RTN_ERROR;
HWINSTA hwinstaold = GetProcessWindowStation();


发布评论