Windows Service Create a privilege Process in spicefied session

东朴 虞 0 Reputation points
2024-09-06T04:51:21.3766667+00:00

I create a process in current session in Windows service but it has only current user privileges.

But now I want to create a privilege process in specified session from code in Windows service, What shall I do?

Here is my code below

BOOL RunInSession(int nSessionID)
{
	std::wstring szPath = GetAppDirectory();
	szPath += L"\\";
	szPath += pExeFile;
	HANDLE primaryToken = GetSessionUserToken(nSessionID);
	if (primaryToken == 0)
	{
		return FALSE;
	}

	STARTUPINFO StartupInfo = {0};
	PROCESS_INFORMATION processInfo;
	StartupInfo.cb = sizeof(STARTUPINFO);

	void* lpEnvironment = NULL;
	BOOL resultEnv = ::CreateEnvironmentBlock(&lpEnvironment, primaryToken, FALSE);
	if (resultEnv == 0)
	{     
		::CloseHandle(primaryToken);
		return FALSE;
	}

	//std::wstring szITAuditExeFile = MAIN_APP_NAME
	std::wstring szArgs = L" ";
	szArgs += szServiceLaunchAPPCmd;
	TCHAR szTmpArgs[512];
	ZeroMemory(&szTmpArgs[0],sizeof(szTmpArgs));
	wcsncpy(szTmpArgs, szArgs.c_str(), min(512-1,szArgs.length()));


	BOOL result = ::CreateProcessAsUser(primaryToken, (LPTSTR)(szPath.c_str()), &szTmpArgs[0], NULL, NULL, FALSE, 
	CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, 0, &StartupInfo, &processInfo);
	
	::DestroyEnvironmentBlock(lpEnvironment);
	::CloseHandle(primaryToken);


	return result;
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,693 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.