Skip to content

Instantly share code, notes, and snippets.

@codemercenary
Last active May 10, 2016 21:47
Show Gist options
  • Save codemercenary/4183f37097c508227e33 to your computer and use it in GitHub Desktop.
Save codemercenary/4183f37097c508227e33 to your computer and use it in GitHub Desktop.
Scan the current process for a pattern on Windows
#include <Psapi.h>
#include <vector>
void scan(void* pPattern, size_t ncb) {
static const DWORD pageSize = [] {
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwPageSize;
}();
// Get all modules for this process:
std::vector<HMODULE> hModules;
const HMODULE hSelf = GetModuleHandle(nullptr);
{
DWORD nModules;
EnumProcessModules(GetCurrentProcess(), nullptr, 0, &nModules);
hModules.resize(nModules);
EnumProcessModules(GetCurrentProcess(), &hModules[0], nModules, &nModules);
}
// Find a module of interest
for (auto hModule : hModules) {
if (hModule == hSelf)
continue;
MODULEINFO modinfo;
GetModuleInformation(GetCurrentProcess(), hModule, &modinfo, sizeof(modinfo));
// Need to put this in a lambda because we are mixing SEH with C++ exceptions
auto scan = [] (const void* pMem, size_t ncb, const void* ptr) {
__try {
if (!memcmp(ptr, pMem, ncb))
__debugbreak();
}
__except (EXCEPTION_EXECUTE_HANDLER) {
// Got an exception, here. The whole page has the same protections; we need to advance to the next page.
// Distance from the offset to the end of the page is the amount we have to advance
size_t pageOffset = (reinterpret_cast<size_t>(ptr) & (pageSize - 1));
return pageSize - pageOffset;
}
return 1UL;
};
// Find the scan string in the module somewhere:
const uint8_t* pCur = (uint8_t*) modinfo.lpBaseOfDll;
for (size_t i = 0; i < modinfo.SizeOfImage - sizeof(GUID);)
i += scan(pPattern, ncb, pCur + i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment