Le service démarre avec l'usager System Local donc pour démarrer une
application au nom de l'usager il faut démarrer celle-ci avec
CreateProcessAsUser. Il faut aller chercher le token de l'usager dans
la session console active.
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <vector>
#include <string>
#include <ShellAPI.h>
#include <userenv.h>
#include <winnt.h>
#include <WtsApi32.h>
#include <process.h>
HANDLE currentToken = 0;
HANDLE primaryToken = 0;
int dwSessionId = 0;
HANDLE hUserToken = 0;
HANDLE hTokenDup = 0;
PWTS_SESSION_INFO pSessionInfo = 0;
DWORD dwCount = 0;
//Get User Token
WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &dwCount);
int dataSize = sizeof(WTS_SESSION_INFO);
for (DWORD i = 0; i < dwCount; ++i)
{
WTS_SESSION_INFO si = pSessionInfo[i];
if (WTSActive == si.State)
{
dwSessionId = si.SessionId;
break;
}
}
WTSFreeMemory(pSessionInfo);
BOOL bRet = WTSQueryUserToken(dwSessionId, ¤tToken);
int errorcode = GetLastError();
if(bRet == false)
{
bLoggedUser = false;
}
else
{
bLoggedUser = true;
}
bRet = DuplicateTokenEx(currentToken, TOKEN_ASSIGN_PRIMARY |
TOKEN_ALL_ACCESS, 0, SecurityImpersonation, TokenPrimary,
&primaryToken);
errorcode = GetLastError();
if (bRet == false)
{
//return 0;
}
if (primaryToken == 0)
{
}
STARTUPINFO StartupInfo = {0};
PROCESS_INFORMATION processInfo;
StartupInfo.cb = sizeof(STARTUPINFO);
STARTUPINFO si = { sizeof(STARTUPINFO) };
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
LPVOID pEnvironment = NULL;
bRet = CreateEnvironmentBlock(&pEnvironment, primaryToken, TRUE);
if (!bRet) {
//hr = GetLastError();
//return hr;
}
.....
CreateProcessAsUser(primaryToken,L"c:\\application.exe",NULL,
NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT , pEnvironment, NULL,
&si, &pi);
DestroyEnvironmentBlock(pEnvironment);
CloseHandle(primaryToken);
CloseHandle(currentToken);
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
Aucun commentaire:
Publier un commentaire