The Win32 Debug API
by Fritz Lowery


Listing One
// Get token for this process
HANDLE token;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) == false)
{
	printf("OpenProcessToken Failed: 0x%X\n", GetLastError());
	exit(-1);
}

//Get LUID for shutdown privilege}
TOKEN_PRIVILEGES tkp;
if(LookupPrivilegeValue(NULL, "SeDebugPrivilege", &tkp.Privileges[0].Luid) == false)
{
	printf("LookupPrivilegeValue failed: 0x%X\n", GetLastError());
	exit(-1);
}

tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

if(AdjustTokenPrivileges(token, false, &tkp, 0, NULL, NULL) == false)
{
	printf("AdjustTokenPrivileges Failed: 0x%X\n", GetLastError());
	exit(-1);
}



Listing Two
HANDLE hProc = INVALID_HANDLE_VALUE;
if(isdigit(sCL[0]) == 0)
{
	STARTUPINFO rStartup;
	ZeroMemory(&rStartup, sizeof(rStartup));
	rStartup.cb = sizeof(rStartup);
	PROCESS_INFORMATION rProc;
	char aCL[2048];
	CopyMemory(aCL, sCL, sCL.GetLength());
	if(CreateProcess(NULL, aCL, NULL, NULL, true, DEBUG_PROCESS, NULL,                                           NULL, &rStartup, &rProc) == false)
	{
		printf("Could not start process commandline: %s\n", sCL);
		exit(-1);
	}
	hProc = rProc.hProcess;

	printf("Attempting to debug: %s\n", aCL);
}
else
{
	// debugging a running process viathe PID
	int iPid = atoi(sCL);
	if(DebugActiveProcess(iPid) == false)
	{
		printf("Error: DebugActiveProcess: %d\n", GetLastError());
		exit(-2);
	}
	hProc = OpenProcess(PROCESS_ALL_ACCESS, false, iPid);
	if(hProc == NULL)
	{
		printf("Error OpenProcess: %d\n", GetLastError());
		exit(-3);
	}
}


Listing Three
case OUTPUT_DEBUG_STRING_EVENT: { 
	char *aBuf = new char[deDebugger.u.DebugString.nDebugStringLength];
	DWORD dwRead;
	ReadProcessMemory(hProc, deDebugger.u.DebugString.lpDebugStringData, aBuf, deDebugger.u.DebugString.nDebugStringLength, &dwRead);
	printf("%s", aBuf);
	delete aBuf;
	break;
}

Listing Four
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
    printf("Process ID = %ld\n",GetCurrentProcessId());
	while(1)
	{
		OutputDebugString("I'm a little teapot\n");
		Sleep(1000);
		OutputDebugString("Short and stout\n");
		Sleep(1000);
		OutoutDebugString("Here is my handle\n");
		Sleep(1000);
		OutputDebugString("Here is my spout\n\n");
		Sleep(1000);
	}
	exit(0);
}




2


