Created
January 8, 2018 22:08
-
-
Save Ostoic/1e27c77e6fa1d19125fff445a4df5a2a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <Windows.h> | |
#include <Tlhelp32.h> | |
// The normal Toolhelp32.h process snapshot enumeration. This example was taken | |
// mostly from MSDN, with a few modifications. | |
std::vector<int> test_toolhelp() | |
{ | |
std::vector<int> pids; | |
PROCESSENTRY32 entry; | |
entry.dwSize = sizeof(entry); | |
// Create snapshot of processes | |
HANDLE snapHandle = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); | |
if (snapHandle == INVALID_HANDLE_VALUE) | |
return {}; | |
entry.dwSize = sizeof(PROCESSENTRY32); | |
if (!::Process32First(snapHandle, &entry)) | |
{ | |
::CloseHandle(snapHandle); | |
return {}; | |
} | |
do | |
{ | |
HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, false, entry.th32ProcessID); | |
if (handle) | |
{ | |
pids.push_back(entry.th32ProcessID); | |
CloseHandle(handle); | |
} | |
} while (::Process32Next(snapHandle, &entry)); | |
// Cleanup snapshot handle | |
::CloseHandle(snapHandle); | |
return pids; | |
} | |
// PID Bruteforce: Loop from 4 to pidMax and test each pid for a valid handle. | |
std::vector<int> test_pidb() | |
{ | |
std::vector<int> pids; | |
// Arbitrary max pid for testing. | |
std::size_t pidMax = 0x4E1C; | |
for (int pid = 4; pid <= pidMax; pid += 4) // process ids ++ by 4 | |
{ | |
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, false, pid); | |
if (handle) | |
{ | |
pids.push_back(pid); | |
CloseHandle(handle); | |
} | |
} | |
return pids; | |
} | |
int main() | |
{ | |
// Enumerate list of process pids. | |
std::vector<int> pidbPids = test_pidb(); | |
std::vector<int> thPids = test_toolhelp(); | |
// Display how many pids each method obtained. | |
std::cout << "Results:\n"; | |
std::cout << "Pidb: " << pidbPids.size() << " handles\n"; | |
std::cout << "TH: " << thPids.size() << " handles\n\n"; | |
// Check pidb results against toolhelp results. | |
for (auto pid : pidbPids) | |
{ | |
auto it = std::find(thPids.begin(), thPids.end(), pid); | |
if (it == thPids.end()) | |
std::cout << "Pid " << pid << " was not in the process snapshot!\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment