summaryrefslogtreecommitdiff
path: root/plugins/PluginUpdater/src/checksum.cpp
blob: 73d8a30734a7d152f1b69d608a45b0b31b1d6c72 (plain)
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

// Checksum Tool
// By Bio (C) 2012

#include "stdafx.h"

// Return codes
#define RESULT_OK			0
#define RESULT_NOTFOUND		10
#define RESULT_READERROR	20
#define RESULT_NOTPE		30
#define RESULT_CORRUPTED	40
#define RESULT_INVALID		50
#define RESULT_NONE			100

#define DEBUG_SECTIONS		1
#define DEBUG_REALLOCS		1

int debug = 0;
DWORD dwVersion = 0;

#pragma comment(lib, "version.lib")

struct MFileMapping
{
	PBYTE  ptr;
	HANDLE hMap, hFile;

	MFileMapping(const wchar_t* ptszFileName)
	{
		ptr = nullptr;
		hMap = nullptr;

		hFile = CreateFile(ptszFileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if (hFile != INVALID_HANDLE_VALUE)
			hMap = CreateFileMapping(hFile, nullptr, PAGE_WRITECOPY, 0, 0, nullptr);
		if (hMap)
			ptr = (PBYTE)MapViewOfFile(hMap, FILE_MAP_COPY, 0, 0, 0);
	}

	~MFileMapping()
	{
		if (ptr)
			UnmapViewOfFile(ptr);

		if (hMap)
			CloseHandle(hMap);

		if (hFile != INVALID_HANDLE_VALUE)
			CloseHandle(hFile);
	}
};

static void PatchResourcesDirectory(PIMAGE_RESOURCE_DIRECTORY pIRD, PBYTE pBase, DWORD dwType);

static void PatchResourceEntry(PIMAGE_RESOURCE_DIRECTORY_ENTRY pIRDE, PBYTE pBase, DWORD dwType)
{
	if (pIRDE->DataIsDirectory)
		PatchResourcesDirectory(PIMAGE_RESOURCE_DIRECTORY(pBase + pIRDE->OffsetToDirectory), pBase, dwType == 0 ? pIRDE->Name : dwType);
	else if (dwType == 16) {
		PIMAGE_RESOURCE_DATA_ENTRY pItem = PIMAGE_RESOURCE_DATA_ENTRY(pBase + pIRDE->OffsetToData);
		dwVersion = pItem->OffsetToData;
	}
}

static void PatchResourcesDirectory(PIMAGE_RESOURCE_DIRECTORY pIRD, PBYTE pBase, DWORD dwType)
{
	UINT i;
	pIRD->TimeDateStamp = 0;

	PIMAGE_RESOURCE_DIRECTORY_ENTRY pIRDE = PIMAGE_RESOURCE_DIRECTORY_ENTRY(pIRD + 1);
	for (i = 0; i < pIRD->NumberOfNamedEntries; i++, pIRDE++)
		PatchResourceEntry(pIRDE, pBase, dwType);

	for (i = 0; i < pIRD->NumberOfIdEntries; i++, pIRDE++)
		PatchResourceEntry(pIRDE, pBase, dwType);
}

__forceinline bool Contains(PIMAGE_SECTION_HEADER pISH, DWORD address, DWORD size = 0)
{
	return (address >= pISH->VirtualAddress && address + size <= pISH->VirtualAddress + pISH->SizeOfRawData);
}

int CalculateModuleHash(const wchar_t *filename, char *szDest)
{
	MFileMapping map(filename);
	if (map.hFile == INVALID_HANDLE_VALUE)
		return RESULT_NOTFOUND;

	if (map.ptr == nullptr)
		return RESULT_READERROR;

	// check minimum and maximum size
	DWORD hsize = 0, filesize = GetFileSize(map.hFile, &hsize);
	if (!filesize || filesize == INVALID_FILE_SIZE || hsize)
		return RESULT_INVALID;

	if (filesize < sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS))
		return RESULT_NOTPE;

	mir_md5_state_t pms;
	mir_md5_init(&pms);

	PIMAGE_DOS_HEADER pIDH = (PIMAGE_DOS_HEADER)map.ptr;
	if (pIDH->e_magic != IMAGE_DOS_SIGNATURE) {
LBL_NotPE:
		mir_md5_append(&pms, map.ptr, filesize);
	}
	else {
		PIMAGE_NT_HEADERS pINTH = (PIMAGE_NT_HEADERS)(map.ptr + pIDH->e_lfanew);
		if ((PBYTE)pINTH + sizeof(IMAGE_NT_HEADERS) >= map.ptr + filesize)
			return RESULT_CORRUPTED;
		
		if (pINTH->Signature != IMAGE_NT_SIGNATURE)
			goto LBL_NotPE;

		WORD  machine = pINTH->FileHeader.Machine;
		DWORD sections = pINTH->FileHeader.NumberOfSections;
		if (!sections)
			return RESULT_INVALID;

		PIMAGE_DATA_DIRECTORY pIDD = nullptr;
		PIMAGE_DEBUG_DIRECTORY pDBG = nullptr;
		PBYTE pRealloc = nullptr;
		ULONGLONG base = 0;

		// try to found correct offset independent of architectures
		DWORD offset = pIDH->e_lfanew + pINTH->FileHeader.SizeOfOptionalHeader + sizeof(IMAGE_NT_HEADERS) - sizeof(IMAGE_OPTIONAL_HEADER);

		if ((machine == IMAGE_FILE_MACHINE_I386) &&
			(pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER32)) &&
			(pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)) {
			pIDD = (PIMAGE_DATA_DIRECTORY)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS32, OptionalHeader.DataDirectory));
			base = *(DWORD*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS32, OptionalHeader.ImageBase));
		}
		else if ((machine == IMAGE_FILE_MACHINE_AMD64) &&
			(pINTH->FileHeader.SizeOfOptionalHeader >= sizeof(IMAGE_OPTIONAL_HEADER64)) &&
			(pINTH->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)) {
			pIDD = (PIMAGE_DATA_DIRECTORY)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS64, OptionalHeader.DataDirectory));
			base = *(ULONGLONG*)((PBYTE)pINTH + offsetof(IMAGE_NT_HEADERS64, OptionalHeader.ImageBase));
		}
		else return RESULT_CORRUPTED;

		// Debugging information entry
		DWORD dbgAddr = pIDD[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
		DWORD dbgSize = pIDD[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;

		// Export information entry
		DWORD expAddr = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
		DWORD expSize = pIDD[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;

		// Resource directory
		DWORD resAddr = pIDD[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
		DWORD resSize = pIDD[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;

		// Reallocation information entry
		DWORD relocAddr = pIDD[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
		DWORD relocSize = pIDD[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;

		// verify image integrity
		for (DWORD idx = 0; idx < sections; idx++) {
			PIMAGE_SECTION_HEADER pISH = (PIMAGE_SECTION_HEADER)(map.ptr + offset + idx * sizeof(IMAGE_SECTION_HEADER));
			if (((PBYTE)pISH + sizeof(IMAGE_SECTION_HEADER) > map.ptr + filesize) || (pISH->PointerToRawData + pISH->SizeOfRawData > filesize))
				return RESULT_CORRUPTED;

			// erase timestamp
			if (dbgSize >= sizeof(IMAGE_DEBUG_DIRECTORY) && Contains(pISH, dbgAddr, dbgSize)) {
				DWORD shift = dbgAddr - pISH->VirtualAddress;
				pDBG = (PIMAGE_DEBUG_DIRECTORY)(map.ptr + shift + pISH->PointerToRawData);
				for (int i = dbgSize / sizeof(IMAGE_DEBUG_DIRECTORY); i > 0; i--)
					pDBG[i - 1].TimeDateStamp = 0;
			}

			// erase export timestamp
			if (expSize >= sizeof(IMAGE_EXPORT_DIRECTORY) && Contains(pISH, expAddr, expSize)) {
				DWORD shift = expAddr - pISH->VirtualAddress;
				PIMAGE_EXPORT_DIRECTORY pEXP = (PIMAGE_EXPORT_DIRECTORY)(map.ptr + shift + pISH->PointerToRawData);
				pEXP->TimeDateStamp = 0;
			}

			// find realocation table
			if ((relocSize >= sizeof(IMAGE_BASE_RELOCATION)) && Contains(pISH, relocAddr, relocSize)) {
				DWORD shift = relocAddr - pISH->VirtualAddress;
				pRealloc = map.ptr + shift + pISH->PointerToRawData;
			}
		}

		for (size_t idx = 0; idx < sections; idx++) {
			PIMAGE_SECTION_HEADER pISH = (PIMAGE_SECTION_HEADER)(map.ptr + offset + idx * sizeof(IMAGE_SECTION_HEADER));

			if (((PBYTE)pISH + sizeof(IMAGE_SECTION_HEADER) > map.ptr + filesize) || (pISH->PointerToRawData + pISH->SizeOfRawData > filesize))
				return RESULT_CORRUPTED;

			// erase debug information
			if (pDBG && pDBG->SizeOfData > 0)
				if (pDBG->PointerToRawData >= pISH->PointerToRawData && pDBG->PointerToRawData + pDBG->SizeOfData <= pISH->PointerToRawData + pISH->SizeOfRawData)
					ZeroMemory(map.ptr + pDBG->PointerToRawData, pDBG->SizeOfData);

			// patch resources
			if (resSize > 0 && Contains(pISH, resAddr, resSize)) {
				dwVersion = 0;

				DWORD shift = resAddr - pISH->VirtualAddress + pISH->PointerToRawData;
				IMAGE_RESOURCE_DIRECTORY *pIRD = (IMAGE_RESOURCE_DIRECTORY*)(map.ptr + shift);
				PatchResourcesDirectory(pIRD, map.ptr + shift, 0);

				// patch version
				if (dwVersion) {
					shift = dwVersion - pISH->VirtualAddress + pISH->PointerToRawData;

					UINT blockSize;
					VS_FIXEDFILEINFO *vsffi;
					VerQueryValue(map.ptr + shift, L"\\", (PVOID*)&vsffi, &blockSize);
					vsffi->dwProductVersionLS = vsffi->dwProductVersionMS = 0;
				}
			}

			// rebase to zero address
			if (pRealloc) {
				DWORD blocklen = relocSize;
				PIMAGE_BASE_RELOCATION pIBR = (PIMAGE_BASE_RELOCATION)pRealloc;
				while (pIBR) {
					if (Contains(pISH, pIBR->VirtualAddress) && pIBR->SizeOfBlock <= blocklen) {
						DWORD shift = pIBR->VirtualAddress - pISH->VirtualAddress + pISH->PointerToRawData;
						int len = pIBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION);
						PWORD pw = (PWORD)((PBYTE)pIBR + sizeof(IMAGE_BASE_RELOCATION));

						while (len > 0) {
							DWORD type = *pw >> 12;
							DWORD addr = (*pw & 0x0FFF);
							PBYTE pAddr = map.ptr + shift + addr;

							switch (type) {
							case IMAGE_REL_BASED_HIGHLOW:
								if (addr + pIBR->VirtualAddress + sizeof(DWORD) >= pISH->VirtualAddress + pISH->SizeOfRawData) {
									len = 0;
									break;
								}
								*(PDWORD)pAddr = (DWORD)((*(PDWORD)pAddr) - (DWORD)base);
								break;

							case IMAGE_REL_BASED_DIR64:
								if (addr + pIBR->VirtualAddress + sizeof(ULONGLONG) >= pISH->VirtualAddress + pISH->SizeOfRawData) {
									len = 0;
									break;
								}
								*(ULONGLONG*)pAddr = (ULONGLONG)((*(ULONGLONG*)pAddr) - base);
								break;

							case IMAGE_REL_BASED_ABSOLUTE:
								// stop processing
								len = 0;
								break;

							case IMAGE_REL_BASED_HIGH:
							case IMAGE_REL_BASED_LOW:
							case IMAGE_REL_BASED_HIGHADJ:
								break;
							}

							len -= sizeof(WORD);
							pw++;
						}
					}

					blocklen -= pIBR->SizeOfBlock;
					if (blocklen <= sizeof(IMAGE_BASE_RELOCATION))
						break;

					pIBR = (PIMAGE_BASE_RELOCATION)((PBYTE)pIBR + pIBR->SizeOfBlock);
				}
			}

			mir_md5_append(&pms, map.ptr + pISH->PointerToRawData, pISH->SizeOfRawData);
		}
	}

	BYTE digest[16];
	mir_md5_finish(&pms, digest);
	bin2hex(digest, sizeof(digest), szDest);
	return RESULT_OK;
}