Enumerating Processes with CreateToolhelp32Snapshot

Here is a quick and dirty example in C++ showing how to use CreateToolhelp32Snapshot to enumerate processes currently running on a Windows machine. This library can also enumerate modules and threads of running processes.

CreateToolhelp32Snapshot is part of the Tool Helper Library.

Malware often uses this library to enumerate processes. Process enumeration is performed by malware for many reasons:

  • Check for antivirus software
  • Detect virtualization or sandboxes
  • Finding suitable processes to inject code into
  • Check if the malware is already running
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <iostream>

DWORD EnumProcs() {
	HANDLE snap;
	PROCESSENTRY32 pe;
	DWORD pid = 0;

	snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (snap == INVALID_HANDLE_VALUE) {
		return GetLastError();
	}

	pe.dwSize = sizeof(PROCESSENTRY32);

	if (!Process32First(snap, &pe)) {
		CloseHandle(snap);
		return GetLastError();
	}

	do {
		std::wcout << pe.th32ProcessID << " " << pe.szExeFile << " " << pe.cntThreads << " " << pe.th32ParentProcessID << std::endl;
	} while (Process32Next(snap, &pe));

	CloseHandle(snap);

	return NO_ERROR;
}

int main() {
	EnumProcs();
	return NO_ERROR;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s