Red Team Notes logo Red Team Notes

We will need to enumerate, parse and be able to work with the handles and information of the process threads to inject or hook them.

CreateToolhelp32Snapshot (Classic technique) (WinAPI)

The classic technique to find a process is by creating a snapshots with CreateToolhelp32Snapshot WINAPI. Once done we can iterate over the names in order to match to the desired one.

Takes a snapshot of the specified processes, as well as the heaps, modules, and threads used by these processes.

If the function succeeds, it returns an open handle to the specified snapshot.

HANDLE CreateToolhelp32Snapshot(
  [in] DWORD dwFlags,
  [in] DWORD th32ProcessID
);

dwFlags=TH32CS_SNAPTHREAD -> Includes all threads in the system in the snapshot. To enumerate the threads, see Thread32First, Thread32Next

Example of returning a hThread:

HANDLE FindThread(int pid){

	HANDLE hThread = NULL;
	THREADENTRY32 thEntry;

	thEntry.dwSize = sizeof(thEntry);
	HANDLE Snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
		
	while (Thread32Next(Snap, &thEntry)) {
		if (thEntry.th32OwnerProcessID == pid) 	{
			hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, thEntry.th32ThreadID);
			break;
		}
	}
	CloseHandle(Snap);
	
	return hThread;
}

Example of returning a tid:

int FindThread(int pid){

	THREADENTRY32 thEntry;
	int tid = 0;
	thEntry.dwSize = sizeof(thEntry);
	HANDLE Snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
		
	while (Thread32Next(Snap, &thEntry)) {
		if (thEntry.th32OwnerProcessID == pid) 	{
			tid = thEntry.th32ThreadID;
			break;
		}
	}
	CloseHandle(Snap);
	return tid;
}