-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathUI.cpp
More file actions
314 lines (266 loc) · 10.2 KB
/
Copy pathUI.cpp
File metadata and controls
314 lines (266 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#include "pch.h"
#include <windows.h>
#include <psapi.h>
#include <tlhelp32.h>
#include <locale>
#include <codecvt>
#include <vector>
#include <map>
#include "..\driver\public.h"
#include "findPFNDatabase.h"
class statistics {
public:
statistics()
{
scannedPages = ignoredPagesNX = scannedProcesses = modifiedPages = 0;
}
unsigned int scannedPages;
unsigned int ignoredPagesNX;
unsigned int scannedProcesses;
unsigned int modifiedPages;
};
class modifiedPage {
public:
modifiedPage(DWORD newProcessID, wchar_t* newModuleName, void* newPageBase, BYTE newSectionName[8], unsigned long long newSectionOffset);
unsigned long processID;
std::wstring moduleName;
unsigned long long pageBase;
std::wstring sectionName;
unsigned long long sectionOffset;
};
modifiedPage::modifiedPage(DWORD newProcessID, wchar_t* newModuleName, void* newPageBase, BYTE newSectionName[8], unsigned long long newSectionOffset)
: processID(newProcessID), moduleName(newModuleName), pageBase((unsigned long long)newPageBase), sectionName(L""), sectionOffset(newSectionOffset)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring secName = std::wstring(converter.from_bytes((char*)newSectionName, (char*)&newSectionName[7]));
size_t nullPos = secName.find(L'\0');
if (nullPos != secName.npos)
secName = secName.substr(0, nullPos);
sectionName.append(secName);
}
BOOL EnableDebugPrivilege(BOOL bEnable)
{
HANDLE hToken = nullptr;
LUID luid;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) return FALSE;
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) return FALSE;
TOKEN_PRIVILEGES tokenPriv;
tokenPriv.PrivilegeCount = 1;
tokenPriv.Privileges[0].Luid = luid;
tokenPriv.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
if (!AdjustTokenPrivileges(hToken, FALSE, &tokenPriv, sizeof(TOKEN_PRIVILEGES), NULL, NULL)) return FALSE;
return TRUE;
}
int scanProcess(HANDLE driverHnd, DWORD targetPID, HANDLE toScanHandle, std::vector<modifiedPage> *resultsOut, statistics* stats)
{
DWORD cbNeeded;
int s = EnumProcessModules(toScanHandle, NULL, 0, &cbNeeded);
if (s == 0)
{
printf("Couldn't call EnumProcessModules to get buffer size, gle %d\n", GetLastError());
return -1;
}
HMODULE* moduleList = (HMODULE*)malloc(cbNeeded);
memset(moduleList, 0, cbNeeded);
s = EnumProcessModules(toScanHandle, moduleList, cbNeeded, &cbNeeded);
if (s == 0)
{
// This'll happen sometimes if there's a module loaded between our calls.
// TODO: we can retry in this case.
printf("Couldn't call EnumProcessModules to get modules, gle %d.\n", GetLastError());
return -1;
}
for (HMODULE* thisModPtr = &moduleList[0]; thisModPtr < &moduleList[cbNeeded / sizeof(HMODULE)]; thisModPtr++)
{
HMODULE thisModule = *thisModPtr;
TCHAR szModName[MAX_PATH];
memset(szModName, 0, MAX_PATH * sizeof(TCHAR));
if (GetModuleFileNameEx(toScanHandle, thisModule, szModName, sizeof(szModName) / sizeof(TCHAR)) == 0)
{
printf("GetModuleFileNameEx failed, GLE %d\n", GetLastError());
continue;
}
IMAGE_DOS_HEADER mz;
SIZE_T bytesRead;
if (!ReadProcessMemory(toScanHandle, thisModule, &mz, sizeof(IMAGE_DOS_HEADER), &bytesRead))
{
printf("Can't read module MZ header\n");
return -1;
}
if (mz.e_magic != IMAGE_DOS_SIGNATURE)
{
printf("MZ header not found\n");
continue;
}
IMAGE_NT_HEADERS pe;
unsigned long long peAddress = (((unsigned long long)thisModule) + mz.e_lfanew);
if (!ReadProcessMemory(toScanHandle, (void*)peAddress, &pe, sizeof(IMAGE_NT_HEADERS), &bytesRead))
{
printf("Can't read module PE header\n");
return -1;
}
if (pe.Signature != IMAGE_NT_SIGNATURE)
{
printf("PE header not found\n");
continue;
}
IMAGE_SECTION_HEADER* sect;
unsigned long long firstSectionAddress = peAddress + FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + sizeof(IMAGE_OPTIONAL_HEADER);
sect = (IMAGE_SECTION_HEADER*)malloc(sizeof(IMAGE_SECTION_HEADER) * pe.FileHeader.NumberOfSections);
if (!ReadProcessMemory(toScanHandle, (LPCVOID)(firstSectionAddress), sect, sizeof(IMAGE_SECTION_HEADER) * pe.FileHeader.NumberOfSections, &bytesRead))
{
printf("Can't read first section of module\n");
return -1;
}
for (unsigned long sectionIndex = 0; sectionIndex < pe.FileHeader.NumberOfSections; sectionIndex++)
{
IMAGE_SECTION_HEADER* thisSection = §[sectionIndex];
unsigned long long relocatedSectionBase = thisSection->VirtualAddress + (unsigned long long)thisModule;
// We are interested only in executable sections.
// TODO: check that discardable pages are zero'ed out?
// TODO: check that non-executable pages haven't been made executable?
if ((thisSection->Characteristics & IMAGE_SCN_MEM_EXECUTE) == 0)
{
stats->ignoredPagesNX += (thisSection->SizeOfRawData / 0x1000);
// printf("%ls!%s (at %p) is not executable, skipping\n", szModName, thisSection->Name, relocatedSectionBase);
continue;
}
//printf("scanning %ls!%s (at %p), size 0x%08lx\n", szModName, thisSection->Name, relocatedSectionBase, thisSection->SizeOfRawData);
int dirtyPages = 0;
int errorPages = 0;
getPageInfoRequest req;
req.pageToCheck = relocatedSectionBase;
// Work out how many pages we will check
req.numberOfPagesToCheck = thisSection->Misc.VirtualSize / 0x1000;
if (thisSection->Misc.VirtualSize % 0x1000 != 0)
req.numberOfPagesToCheck++;
req.targetPID = targetPID;
getPageInfoResponse* resp = (getPageInfoResponse*)malloc(sizeof(getPageInfoRequest) * req.numberOfPagesToCheck);
memset(resp, 0x00, sizeof(getPageInfoResponse) * req.numberOfPagesToCheck);
DWORD bytesRet;
s = DeviceIoControl(driverHnd, IOCTL_DRIVER_QUERY_VA, &req, sizeof(req), resp, sizeof(getPageInfoResponse) * req.numberOfPagesToCheck, &bytesRet, NULL);
if (s == 0)
{
errorPages++;
printf("DeviceIoControl failed, GLE %d\n", GetLastError());
return -1;
}
stats->scannedPages += req.numberOfPagesToCheck;
for (unsigned int n = 0; n < req.numberOfPagesToCheck; n++)
{
unsigned long long pageAddress = relocatedSectionBase + (n * 0x1000);
if (!resp[n].isValid)
{
printf("Page at 0x%016llx (%ls!%s) not valid (maybe it's paged out?) 0x%08lx\n", pageAddress, szModName, thisSection->Name, thisSection->Characteristics);
errorPages++;
continue;
}
if (resp[n].isDirty)
{
dirtyPages++;
resultsOut->push_back(modifiedPage(targetPID, (wchar_t*)szModName, (void*)pageAddress, thisSection->Name, (pageAddress - relocatedSectionBase)));
stats->modifiedPages++;
}
}
// if (dirtyPages == 0)
// printf("Module %ls: OK\n", szModName);
// else
// printf("Module %ls: detected %d dirty pages!\n", szModName, dirtyPages);
}
}
return 0;
}
int setPFNDatabase(HANDLE driverHnd, unsigned long long PFNDatabaseStart)
{
setPFNDatabaseRequest req;
req.offsetToMmPfnDatabaseInNtDllFromExAllocatePoolWithTag = PFNDatabaseStart;
DWORD bytesRet;
int s = DeviceIoControl(driverHnd, IOCTL_DRIVER_SET_PFN_DATABASE, &req, sizeof(req), NULL, 0, &bytesRet, NULL);
if (s == 0)
{
printf("Failed to set PFN database to 0x%016llx: GLE %d\n", PFNDatabaseStart, GetLastError());
return -1;
}
return 0;
}
int main()
{
EnableDebugPrivilege(TRUE);
HANDLE driverHnd = CreateFile(L"\\\\.\\cowspot", GENERIC_ALL, 0, NULL, OPEN_EXISTING, 0, NULL);
if (driverHnd == INVALID_HANDLE_VALUE)
{
printf("Couldn't open driver device '%ls', gle %d\n", DOS_DEVICE_NAME, GetLastError());
return -1;
}
if (setPFNDatabase(driverHnd, findPFNDatabase()) != 0)
return -1;
HANDLE snapshotHnd = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (snapshotHnd == INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot failed, GLE %d\n", GetLastError());
return -1;
}
PROCESSENTRY32 proc;
memset(&proc, 0, sizeof(PROCESSENTRY32));
proc.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(snapshotHnd, &proc))
{
printf("Process32First failed, GLE %d\n", GetLastError());
return -1;
}
statistics stat;
std::vector<modifiedPage> results;
unsigned long start = GetTickCount();
while (Process32Next(snapshotHnd, &proc))
{
HANDLE toScanHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, proc.th32ProcessID);
if (toScanHandle == NULL)
{
printf("Couldn't open target process with PID %d ('%ls'), gle %d\n", proc.th32ProcessID, proc.szExeFile, GetLastError());
continue;
}
stat.scannedProcesses++;
if (scanProcess(driverHnd, proc.th32ProcessID, toScanHandle, &results, &stat) != 0)
printf("Failed to scan process '%ls'\n", proc.szExeFile);
// else
// printf("Scanned process '%ls'\n", proc.szExeFile);
CloseHandle(toScanHandle);
}
CloseHandle(snapshotHnd);
unsigned long end = GetTickCount();
printf("Scan took %dms\n", (end - start));
// Print some stats and the results. Each page is 4KB, so 256 pages is 1MB.
printf("Scanned %d pages (%d MB), ignored %d NX pages (%d MB), totalling %d pages (%d MB). Found %d modified pages (%.02f MB).\n",
stat.scannedPages, stat.scannedPages / 256,
stat.ignoredPagesNX, stat.scannedPages / 256,
stat.ignoredPagesNX + stat.scannedPages, (stat.ignoredPagesNX + stat.scannedPages) / 256,
stat.modifiedPages, ((float)stat.modifiedPages) / 256);
for (unsigned int n = 0; n < results.size(); n++)
{
modifiedPage thisModifiedPage = results[n];
printf("PID %04d module '%ls', section %S, offset 0x%08llx\n", thisModifiedPage.processID, thisModifiedPage.moduleName.c_str(), thisModifiedPage.sectionName.c_str(), thisModifiedPage.sectionOffset);
/*
HANDLE toScanHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, thisModifiedPage.processID);
if (toScanHandle == NULL)
{
printf("Couldn't open target process with PID %d ('%ls'), gle %d\n", proc.th32ProcessID, proc.szExeFile, GetLastError());
continue;
}
SIZE_T bytesRead;
unsigned char* pageContents[0x2000];
memset(pageContents, 0, 0x2000);
if (!ReadProcessMemory(toScanHandle, (LPCVOID)thisModifiedPage.pageBase, pageContents, 0x2000, &bytesRead))
{
printf("ReadProcessMemory failed\n");
continue;
}
for (unsigned int n = 0; n < 0x2001; n++)
{
printf("0x%02hhx ", (unsigned)pageContents[n]);
if (n % 0x10 == 0)
printf("\n0x%08lx: ", n);
}
CloseHandle(toScanHandle);*/
}
return 0;
}