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;
}