Skip to content

Instantly share code, notes, and snippets.

@malkia
Created February 1, 2025 22:57
Show Gist options
  • Save malkia/11fa1dc980196c15123cb5bb0477991a to your computer and use it in GitHub Desktop.
Save malkia/11fa1dc980196c15123cb5bb0477991a to your computer and use it in GitHub Desktop.
wts
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <WtsApi32.h>
#include <conio.h>
#pragma comment(lib,"Wtsapi32.lib")
#define MAX_LENGTH 250
bool SpawnProcess(const WCHAR *path)
{
WCHAR buffer[MAX_LENGTH];
LPWSTR pUserName = nullptr;
// First have to find a valid session/user (services run as SYSTEM)
DWORD sessionId = 0;
bool sessionFound = false;
WTS_SESSION_INFO_1W* sessions{};
DWORD sessionCount{};
DWORD level{ 1 };
if (!WTSEnumerateSessionsExW(WTS_CURRENT_SERVER_HANDLE, &level, 0, &sessions, &sessionCount))
{
goto Fail;
}
for (size_t i = 0; i < sessionCount; i++)
{
const auto& session = sessions[i];
printf("%zd: ExecEnvId=%u id=%u State=%d name=%S host=%S user=%S domain=%S farm=%S\n", i, session.ExecEnvId, session.SessionId, session.State, session.pSessionName, session.pHostName, session.pUserName, session.pDomainName, session.pFarmName);
}
for (size_t i = 0; i < sessionCount; i++)
{
sessionId = sessions[i].SessionId;
WTS_CONNECTSTATE_CLASS* pwtsConnectState{};
DWORD bytesReturned{};
if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSConnectState, reinterpret_cast<LPWSTR*>(&pwtsConnectState), &bytesReturned))
{
const auto wtsConnectState{ *pwtsConnectState };
WTSFreeMemory(pwtsConnectState);
if (wtsConnectState == WTSActive)
{
sessionFound = true;
break;
}
}
}
if (!sessionFound)
{
StringCchPrintfW(buffer, MAX_LENGTH, L"No active session found in %d sessions", sessionCount);
printf("%S\n", buffer);
goto Fail;
}
// Find the active session username
DWORD bytesReturned = 0;
if (!WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName,
&pUserName, &bytesReturned))
{
StringCchPrintfW(buffer, MAX_LENGTH, L"Unable to acquire session username (0x%X)", GetLastError());
printf("%S\n", buffer);
goto Fail;
}
printf("userName: %S\n", pUserName);
WTSFreeMemoryExW(WTSTypeSessionInfoLevel1, sessions, sessionCount);
sessions = nullptr;
sessionCount = 0;
return true;
Fail:
return false;
}
int main()
{
SpawnProcess(L"cmd /c dir");
fflush(stdout);
_getch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment