forked from kaisersoju/Eac-Bypass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemEx.cpp
1679 lines (1406 loc) · 62.6 KB
/
MemEx.cpp
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "MemEx.hpp"
#ifdef UNICODE
#define lstrstr wcsstr
#define lstring wstring
#else
#define lstrstr strstr
#define lstring string
#endif
#define PLACE(type, value) *reinterpret_cast<type*>(buffer) = (type)(value); buffer += sizeof(type)
#define PLACE1(value) *buffer++ = static_cast<uint8_t>(value)
#define PLACE2(value) PLACE(uint16_t, value)
#define PLACE4(value) PLACE(uint32_t, value)
#define PLACE8(value) PLACE(uint64_t, value)
#define PUSH1(value) PLACE1(0x6A); PLACE(uint8_t, value)
#define PUSH4(value) PLACE1(0x68); PLACE(uint32_t, value)
#define CALL_RELATIVE(sourceAddress, functionAddress) PLACE1(0xE8); PLACE(ptrdiff_t, (ptrdiff_t)(functionAddress) - reinterpret_cast<ptrdiff_t>(sourceAddress + 4))
#define CALL_ABSOLUTE(address) PLACE2(0xB848); PLACE8(address); PLACE2(0xD0FF);
#define HOOK_MAX_NUM_REPLACED_BYTES 19
#define X86_MAXIMUM_INSTRUCTION_LENGTH 15
//LDE
#define R (*b >> 4) // Four high-order bits of an opcode to index a row of the opcode table
#define C (*b & 0xF) // Four low-order bits to index a column of the table
static const uint8_t prefixes[] = { 0xF0, 0xF2, 0xF3, 0x2E, 0x36, 0x3E, 0x26, 0x64, 0x65, 0x66, 0x67 };
static const uint8_t op1modrm[] = { 0x62, 0x63, 0x69, 0x6B, 0xC0, 0xC1, 0xC4, 0xC5, 0xC6, 0xC7, 0xD0, 0xD1, 0xD2, 0xD3, 0xF6, 0xF7, 0xFE, 0xFF };
static const uint8_t op1imm8[] = { 0x6A, 0x6B, 0x80, 0x82, 0x83, 0xA8, 0xC0, 0xC1, 0xC6, 0xCD, 0xD4, 0xD5, 0xEB };
static const uint8_t op1imm32[] = { 0x68, 0x69, 0x81, 0xA9, 0xC7, 0xE8, 0xE9 };
static const uint8_t op2modrm[] = { 0x0D, 0xA3, 0xA4, 0xA5, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF };
inline bool findByte(const uint8_t* arr, const size_t N, const uint8_t x) { for (size_t i = 0; i < N; i++) { if (arr[i] == x) { return true; } }; return false; }
inline void parseModRM(uint8_t** b, const bool addressPrefix)
{
uint8_t modrm = *++ * b;
if (!addressPrefix || (addressPrefix && **b >= 0x40))
{
bool hasSIB = false; //Check for SIB byte
if (**b < 0xC0 && (**b & 0b111) == 0b100 && !addressPrefix)
hasSIB = true, (*b)++;
if (modrm >= 0x40 && modrm <= 0x7F) // disp8 (ModR/M)
(*b)++;
else if ((modrm <= 0x3F && (modrm & 0b111) == 0b101) || (modrm >= 0x80 && modrm <= 0xBF)) //disp16,32 (ModR/M)
*b += (addressPrefix) ? 2 : 4;
else if (hasSIB && (**b & 0b111) == 0b101) //disp8,32 (SIB)
*b += (modrm & 0b01000000) ? 1 : 4;
}
else if (addressPrefix && modrm == 0x26)
*b += 2;
};
//MD5
#define ROL(x,s)((x<<s)|x>>(32-s))
static const uint32_t r[] = { 7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21 };
static const uint32_t k[] = { 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,0x6b901122,0xfd987193,0xa679438e,0x49b40821,0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8,0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,0x289b7ec6,0xeaa127fa,0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391 };
ScanBoundaries::ScanBoundaries(const SCAN_BOUNDARIES scanBoundaries, const uintptr_t start, const uintptr_t end)
: scanBoundaries(scanBoundaries),
start(start),
end(end) {}
ScanBoundaries::ScanBoundaries(const SCAN_BOUNDARIES scanBoundaries, const TCHAR* const moduleName)
: scanBoundaries(scanBoundaries),
moduleName(moduleName) {
end = 0;
}
ScanBoundaries::ScanBoundaries(const SCAN_BOUNDARIES scanBoundaries)
: scanBoundaries(scanBoundaries),
start(0), end(0) {}
typedef PVOID(__stdcall* _MapViewOfFileNuma2)(HANDLE FileMappingHandle, HANDLE ProcessHandle, ULONG64 Offset, PVOID BaseAddress, SIZE_T ViewSize, ULONG AllocationType, ULONG PageProtection, ULONG PreferredNode);
typedef BOOL(__stdcall* _UnmapViewOfFile2)(HANDLE Process, LPCVOID BaseAddress, ULONG UnmapFlags);
const DWORD MemEx::dwPageSize = MemEx::GetPageSize();
const DWORD MemEx::dwDesiredAccess = PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_DUP_HANDLE | PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION;
MemEx::MemEx()
: m_hProcess(NULL),
m_dwProcessId(0),
m_hFileMapping(NULL), m_hFileMappingDuplicate(NULL),
m_hThread(NULL),
m_hEvent1(NULL), m_hEvent2(NULL),
m_hEventDuplicate1(NULL), m_hEventDuplicate2(NULL),
m_targetMappedView(NULL), m_thisMappedView(NULL),
m_numPages(0),
m_isWow64(false) {}
MemEx::~MemEx() { Close(); }
bool MemEx::IsOpened() { return m_hProcess; }
bool MemEx::Open(const HANDLE hProcess)
{
DWORD tmp;
m_numPages = 1;
return !m_hProcess &&
GetHandleInformation((m_hProcess = hProcess), &tmp) &&
(m_dwProcessId = GetProcessId(hProcess)) &&
IsWow64Process(m_hProcess, reinterpret_cast<PBOOL>(&m_isWow64));
}
bool MemEx::Open(const DWORD dwProcessId, const DWORD dwDesiredAccess) { return Open(OpenProcess(dwDesiredAccess, FALSE, dwProcessId)); }
bool MemEx::Open(const TCHAR* const processName, const DWORD dwDesiredAccess) { return Open(MemEx::GetProcessIdByName(processName), dwDesiredAccess); }
bool MemEx::OpenByWindow(const TCHAR* const windowName, const TCHAR* const className, const DWORD dwDesiredAccess) { return Open(MemEx::GetProcessIdByWindow(windowName, className), dwDesiredAccess); }
void MemEx::WaitOpen(const TCHAR* const processName, const DWORD dwDesiredAccess, const DWORD dwMilliseconds)
{
while (!Open(processName, dwDesiredAccess))
Sleep(dwMilliseconds);
}
void MemEx::WaitOpenByWindow(const TCHAR* const windowName, const TCHAR* const className, const DWORD dwDesiredAccess, const DWORD dwMilliseconds)
{
while (!OpenByWindow(windowName, className, dwDesiredAccess))
Sleep(dwMilliseconds);
}
void MemEx::Close()
{
if (!m_hProcess)
return;
DeleteRemoteThread();
FreeSharedMemory(m_hFileMapping, m_thisMappedView, m_targetMappedView);
m_hFileMapping = NULL;
CloseHandle(m_hProcess);
m_hProcess = NULL;
m_dwProcessId = static_cast<DWORD>(0);
}
HANDLE MemEx::GetProcess() const { return m_hProcess; }
DWORD MemEx::GetPid() const { return m_dwProcessId; }
bool MemEx::Read(const uintptr_t address, void* const buffer, const SIZE_T size) const { return ReadProcessMemory(m_hProcess, reinterpret_cast<LPCVOID>(address), buffer, size, NULL); }
bool MemEx::Write(uintptr_t address, const void* const buffer, const SIZE_T size) const
{
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQueryEx(m_hProcess, reinterpret_cast<LPCVOID>(address), &mbi, sizeof(MEMORY_BASIC_INFORMATION)))
return false;
DWORD oldProtect = 0;
if (mbi.Protect & (PAGE_READONLY | PAGE_GUARD))
VirtualProtectEx(m_hProcess, reinterpret_cast<LPVOID>(address), size, PAGE_EXECUTE_READWRITE, &oldProtect);
bool ret = static_cast<bool>(WriteProcessMemory(m_hProcess, reinterpret_cast<LPVOID>(address), buffer, size, NULL));
if (oldProtect)
VirtualProtectEx(m_hProcess, reinterpret_cast<LPVOID>(address), size, oldProtect, &oldProtect);
return ret;
}
bool MemEx::Patch(const uintptr_t address, const char* const bytes, const size_t size) const { return Write(address, bytes, size) && static_cast<bool>(FlushInstructionCache(m_hProcess, reinterpret_cast<LPCVOID>(address), static_cast<SIZE_T>(size))); }
bool MemEx::Nop(const uintptr_t address, const size_t size, const bool saveBytes)
{
if (saveBytes)
{
m_Nops[address].buffer = std::make_unique<uint8_t[]>(size);
m_Nops[address].size = size;
if (!Read(address, m_Nops[address].buffer.get(), size))
{
m_Nops.erase(address);
return false;
}
}
return Set(address, 0x90, size) && static_cast<bool>(FlushInstructionCache(m_hProcess, reinterpret_cast<LPCVOID>(address), static_cast<SIZE_T>(size)));
}
bool MemEx::Restore(const uintptr_t address)
{
bool bRet = Patch(address, reinterpret_cast<const char*>(m_Nops[address].buffer.get()), m_Nops[address].size);
m_Nops.erase(address);
return bRet && static_cast<bool>(FlushInstructionCache(m_hProcess, reinterpret_cast<LPCVOID>(address), static_cast<SIZE_T>(m_Nops[address].size)));
}
bool MemEx::Copy(const uintptr_t destinationAddress, const uintptr_t sourceAddress, const size_t size) const
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
return !Read(sourceAddress, buffer.get(), size) || !Write(destinationAddress, buffer.get(), size);
}
bool MemEx::Set(const uintptr_t address, const int value, const size_t size) const
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
memset(buffer.get(), value, size);
return Write(address, buffer.get(), size);
}
bool MemEx::Compare(const uintptr_t address1, const uintptr_t address2, const size_t size) const
{
std::unique_ptr<uint8_t[]> buffer1 = std::make_unique<uint8_t[]>(size), buffer2 = std::make_unique<uint8_t[]>(size);
if (!Read(address1, buffer1.get(), size) || !Read(address2, buffer2.get(), size))
return false;
return memcmp(buffer1.get(), buffer2.get(), size) == 0;
}
//Credits to: https://gist.github.com/creationix/4710780
bool MemEx::HashMD5(const uintptr_t address, const size_t size, uint8_t* const outHash) const
{
size_t N = ((((size + 8) / 64) + 1) * 64) - 8;
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(N + 64);
if (!Read(address, buffer.get(), size))
return false;
buffer[size] = static_cast<uint8_t>(0x80); // 0b10000000
*reinterpret_cast<uint32_t*>(buffer.get() + N) = static_cast<uint32_t>(size * 8);
uint32_t X[4] = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 };
for (uint32_t i = 0, AA = X[0], BB = X[1], CC = X[2], DD = X[3]; i < N; i += 64)
{
for (uint32_t j = 0, f, g; j < 64; j++)
{
if (j < 16) {
f = (BB & CC) | ((~BB) & DD);
g = j;
}
else if (j < 32) {
f = (DD & BB) | ((~DD) & CC);
g = (5 * j + 1) % 16;
}
else if (j < 48) {
f = BB ^ CC ^ DD;
g = (3 * j + 5) % 16;
}
else {
f = CC ^ (BB | (~DD));
g = (7 * j) % 16;
}
uint32_t temp = DD;
DD = CC;
CC = BB;
BB += ROL((AA + f + k[j] + reinterpret_cast<uint32_t*>(buffer.get() + i)[g]), r[j]);
AA = temp;
}
X[0] += AA, X[1] += BB, X[2] += CC, X[3] += DD;
}
for (int i = 0; i < 4; i++)
reinterpret_cast<uint32_t*>(outHash)[i] = X[i];
return true;
}
uintptr_t MemEx::PatternScan(const char* const pattern, const char* const mask, const ScanBoundaries& scanBoundaries, const DWORD protect, const size_t numThreads, const bool firstMatch) const
{
std::atomic<uintptr_t> address = -1;
uintptr_t start = 0, end = 0;
switch (scanBoundaries.scanBoundaries)
{
case SCAN_BOUNDARIES::RANGE:
start = scanBoundaries.start, end = scanBoundaries.end;
break;
case SCAN_BOUNDARIES::MODULE:
DWORD moduleSize;
if (!(start = GetModuleBase(scanBoundaries.moduleName, &moduleSize)))
return 0;
end = start + moduleSize;
break;
case SCAN_BOUNDARIES::ALL_MODULES:
{
struct PatternInfo
{
const char* const pattern, * const mask;
const MemEx* mem;
DWORD protect;
size_t numThreads;
bool firstMatch;
uintptr_t address;
};
PatternInfo pi = { pattern, mask, this, protect, numThreads, firstMatch, 0 };
EnumModules(m_dwProcessId,
[](MODULEENTRY32& me, void* param)
{
PatternInfo* pi = static_cast<PatternInfo*>(param);
return !(pi->address = pi->mem->PatternScan(pi->pattern, pi->mask, ScanBoundaries(SCAN_BOUNDARIES::RANGE, reinterpret_cast<uintptr_t>(me.modBaseAddr), reinterpret_cast<uintptr_t>(me.modBaseAddr + me.modBaseSize)), pi->protect, pi->numThreads, pi->firstMatch));
}, &pi);
return pi.address;
}
default:
return 0;
}
size_t chunkSize = (end - start) / numThreads;
std::vector<std::thread> threads;
for (size_t i = 0; i < numThreads; i++)
threads.emplace_back(std::thread(&MemEx::PatternScanImpl, this, std::ref(address), reinterpret_cast<const uint8_t* const>(pattern), mask, start + chunkSize * i, start + chunkSize * (i + 1), protect, firstMatch));
for (auto& thread : threads)
thread.join();
return (address.load() != -1) ? address.load() : 0;
}
uintptr_t MemEx::AOBScan(const char* const AOB, const ScanBoundaries& scanBoundaries, const DWORD protect, size_t* const patternSize, const size_t numThreads, const bool firstMatch) const
{
std::string pattern, mask;
AOBToPattern(AOB, pattern, mask);
if (patternSize)
*patternSize = pattern.size();
return PatternScan(pattern.c_str(), mask.c_str(), scanBoundaries, protect, numThreads, firstMatch);
}
//Based on https://guidedhacking.com/threads/finddmaaddy-c-multilevel-pointer-function.6292/
uintptr_t MemEx::ReadMultiLevelPointer(uintptr_t base, const std::vector<uint32_t>& offsets) const
{
for (auto& offset : offsets)
{
if (!Read(base, &base, sizeof(uintptr_t)))
return 0;
base += offset;
}
return base;
}
bool MemEx::Hook(const uintptr_t address, const void* const callback, uintptr_t* const trampoline, const DWORD saveCpuStateMask)
{
size_t size = 0;
constexpr uint8_t hookMark[12] = { 0xD6, 0xD6, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0xD6, 0xD6 };
const uint8_t* tmp = static_cast<const uint8_t*>(callback);
while (memcmp(tmp, hookMark, sizeof(hookMark)) != 0)
tmp++;
return HookBuffer(address, callback, static_cast<const size_t>(reinterpret_cast<ptrdiff_t>(tmp) - reinterpret_cast<ptrdiff_t>(callback)), trampoline, saveCpuStateMask);
}
bool MemEx::HookBuffer(const uintptr_t address, const void* const callback, const size_t callbackSize, uintptr_t* const trampoline, const DWORD saveCpuStateMask)
{
uint8_t originalCode[HOOK_MAX_NUM_REPLACED_BYTES];
if (!m_hProcess || !Read(address, originalCode, sizeof(originalCode)))
return false;
size_t numReplacedBytes = 0;
while (numReplacedBytes < 5)
numReplacedBytes += GetInstructionLength(address + numReplacedBytes);
#ifdef _WIN64
const bool callbackNearHook = (reinterpret_cast<ptrdiff_t>(callback) - static_cast<ptrdiff_t>(address + 5)) < 0x80000000;
const size_t saveCpuStateBufferSize = static_cast<size_t>(saveCpuStateMask || (!saveCpuStateMask && !callbackNearHook) ? 14 : 0) + (saveCpuStateMask ? 8 : 0) + (saveCpuStateMask & FLAGS ? 2 : 0) + (saveCpuStateMask & GPR ? 22 : 0) + (saveCpuStateMask & XMMX ? 78 : 0);
#else
const size_t saveCpuStateBufferSize = (saveCpuStateMask ? 5 : 0) + (saveCpuStateMask & FLAGS ? 2 : 0) + (saveCpuStateMask & GPR ? 2 : 0) + (saveCpuStateMask & XMMX ? 76 : 0);
#endif
const size_t trampolineSize = numReplacedBytes + 5;
const size_t bufferSize = saveCpuStateBufferSize + trampolineSize;
HookStruct hook; uintptr_t bufferAddress = NULL; uint8_t codeCaveNullByte = 0;
if (!(bufferAddress = FindCodeCaveBatch(bufferSize, { 0x00, 0xCC }, &codeCaveNullByte, ScanBoundaries(SCAN_BOUNDARIES::RANGE, address > 0x7ffff000 ? address - 0x7ffff000 : 0, address + 0x7ffff000))))
{
hook.useCodeCaveAsMemory = false;
for (auto page : m_Pages)
{
if (0x1000 - page.second > bufferSize)
{
bufferAddress = page.second;
page.second += bufferSize;
break;
}
}
if (!bufferAddress)
{
MEMORY_BASIC_INFORMATION mbi;
uintptr_t newBufferAddress = address > 0x7ffff000 ? address - 0x7ffff000 : 0;
if (!VirtualQueryEx(m_hProcess, reinterpret_cast<LPVOID>(newBufferAddress), &mbi, sizeof(MEMORY_BASIC_INFORMATION)))
return false;
if (reinterpret_cast<uintptr_t>(mbi.BaseAddress) < (address > 0x7ffff000 ? address - 0x7ffff000 : 0))
newBufferAddress = reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize;
do
{
if (mbi.State == MEM_FREE)
{
do
{
if ((bufferAddress = reinterpret_cast<uintptr_t>(VirtualAllocEx(m_hProcess, reinterpret_cast<LPVOID>(newBufferAddress), 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE))))
break;
else
newBufferAddress += 0x1000;
} while (newBufferAddress < reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize);
}
else
newBufferAddress = reinterpret_cast<uintptr_t>(mbi.BaseAddress) + mbi.RegionSize;
} while (VirtualQueryEx(m_hProcess, reinterpret_cast<LPVOID>(newBufferAddress), &mbi, sizeof(MEMORY_BASIC_INFORMATION)) && newBufferAddress < address + 0x7ffff000 && !bufferAddress);
if (bufferAddress)
m_Pages[bufferAddress] = bufferSize;
}
}
if (!bufferAddress)
return false;
std::unique_ptr<uint8_t[]> bufferPtr = std::make_unique<uint8_t[]>(bufferSize);
uint8_t* buffer = bufferPtr.get();
if (saveCpuStateMask)
{
#ifdef _WIN64
PLACE8(callback);
#endif
if (saveCpuStateMask & GPR)
{
#ifdef _WIN64
// push rax, rcx, rdx, r8, r9, r10, r11
PLACE8(0x4151415041525150); PLACE1(0x52); PLACE2(0x5341);
#else
PLACE1(0x60); // pushad
#endif
}
if (saveCpuStateMask & XMMX)
{
#ifdef _WIN64
PLACE4(0x60EC8348); // sub rsp, 0x60
#else
PLACE1(0x83); PLACE2(0x60EC); // sub esp, 0x60
#endif
PLACE1(0xF3); PLACE4(0x246C7F0F); PLACE1(0x50); // movdqu xmmword ptr ss:[r/esp+0x50], xmm5
PLACE1(0xF3); PLACE4(0x24647F0F); PLACE1(0x40); // movdqu xmmword ptr ss:[r/esp+0x40], xmm4
PLACE1(0xF3); PLACE4(0x245C7F0F); PLACE1(0x30); // movdqu xmmword ptr ss:[r/esp+0x30], xmm3
PLACE1(0xF3); PLACE4(0x24547F0F); PLACE1(0x20); // movdqu xmmword ptr ss:[r/esp+0x20], xmm2
PLACE1(0xF3); PLACE4(0x244C7F0F); PLACE1(0x10); // movdqu xmmword ptr ss:[r/esp+0x10], xmm1
PLACE1(0xF3); PLACE4(0x24047F0F); // movdqu xmmword ptr ss:[r/esp], xmm0
}
if (saveCpuStateMask & FLAGS)
{
PLACE1(0x9C);
} // pushfd/q
#ifdef _WIN64
PLACE4(0x28EC8348); // sub rsp, 0x28
PLACE2(0x15FF); PLACE4((saveCpuStateMask & GPR ? -11 : 0) + (saveCpuStateMask & XMMX ? -39 : 0) + (saveCpuStateMask & FLAGS ? -1 : 0) - 18);
PLACE4(0x28C48348); // add rsp, 0x28
#else
PLACE1(0xE8); PLACE4(reinterpret_cast<ptrdiff_t>(callback) - reinterpret_cast<ptrdiff_t>(buffer + 4));
#endif
if (saveCpuStateMask & FLAGS)
{
PLACE1(0x9D);
} // popfd/q
if (saveCpuStateMask & XMMX)
{
PLACE1(0xF3); PLACE4(0x24046F0F); // movdqu xmm0, xmmword ptr ss:[r/esp]
PLACE1(0xF3); PLACE4(0x244C6F0F); PLACE1(0x10); // movdqu xmm1, xmmword ptr ss:[r/esp+0x10]
PLACE1(0xF3); PLACE4(0x24546F0F); PLACE1(0x20); // movdqu xmm2, xmmword ptr ss:[r/esp+0x20]
PLACE1(0xF3); PLACE4(0x245C6F0F); PLACE1(0x30); // movdqu xmm3, xmmword ptr ss:[r/esp+0x30]
PLACE1(0xF3); PLACE4(0x24646F0F); PLACE1(0x40); // movdqu xmm4, xmmword ptr ss:[r/esp+0x40]
PLACE1(0xF3); PLACE4(0x246C6F0F); PLACE1(0x50); // movdqu xmm5, xmmword ptr ss:[r/esp+0x50]
#ifdef _WIN64
PLACE4(0x60C48348); // add rsp, 0x60
#else
PLACE1(0x83); PLACE2(0x60C4); // add esp, 0x60
#endif
}
if (saveCpuStateMask & GPR)
{
#ifdef _WIN64
// pop r11, r10, r9, r8, rdx, rcx, rax
PLACE8(0x584159415A415B41); PLACE1(0x5A); PLACE2(0x5859);
#else
PLACE1(0x61); // popad
#endif
}
}
#ifdef _WIN64
else if (!callbackNearHook)
{
PLACE2(0x25FF); PLACE4(0); PLACE8(callback);
}
#endif
//Copy original instructions
memcpy(reinterpret_cast<void*>(buffer), reinterpret_cast<const void*>(address), numReplacedBytes);
if (*buffer == 0xE9)
*reinterpret_cast<uint32_t*>(buffer + 1) = static_cast<uint32_t>(static_cast<ptrdiff_t>(*reinterpret_cast<uint32_t*>(buffer + 1) + address + 5) - static_cast<ptrdiff_t>(bufferAddress + (bufferPtr.get() - buffer) + 5));
buffer += numReplacedBytes;
//Jump back to original function
PLACE1(0xE9); PLACE4(static_cast<ptrdiff_t>(address + numReplacedBytes) - reinterpret_cast<ptrdiff_t>(buffer + 4));
if (!Write(bufferAddress, bufferPtr.get(), bufferSize))
return false;
//Jump from hooked function to callback(x32 && !saveCpuStateMask) / buffer(x64)
uint8_t jump[5]; buffer = jump;
#ifdef _WIN64
PLACE1(0xE9); PLACE4(((!saveCpuStateMask && callbackNearHook) ? reinterpret_cast<ptrdiff_t>(callback) : static_cast<ptrdiff_t>(bufferAddress + 8)) - reinterpret_cast<ptrdiff_t>(buffer + 4));
#else
PLACE1(0xE9); PLACE4((saveCpuStateMask ? static_cast<ptrdiff_t>(bufferAddress) : reinterpret_cast<ptrdiff_t>(callback)) - reinterpret_cast<ptrdiff_t>(buffer + 4));
#endif
if (!Write(address, jump, 5))
return false;
hook.buffer = bufferAddress;
hook.bufferSize = static_cast<uint8_t>(bufferSize);
hook.codeCaveNullByte = codeCaveNullByte;
hook.numReplacedBytes = static_cast<uint8_t>(numReplacedBytes);
m_Hooks[bufferAddress] = hook;
return static_cast<bool>(FlushInstructionCache(m_hProcess, reinterpret_cast<LPCVOID>(address), numReplacedBytes));
}
bool MemEx::Unhook(const uintptr_t address)
{
//Restore original instruction(s)
std::unique_ptr<uint8_t[]> replacedBytes = std::make_unique<uint8_t[]>(m_Hooks[address].numReplacedBytes);
if (!Read(m_Hooks[address].buffer + m_Hooks[address].bufferSize - 5 - m_Hooks[address].numReplacedBytes, replacedBytes.get(), m_Hooks[address].numReplacedBytes))
return false;
if (*(replacedBytes.get() + 1) == 0xE9)
*reinterpret_cast<uint32_t*>(replacedBytes.get() + 1) = static_cast<uint32_t>(static_cast<ptrdiff_t>(*reinterpret_cast<uint32_t*>(replacedBytes.get() + 1) + (m_Hooks[address].buffer + m_Hooks[address].bufferSize)) - static_cast<ptrdiff_t>(address + 5));
if (!Write(address, replacedBytes.get(), m_Hooks[address].numReplacedBytes))
return false;
//Free memory used to store the buffer
if (m_Hooks[address].useCodeCaveAsMemory && !Set(m_Hooks[address].buffer, m_Hooks[address].codeCaveNullByte, m_Hooks[address].bufferSize))
return false;
else
{
for (auto page : m_Pages)
{
if (page.first == m_Hooks[address].buffer && !(page.second -= m_Hooks[address].bufferSize))
{
VirtualFreeEx(m_hProcess, reinterpret_cast<LPVOID>(page.first), 0x1000, MEM_FREE);
m_Pages.erase(m_Hooks[address].buffer);
}
}
}
m_Hooks.erase(address);
return static_cast<bool>(FlushInstructionCache(m_hProcess, reinterpret_cast<LPCVOID>(address), static_cast<SIZE_T>(m_Hooks[address].numReplacedBytes)));
}
uintptr_t MemEx::FindCodeCave(const size_t size, const uint32_t nullByte, const ScanBoundaries& scanBoundaries, size_t* const codeCaveSize, const DWORD protection, const size_t numThreads, const bool firstMatch) const
{
uintptr_t address = NULL;
if (nullByte != -1)
{
auto pattern = std::make_unique<char[]>(size), mask = std::make_unique<char[]>(size + 1);
memset(pattern.get(), static_cast<int>(nullByte), size);
memset(mask.get(), static_cast<int>('x'), size);
mask.get()[size] = '\0';
address = PatternScan(pattern.get(), mask.get(), scanBoundaries, protection, numThreads, firstMatch);
}
else
{
std::atomic<uintptr_t> atomicAddress = -1;
uintptr_t start = 0, end = 0;
switch (scanBoundaries.scanBoundaries)
{
case SCAN_BOUNDARIES::RANGE:
start = scanBoundaries.start, end = scanBoundaries.end;
break;
case SCAN_BOUNDARIES::MODULE:
DWORD moduleSize;
if (!(start = GetModuleBase(scanBoundaries.moduleName, &moduleSize)))
return 0;
end = start + moduleSize;
break;
case SCAN_BOUNDARIES::ALL_MODULES:
{
struct CodeCaveInfo
{
size_t size;
size_t* const codeCaveSize;
const MemEx* memex;
DWORD protect;
size_t numThreads;
bool firstMatch;
uintptr_t address;
};
CodeCaveInfo cci = { size, codeCaveSize, this, protection, numThreads, firstMatch, 0 };
EnumModules(GetCurrentProcessId(),
[](MODULEENTRY32& me, void* param)
{
CodeCaveInfo* cci = static_cast<CodeCaveInfo*>(param);
return !(cci->address = cci->memex->FindCodeCave(cci->size, -1, ScanBoundaries(SCAN_BOUNDARIES::RANGE, reinterpret_cast<uintptr_t>(me.modBaseAddr), reinterpret_cast<uintptr_t>(me.modBaseAddr + me.modBaseSize)), cci->codeCaveSize, cci->protect, cci->numThreads, cci->firstMatch));
}, &cci);
return cci.address;
}
default:
return 0;
}
size_t chunkSize = (end - start) / numThreads;
std::vector<std::thread> threads;
for (size_t i = 0; i < numThreads; i++)
threads.emplace_back(std::thread(&MemEx::FindCodeCaveImpl, this, std::ref(atomicAddress), size, start + chunkSize * i, start + chunkSize * (static_cast<size_t>(i) + 1), protection, firstMatch));
for (auto& thread : threads)
thread.join();
address = (atomicAddress.load() != -1) ? atomicAddress.load() : 0;
}
if (address && codeCaveSize)
{
size_t remainingSize = 0; SIZE_T nBytesRead;
uint8_t buffer[4096];
uint8_t realNullByte = nullByte == -1 ? *reinterpret_cast<uint8_t*>(address) : nullByte;
while (ReadProcessMemory(m_hProcess, reinterpret_cast<LPCVOID>(address + size + remainingSize), buffer, 4096, &nBytesRead))
{
for (SIZE_T i = 0; i < nBytesRead; i++)
{
if (buffer[i] == realNullByte)
remainingSize++;
else
{
*codeCaveSize = size + remainingSize;
return address;
}
}
}
*codeCaveSize = size + remainingSize;
}
return address;
}
uintptr_t MemEx::FindCodeCaveBatch(const size_t size, const std::vector<uint8_t>& nullBytes, uint8_t* const pNullByte, const ScanBoundaries& scanBoundaries, size_t* const codeCaveSize, const DWORD protection, const size_t numThreads, const bool firstMatch) const
{
for (auto nullByte : nullBytes)
{
auto address = FindCodeCave(size, nullByte, scanBoundaries, codeCaveSize, protection, numThreads, firstMatch);
if (address)
{
if (pNullByte)
*pNullByte = nullByte;
return address;
}
}
return 0;
}
PVOID MemEx::MapLocalViewOfFile(const HANDLE hFileMapping) { return MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS | FILE_MAP_WRITE, 0, 0, 0); }
bool MemEx::UnmapLocalViewOfFile(LPCVOID localAddress) { return static_cast<bool>(UnmapViewOfFile(localAddress)); }
PVOID MemEx::MapRemoteViewOfFile(const HANDLE hFileMapping) const
{
auto lib = LoadLibrary(TEXT("Api-ms-win-core-memory-l1-1-5.dll"));
_MapViewOfFileNuma2 mapViewOfFileNuma2;
if (lib && (mapViewOfFileNuma2 = reinterpret_cast<_MapViewOfFileNuma2>(GetProcAddress(lib, "MapViewOfFileNuma2"))))
{
FreeLibrary(lib);
return mapViewOfFileNuma2(hFileMapping, m_hProcess, 0, nullptr, 0, 0, PAGE_EXECUTE_READWRITE, -1);
}
else
{
LPVOID address = VirtualAllocEx(m_hProcess, NULL, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!address)
return (PVOID)false;
//Construct shellcode and copy it to the target process
uint8_t shellcode[96]; uint8_t* buffer = shellcode;
//Duplicate the handle to the file mapping object
HANDLE hFileMappingDuplicate, hProcessDuplicate;
if (!DuplicateHandle(GetCurrentProcess(), hFileMapping, m_hProcess, &hFileMappingDuplicate, NULL, FALSE, DUPLICATE_SAME_ACCESS) || !DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), m_hProcess, &hProcessDuplicate, NULL, FALSE, DUPLICATE_SAME_ACCESS))
{
VirtualFreeEx(m_hProcess, address, 0, MEM_RELEASE);
return (PVOID)false;
}
PVOID targetAddress = nullptr;
#ifdef _WIN64
PLACE1(0xB9); PLACE4(reinterpret_cast<uintptr_t>(m_hFileMappingDuplicate)); // mov ecx, m_hFileMappingDuplicate
PLACE1(0xBA); PLACE4(FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE); //mov edx, FILE_MAP_ALL_ACCESS
PLACE4(0x45C03345); PLACE2(0xC933); // (xor r8d, r8d) & (xor r9d, r9d)
PUSH1(0);
CALL_ABSOLUTE(MapViewOfFile);
PLACE1(0x50);
PLACE1(0xB9); PLACE4(reinterpret_cast<uintptr_t>(hProcessDuplicate));
PLACE1(0xBA); PLACE8(&m_targetMappedView);
PLACE1(0x4C); PLACE2(0xC48B); // mov r8, rax
PLACE2(0xB941); PLACE4(sizeof(uintptr_t)); // mov r9d, sizeof(HANDLE)
PUSH1(0);
CALL_ABSOLUTE(WriteProcessMemory);
PLACE2(0xC358); // pop esp & ret
#else
PUSH1(0);
PUSH1(0);
PUSH1(0);
PUSH4(FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE);
PUSH4(hFileMappingDuplicate);
CALL_RELATIVE(reinterpret_cast<uint8_t*>(address) + (buffer - shellcode), MapViewOfFile);
PLACE1(0x50); //push eax
PUSH1(0);
PUSH1(sizeof(uintptr_t));
PLACE4(0x0824448D); // lea eax, dword ptr ss:[esp + 8]
PLACE1(0x50); // push eax
PUSH4(&targetAddress);
PUSH4(hProcessDuplicate);
CALL_RELATIVE(reinterpret_cast<uint8_t*>(address) + (buffer - shellcode), WriteProcessMemory);
PLACE2(0xC358); // pop esp & ret
#endif
WriteProcessMemory(m_hProcess, address, shellcode, sizeof(shellcode), NULL);
CreateRemoteThread(m_hProcess, NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(address), NULL, NULL, NULL);
Sleep(2);
DuplicateHandle(m_hProcess, hProcessDuplicate, NULL, NULL, NULL, FALSE, DUPLICATE_CLOSE_SOURCE);
VirtualFreeEx(m_hProcess, address, 0, MEM_RELEASE);
return targetAddress;
}
}
bool MemEx::UnmapRemoteViewOfFile(LPCVOID remoteAddress) const
{
auto lib = LoadLibrary(TEXT("kernelbase.dll"));
_UnmapViewOfFile2 unmapViewOfFile2;
if (lib && (unmapViewOfFile2 = reinterpret_cast<_UnmapViewOfFile2>(GetProcAddress(lib, "UnmapViewOfFile2"))))
{
FreeLibrary(lib);
return static_cast<bool>(unmapViewOfFile2(m_hProcess, remoteAddress, 0));
}
else
CreateRemoteThread(m_hProcess, NULL, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(UnmapViewOfFile), const_cast<LPVOID>(remoteAddress), NULL, NULL);
return true;
}
DWORD MemEx::GetProcessIdByName(const TCHAR* processName)
{
const HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
return 0;
std::lstring processNameLowercase(processName);
std::transform(processNameLowercase.begin(), processNameLowercase.end(), processNameLowercase.begin(), [](TCHAR c) { return c >= 'A' && c < 'Z' ? c + 0x20 : c; });
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnapshot, &pe32))
{
do
{
bool match = true;
for (int i = 0; pe32.szExeFile[i]; i++)
{
TCHAR c = pe32.szExeFile[i];
if ((c >= 'A' && c <= 'Z' ? c + 0x20 : c) != processNameLowercase[i])
{
match = false;
break;
}
}
if (match)
{
CloseHandle(hSnapshot);
return pe32.th32ProcessID;
}
} while (Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
return 0;
}
DWORD MemEx::GetProcessIdByWindow(const TCHAR* windowName, const TCHAR* className)
{
DWORD dwProcessId;
GetWindowThreadProcessId(FindWindow(className, windowName), &dwProcessId);
return dwProcessId;
}
uintptr_t MemEx::GetModuleBase(const TCHAR* const moduleName, DWORD* const pModuleSize) const { return MemEx::GetModuleBase(m_dwProcessId, moduleName, pModuleSize); }
uintptr_t MemEx::GetModuleBase(const DWORD dwProcessId, const TCHAR* const moduleName, DWORD* const pModuleSize)
{
struct ModuleInfo { std::lstring* name; uintptr_t base; DWORD* const size; };
std::lstring moduleNameLowerCase;
ModuleInfo mi = { nullptr, NULL, pModuleSize };
if (moduleName)
{
moduleNameLowerCase = moduleName;
std::transform(moduleNameLowerCase.begin(), moduleNameLowerCase.end(), moduleNameLowerCase.begin(), [](TCHAR c) { return c >= 'A' && c < 'Z' ? c + 0x20 : c; });
mi.name = &moduleNameLowerCase;
}
EnumModules(dwProcessId,
[](MODULEENTRY32& me, void* param)
{
ModuleInfo* mi = static_cast<ModuleInfo*>(param);
bool match = true;
if (mi->name)
{
for (int i = 0; me.szModule[i]; i++)
{
TCHAR c = me.szModule[i];
if ((c >= 'A' && c <= 'Z' ? c + 0x20 : c) != mi->name->at(i))
{
match = false;
break;
}
}
}
else
match = lstrstr(me.szModule, TEXT(".exe")) != nullptr;
if (match)
{
mi->base = reinterpret_cast<uintptr_t>(me.modBaseAddr);
if (mi->size)
*mi->size = me.modBaseSize;
return false;
}
return true;
}, &mi);
return mi.base;
}
//https://github.com/Nomade040/length-disassembler
size_t MemEx::GetInstructionLength(const uintptr_t address)
{
uint8_t buffer[X86_MAXIMUM_INSTRUCTION_LENGTH];
if (!Read(address, buffer, X86_MAXIMUM_INSTRUCTION_LENGTH))
return 0;
size_t offset = 0;
bool operandPrefix = false, addressPrefix = false, rexW = false;
uint8_t* b = (uint8_t*)(buffer);
//Parse legacy prefixes & REX prefixes
#if UINTPTR_MAX == UINT64_MAX
for (int i = 0; i < 14 && findByte(prefixes, sizeof(prefixes), *b) || (R == 4); i++, b++)
#else
for (int i = 0; i < 14 && findByte(prefixes, sizeof(prefixes), *b); i++, b++)
#endif
{
if (*b == 0x66)
operandPrefix = true;
else if (*b == 0x67)
addressPrefix = true;
else if (R == 4 && C >= 8)
rexW = true;
}
//Parse opcode(s)
if (*b == 0x0F) // 2,3 bytes
{
b++;
if (*b == 0x38 || *b == 0x3A) // 3 bytes
{
if (*b++ == 0x3A)
offset++;
parseModRM(&b, addressPrefix);
}
else // 2 bytes
{
if (R == 8) //disp32
offset += 4;
else if ((R == 7 && C < 4) || *b == 0xA4 || *b == 0xC2 || (*b > 0xC3 && *b <= 0xC6) || *b == 0xBA || *b == 0xAC) //imm8
offset++;
//Check for ModR/M, SIB and displacement
if (findByte(op2modrm, sizeof(op2modrm), *b) || (R != 3 && R > 0 && R < 7) || *b >= 0xD0 || (R == 7 && C != 7) || R == 9 || R == 0xB || (R == 0xC && C < 8) || (R == 0 && C < 4))
parseModRM(&b, addressPrefix);
}
}
else // 1 byte
{
//Check for immediate field
if ((R == 0xE && C < 8) || (R == 0xB && C < 8) || R == 7 || (R < 4 && (C == 4 || C == 0xC)) || (*b == 0xF6 && !(*(b + 1) & 48)) || findByte(op1imm8, sizeof(op1imm8), *b)) //imm8
offset++;
else if (*b == 0xC2 || *b == 0xCA) //imm16
offset += 2;
else if (*b == 0xC8) //imm16 + imm8
offset += 3;
else if ((R < 4 && (C == 5 || C == 0xD)) || (R == 0xB && C >= 8) || (*b == 0xF7 && !(*(b + 1) & 48)) || findByte(op1imm32, sizeof(op1imm32), *b)) //imm32,16
offset += (rexW) ? 8 : (operandPrefix ? 2 : 4);
else if (R == 0xA && C < 4)
offset += (rexW) ? 8 : (addressPrefix ? 2 : 4);
else if (*b == 0xEA || *b == 0x9A) //imm32,48
offset += operandPrefix ? 4 : 6;
//Check for ModR/M, SIB and displacement
if (findByte(op1modrm, sizeof(op1modrm), *b) || (R < 4 && (C < 4 || (C >= 8 && C < 0xC))) || R == 8 || (R == 0xD && C >= 8))
parseModRM(&b, addressPrefix);
}
return (size_t)((ptrdiff_t)(++b + offset) - (ptrdiff_t)(address));
}
void MemEx::EnumModules(const DWORD processId, bool (*callback)(MODULEENTRY32& me, void* param), void* param)
{
const HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, processId);
if (hSnapshot == INVALID_HANDLE_VALUE)
return;
MODULEENTRY32 me = { sizeof(MODULEENTRY32) };
if (Module32First(hSnapshot, &me))
{
do
{
if (!callback(me, param))
break;
} while (Module32Next(hSnapshot, &me));
}
CloseHandle(hSnapshot);
}
//Credits to: https://guidedhacking.com/threads/universal-pattern-signature-parser.9588/ & https://guidedhacking.com/threads/python-script-to-convert-ces-aob-signature-to-c-s-signature-mask.14095/
void MemEx::AOBToPattern(const char* const AOB, std::string& pattern, std::string& mask)
{
if (!AOB)
return;
auto ishex = [](const char c) -> bool { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'); };
auto hexchartoint = [](const char c) -> uint8_t { return (c >= 'A') ? (c - 'A' + 10) : (c - '0'); };
const char* bytes = AOB;
for (; *bytes != '\0'; bytes++)
{
if (ishex(*bytes))
pattern += static_cast<char>((ishex(*(bytes + 1))) ? hexchartoint(*bytes) | (hexchartoint(*(bytes++)) << 4) : hexchartoint(*bytes)), mask += 'x';
else if (*bytes == '?')
pattern += '\x00', mask += '?', (*(bytes + 1) == '?') ? (bytes++) : (bytes);
}
}
void MemEx::PatternToAOB(const char* const pattern, const char* const mask, std::string& AOB)
{
for (size_t i = 0; mask[i]; i++)
{
if (mask[i] == '?')
AOB += "??";
else
AOB += static_cast<char>((pattern[i] & 0xF0) >> 4) + static_cast<char>(pattern[i] & 0x0F);
AOB += ' ';
}
}