-
Notifications
You must be signed in to change notification settings - Fork 87
/
Dumper.pas
541 lines (462 loc) · 16.7 KB
/
Dumper.pas
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
unit Dumper;
interface
uses Windows, SysUtils, Classes, Generics.Collections, TlHelp32, PEInfo, Utils;
const
MAX_IAT_SIZE = $2000; // max 2048 imports
type
TExportTable = TDictionary<Pointer, string>;
TRemoteModule = record
Base, EndOff: PByte;
Name: string;
ExportTbl: TExportTable;
end;
PRemoteModule = ^TRemoteModule;
TForwardDict = TDictionary<Pointer, Pointer>;
TImportThunk = class
public
Module: PRemoteModule;
Name: string;
Addresses: TList<PPointer>;
constructor Create(RM: PRemoteModule);
destructor Destroy; override;
end;
TDumper = class
private
FProcess: TProcessInformation;
FOEP, FIAT, FImageBase: NativeUInt;
FForwards: TForwardDict; // Key: NTDLL, Value: kernel32 (points to API)
FForwardsType2: TForwardDict; // Key: NTDLL, Value: user32 (points to fwd-string)
FForwardsOle32: TForwardDict; // Key: combase, Value: ole32
FForwardsNetapi32: TForwardDict; // Key: netutils, Value: netapi32
FForwardsCrypt32: TForwardDict; // Key: DPAPI, Value: crypt32
FForwardsDbghelp: TForwardDict; // Key: dbgcore, Value: dbghelp
FForwardsKernelbase: TForwardDict; // Key: NTDLL, Value: kernelbase (Win8 sync APIs like WakeByAddressAll)
FAllModules: TList<PRemoteModule>;
FIATImage: PByte;
FIATImageSize: Cardinal;
FUsrPath: PChar;
FHUsr: HMODULE;
procedure CollectNTFwd; overload;
procedure CollectForwards(Fwds: TForwardDict; hModReal, hModScan: HMODULE); overload;
procedure GatherModuleExportsFromRemoteProcess(M: PRemoteModule);
procedure TakeModuleSnapshot;
function GetLocalProcAddr(hModule: HMODULE; ProcName: PAnsiChar): Pointer;
function RPM(Address: NativeUInt; Buf: Pointer; BufSize: NativeUInt): Boolean;
public
constructor Create(const AProcess: TProcessInformation; AImageBase, AOEP: UIntPtr);
destructor Destroy; override;
function Process: TPEHeader;
procedure DumpToFile(const FileName: string; PE: TPEHeader);
function IsAPIAddress(Address: NativeUInt): Boolean;
property IAT: NativeUInt read FIAT write FIAT; // Virtual address of IAT in target
end;
implementation
uses Debugger;
{ TDumper }
constructor TDumper.Create(const AProcess: TProcessInformation; AImageBase, AOEP: UIntPtr);
begin
FProcess := AProcess;
FOEP := AOEP;
FImageBase := AImageBase;
if Win32MajorVersion > 5 then
begin
FUsrPath := PChar(ExtractFilePath(ParamStr(0)) + 'mmusr32.dll');
CopyFile('C:\Windows\system32\user32.dll', FUsrPath, False);
FHUsr := LoadLibraryEx(FUsrPath, 0, $20) - 2;
end;
FForwards := TForwardDict.Create(32);
FForwardsType2 := TForwardDict.Create(16);
FForwardsOle32 := TForwardDict.Create(32);
FForwardsNetapi32 := TForwardDict.Create(32);
FForwardsCrypt32 := TForwardDict.Create(16);
FForwardsDbghelp := TForwardDict.Create(16);
FForwardsKernelbase := TForwardDict.Create(16);
CollectNTFwd;
end;
destructor TDumper.Destroy;
var
RM: PRemoteModule;
begin
FForwards.Free;
FForwardsType2.Free;
FForwardsOle32.Free;
FForwardsNetapi32.Free;
FForwardsCrypt32.Free;
FForwardsDbghelp.Free;
FForwardsKernelbase.Free;
if FAllModules <> nil then
begin
for RM in FAllModules do
begin
RM.ExportTbl.Free;
Dispose(RM);
end;
FAllModules.Free;
end;
if FIATImage <> nil then
FreeMem(FIATImage);
if FHUsr <> 0 then
begin
FreeLibrary(FHUsr + 2);
Windows.DeleteFile(FUsrPath);
end;
inherited;
end;
procedure TDumper.CollectNTFwd;
var
hNetapi, hSrvcli, hCrypt32, hDpapi, hDbghelp, hDbgcore: HMODULE;
begin
CollectForwards(FForwards, GetModuleHandle(kernel32), 0);
if FHUsr <> 0 then
CollectForwards(FForwardsType2, GetModuleHandle(user32), FHUsr);
CollectForwards(FForwardsOle32, GetModuleHandle('ole32.dll'), 0);
hNetapi := LoadLibrary('netapi32.dll');
hSrvcli := LoadLibrary('srvcli.dll'); // Required for CollectForwards
CollectForwards(FForwardsNetapi32, hNetapi, 0);
FreeLibrary(hSrvcli);
FreeLibrary(hNetapi);
if Win32MajorVersion >= 6 then
begin
hCrypt32 := LoadLibrary('crypt32.dll');
hDpapi := LoadLibrary('dpapi.dll'); // Required for CollectForwards
CollectForwards(FForwardsCrypt32, hCrypt32, 0);
FreeLibrary(hCrypt32);
FreeLibrary(hDpapi);
end;
hDbghelp := LoadLibrary('dbghelp.dll');
hDbgcore := LoadLibrary('dbgcore.dll'); // Required for CollectForwards
CollectForwards(FForwardsDbghelp, hDbghelp, 0);
FreeLibrary(hDbghelp);
FreeLibrary(hDbgcore);
if GetModuleHandle('kernelbase.dll') <> 0 then
CollectForwards(FForwardsKernelbase, GetModuleHandle('kernelbase.dll'), 0);
end;
procedure TDumper.CollectForwards(Fwds: TForwardDict; hModReal, hModScan: HMODULE);
var
ModScan: PByte;
ExpDir: PImageExportDirectory;
i, DotPos: Integer;
a: PCardinal;
Fwd: PAnsiChar;
hMod: HMODULE;
ProcAddr: Pointer;
begin
if hModScan = 0 then
hModScan := hModReal;
ModScan := Pointer(hModScan);
ExpDir := Pointer(ModScan + PImageNTHeaders(ModScan + PImageDosHeader(ModScan)._lfanew).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
a := PCardinal(ModScan + ExpDir.AddressOfFunctions);
for i := 0 to ExpDir.NumberOfFunctions - 1 do
begin
Fwd := PAnsiChar(ModScan + a^); // e.g. NTDLL.RtlAllocateHeap
DotPos := Pos(AnsiString('.'), Fwd);
if (Length(Fwd) in [10..90]) and (((DotPos > 0) and (DotPos < 15)) or (Pos(AnsiString('api-ms-win'), Fwd) > 0)) and (Pos(AnsiString('.#'), Fwd) = 0) then
begin
hMod := GetModuleHandleA(PAnsiChar(Copy(Fwd, 1, DotPos - 1)));
if hMod > 0 then
begin
// Not using the normal GetProcAddress because it can return apphelp hooks (e.g., CoCreateInstance when running as admin)
ProcAddr := GetLocalProcAddr(hMod, PAnsiChar(Copy(Fwd, DotPos + 1, 50)));
if ProcAddr <> nil then
Fwds.AddOrSetValue(ProcAddr, PByte(hModReal) + a^);
//Log(ltInfo, Format('%s @ %p', [PAnsiChar(Copy(Fwd, DotPos + 1, 50)), ProcAddr]));
end
//else
// Log(ltFatal, Format('Forward target not loaded: %s', [string(AnsiString(PAnsiChar(Copy(Fwd, 1, DotPos - 1))))]));
end;
Inc(a);
end;
end;
procedure TDumper.DumpToFile(const FileName: string; PE: TPEHeader);
var
FS: TFileStream;
Buf: PByte;
i: Integer;
Size, Delta, IATRawOffset: Cardinal;
begin
FS := TFileStream.Create(FileName, fmCreate);
try
Size := PE.DumpSize;
GetMem(Buf, Size);
if not RPM(FImageBase, Buf, Size) then
raise Exception.Create('DumpToFile RPM failed');
IATRawOffset := FIAT - FImageBase;
// TrimHugeSections may adjust IATRawOffset depending on what is trimmed.
Delta := PE.TrimHugeSections(Buf, IATRawOffset);
Dec(Size, Delta);
FS.Write(Buf^, Size);
FreeMem(Buf);
for i := PE.NTHeaders.FileHeader.NumberOfSections to High(PE.Sections) do
begin
FS.Write(PE.Sections[i].Data^, PE.Sections[i].Header.SizeOfRawData);
end;
PE.NTHeaders.FileHeader.NumberOfSections := Length(PE.Sections);
PE.NTHeaders.OptionalHeader.AddressOfEntryPoint := FOEP - FImageBase;
if (PE.NTHeaders.OptionalHeader.DllCharacteristics and $40) <> 0 then
begin
Log(ltInfo, 'Executable is ASLR-aware - disabling the flag in the dump');
PE.NTHeaders.OptionalHeader.DllCharacteristics := PE.NTHeaders.OptionalHeader.DllCharacteristics and not $40;
end;
PE.SaveToStream(FS);
FS.Seek(IATRawOffset, soBeginning);
FS.Write(FIATImage^, FIATImageSize);
finally
FS.Free;
end;
end;
{$POINTERMATH ON}
function TDumper.Process: TPEHeader;
var
IAT: PByte;
i, j: Integer;
IATSize, Diff: Cardinal;
LastValidOffset: NativeUInt;
PE: TPEHeader;
a: ^PByte;
Fwd: Pointer;
Thunks: TList<TImportThunk>;
Thunk: TImportThunk;
NeedNewThunk, Found: Boolean;
RM: PRemoteModule;
s: AnsiString;
Section, Strs, RangeChecker: PByte;
Descriptors: PImageImportDescriptor;
ImportSect: PPESection;
begin
if FIAT = 0 then
raise Exception.Create('Must set IAT before calling Process()');
// Read header from memory
GetMem(Section, $1000);
RPM(FImageBase, Section, $1000);
PE := TPEHeader.Create(Section);
PE.Sanitize;
FreeMem(Section);
GetMem(IAT, MAX_IAT_SIZE);
RPM(FIAT, IAT, MAX_IAT_SIZE);
LastValidOffset := 0;
i := 0;
while (i < MAX_IAT_SIZE) and ((LastValidOffset = 0) or (NativeUInt(i) < LastValidOffset + $100)) do
begin
if IsAPIAddress(PNativeUInt(IAT + i)^) then
LastValidOffset := NativeUInt(i);
Inc(i, SizeOf(Pointer));
end;
IATSize := LastValidOffset + SizeOf(Pointer);
Log(ltInfo, Format('Determined IAT size: %X', [IATSize]));
with PE.NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT] do
begin
VirtualAddress := FIAT - FImageBase;
Size := IATSize + SizeOf(Pointer);
end;
if FAllModules = nil then
TakeModuleSnapshot;
Thunks := TObjectList<TImportThunk>.Create;
a := Pointer(IAT);
NeedNewThunk := False; // whether there's an address "gap" (example: k32-api, 0, k32-api)
for i := 0 to IATSize div SizeOf(Pointer) - 1 do
begin
//Log(ltInfo, IntToHex(UIntPtr(a) - UIntPtr(IAT) + FIAT, 8) + ' -> ' + IntToHex(UIntPtr(a^), 8));
// Type 2: a^ is correct for export lookup, but need to look in different module! (ntdll --> user32)
if FForwardsType2.TryGetValue(a^, Fwd) then
begin
RangeChecker := Fwd;
end
else
begin
// Some kernel32 functions are forwarded to ntdll - restore the original address
if FForwards.TryGetValue(a^, Fwd) then
a^ := Fwd
else if FForwardsOle32.TryGetValue(a^, Fwd) then
a^ := Fwd
else if FForwardsNetapi32.TryGetValue(a^, Fwd) then
a^ := Fwd
else if FForwardsCrypt32.TryGetValue(a^, Fwd) then
a^ := Fwd
else if FForwardsDbghelp.TryGetValue(a^, Fwd) then
a^ := Fwd
else if FForwardsKernelbase.TryGetValue(a^, Fwd) then
a^ := Fwd;
RangeChecker := a^;
end;
//Log(ltInfo, ' -> ' + IntToHex(UIntPtr(a^), 8));
Found := False;
for RM in FAllModules do
if (RangeChecker > RM.Base) and (RangeChecker < RM.EndOff) then
begin
if RM.ExportTbl = nil then
GatherModuleExportsFromRemoteProcess(RM);
if RM.ExportTbl.ContainsKey(a^) then
begin
if (Thunks.Count = 0) or (Thunks.Last.Name <> RM.Name) or NeedNewThunk then
begin
Thunks.Add(TImportThunk.Create(RM));
NeedNewThunk := False; // reset
end;
Found := True;
//Log(ltInfo, 'IAT ' + IntToHex(UIntPtr(a) - UIntPtr(IAT) + FIAT, 8) + ' -> API ' + IntToHex(UIntPtr(a^), 8) + ' belongs to ' + RM.Name);
Thunks.Last.Addresses.Add(PPointer(a))
end
else
Log(ltFatal, 'IAT ' + IntToHex(UIntPtr(a) - UIntPtr(IAT) + FIAT, 8) + ' -> API ' + IntToHex(UIntPtr(a^), 8) + ' not in export table of ' + RM.Name + ' (likely a bogus entry)');
Break;
end;
if not Found then
NeedNewThunk := True;
Inc(a);
end;
ImportSect := PE.CreateSection('.import', $1000);
Section := AllocMem(ImportSect.Header.SizeOfRawData);
Pointer(Descriptors) := Section; // Map the Descriptors array to the start of the section
Strs := Section + (Thunks.Count + 1) * SizeOf(TImageImportDescriptor); // Last descriptor is empty
i := 0;
for Thunk in Thunks do
begin
Descriptors[i].FirstThunk := (FIAT - FImageBase) + UIntPtr(Thunk.Addresses.First) - UIntPtr(IAT);
Descriptors[i].Name := PE.ConvertOffsetToRVAVector(ImportSect.Header.PointerToRawData + Cardinal(Strs - Section));
Inc(i);
s := AnsiString(Thunk.Name);
Move(s[1], Strs^, Length(s));
Inc(Strs, Length(s) + 1);
RM := Thunk.Module;
Log(ltInfo, 'Thunk ' + Thunk.Name + ' - first import: ' + RM.ExportTbl[Thunk.Addresses.First^]);
for j := 0 to Thunk.Addresses.Count - 1 do
begin
Inc(Strs, 2); // Hint
s := AnsiString(RM.ExportTbl[Thunk.Addresses[j]^]);
// Set the address in the IAT to this string entry
Thunk.Addresses[j]^ := Pointer(PE.ConvertOffsetToRVAVector(ImportSect.Header.PointerToRawData + Cardinal(Strs - 2 - Section)));
Move(s[1], Strs^, Length(s));
Inc(Strs, Length(s) + 1);
if Strs > Section + ImportSect.Header.SizeOfRawData - $100 then
begin
Inc(ImportSect.Header.SizeOfRawData, $1000);
Inc(ImportSect.Header.Misc.VirtualSize, $1000);
Inc(PE.NTHeaders.OptionalHeader.SizeOfImage, $1000);
Diff := Strs - Section;
ReallocMem(Section, ImportSect.Header.SizeOfRawData);
FillChar((Section + ImportSect.Header.SizeOfRawData - $1000)^, $1000, 0);
Strs := Section + Diff;
Pointer(Descriptors) := Section;
//Log(ltInfo, 'Increased import section size to ' + IntToHex(ImportSect.Header.SizeOfRawData, 4));
end;
end;
end;
ImportSect.Data := Section;
with PE.NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] do
begin
VirtualAddress := ImportSect.Header.VirtualAddress;
Size := Thunks.Count * SizeOf(TImageImportDescriptor);
end;
Thunks.Free;
FIATImage := IAT;
FIATImageSize := IATSize;
Result := PE;
end;
procedure TDumper.GatherModuleExportsFromRemoteProcess(M: PRemoteModule);
var
Head: PByte;
Exp: PImageExportDirectory;
Off: PByte;
a, n: PCardinal;
o: PWord;
i: Integer;
begin
M.ExportTbl := TExportTable.Create;
GetMem(Head, $1000);
RPM(NativeUInt(M.Base), Head, $1000);
with PImageNtHeaders(Head + PImageDosHeader(Head)._lfanew).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] do
begin
GetMem(Exp, Size);
RPM(NativeUInt(M.Base + VirtualAddress), Exp, Size);
Off := PByte(Exp) - VirtualAddress;
end;
FreeMem(Head);
Pointer(a) := Off + Exp.AddressOfFunctions;
Pointer(n) := Off + Exp.AddressOfNames;
Pointer(o) := Off + Exp.AddressOfNameOrdinals;
for i := 0 to Exp.NumberOfNames - 1 do
begin
M.ExportTbl.AddOrSetValue(M.Base + a[o[i]], string(AnsiString(PAnsiChar(Off + n[i]))));
end;
FreeMem(Exp);
end;
function TDumper.GetLocalProcAddr(hModule: HMODULE; ProcName: PAnsiChar): Pointer;
var
Exp: PImageExportDirectory;
Off: PByte;
a, n: PCardinal;
o: PWord;
i: Integer;
begin
with PImageNtHeaders(hModule + Cardinal(PImageDosHeader(hModule)._lfanew)).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] do
begin
Exp := Pointer(hModule + VirtualAddress);
Off := PByte(Exp) - VirtualAddress;
end;
Pointer(a) := Off + Exp.AddressOfFunctions;
Pointer(n) := Off + Exp.AddressOfNames;
Pointer(o) := Off + Exp.AddressOfNameOrdinals;
for i := 0 to Exp.NumberOfNames - 1 do
if AnsiStrComp(PAnsiChar(Off + n[i]), ProcName) = 0 then
Exit(Pointer(hModule + a[o[i]]));
Result := nil;
end;
function TDumper.IsAPIAddress(Address: NativeUInt): Boolean;
var
RM: PRemoteModule;
begin
if FAllModules = nil then
TakeModuleSnapshot;
for RM in FAllModules do
if (Address >= NativeUInt(RM.Base)) and (Address < NativeUInt(RM.EndOff)) then
begin
if RM.ExportTbl = nil then
GatherModuleExportsFromRemoteProcess(RM);
Exit(RM.ExportTbl.ContainsKey(Pointer(Address)));
end;
Result := False;
end;
procedure TDumper.TakeModuleSnapshot;
var
hSnap: THandle;
ME: TModuleEntry32;
RM: PRemoteModule;
begin
FAllModules := TList<PRemoteModule>.Create;
hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, FProcess.dwProcessId);
ME.dwSize := SizeOf(TModuleEntry32);
if not Module32First(hSnap, ME) then
raise Exception.Create('Module32First');
repeat
if ME.hModule <> FImageBase then
begin
//Log(ltInfo, IntToHex(ME.hModule, 8) + ' : ' + IntToHex(ME.modBaseSize, 4) + ' : ' + string(ME.szModule));
New(RM);
RM.Base := ME.modBaseAddr;
RM.EndOff := ME.modBaseAddr + ME.modBaseSize;
RM.Name := LowerCase(ME.szModule);
RM.ExportTbl := nil;
FAllModules.Add(RM);
end;
until not Module32Next(hSnap, ME);
CloseHandle(hSnap);
end;
function TDumper.RPM(Address: NativeUInt; Buf: Pointer; BufSize: NativeUInt): Boolean;
begin
Result := ReadProcessMemory(FProcess.hProcess, Pointer(Address), Buf, BufSize, BufSize);
if not Result then
Log(ltFatal, 'RPM failed');
end;
{ TImportThunk }
constructor TImportThunk.Create(RM: PRemoteModule);
begin
Module := RM;
Name := RM.Name;
Addresses := TList<PPointer>.Create;
end;
destructor TImportThunk.Destroy;
begin
Addresses.Free;
inherited;
end;
end.