forked from AlexanderBagel/ProcessMemoryMap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryMap.PEImage.pas
More file actions
306 lines (275 loc) · 9.58 KB
/
Copy pathMemoryMap.PEImage.pas
File metadata and controls
306 lines (275 loc) · 9.58 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
////////////////////////////////////////////////////////////////////////////////
//
// ****************************************************************************
// * Project : MemoryMap
// * Unit Name : MemoryMap.PEImage.pas
// * Purpose : Класс собирает данные по секциям и директориям PE файла
// * Author : Александр (Rouse_) Багель
// * Copyright : © Fangorn Wizards Lab 1998 - 2023.
// * Version : 1.4.29
// * Home Page : http://rouse.drkb.ru
// * Home Blog : http://alexander-bagel.blogspot.ru
// ****************************************************************************
// * Stable Release : http://rouse.drkb.ru/winapi.php#pmm2
// * Latest Source : https://github.com/AlexanderBagel/ProcessMemoryMap
// ****************************************************************************
//
unit MemoryMap.PEImage;
interface
uses
Winapi.Windows,
Generics.Collections,
MemoryMap.Utils,
MemoryMap.ImageHlp,
SysUtils;
type
TSection = record
Caption: ShortString;
Address: NativeUInt;
Size: NativeUInt;
IsCode: Boolean;
IsData: Boolean;
end;
TDirectoryFlag = (dfDirectory, dfEntryPoint, dfTlsCallback);
TDirectory = record
Flag: TDirectoryFlag;
Caption: ShortString;
Address: ULONG_PTR;
Size: NativeUInt;
end;
TDirectoryArray = record
Count: Integer;
Data: array [0..14] of TDirectory;
end;
TTLSCallback = record
Caption: ShortString;
Address: Pointer;
end;
TCoffSymbol = packed record
Name: array [0..3] of Byte;
StrOfs: LongInt;
Value: LongInt;
Section: SmallInt;
Empty: Word;
Typ: Byte;
Aux: Byte;
end;
TPEImage = class
private
FProcessHandle: THandle;
FImage64: Boolean;
FImageBase: Pointer;
FImageInfo: LOADED_IMAGE;
FSections: TList<TSection>;
FDirectoryes: TList<TDirectoryArray>;
FEntryPoints: TList<Pointer>;
FTLSCallbacks: TList<TTLSCallback>;
protected
procedure EnumSections;
procedure EnumDirectories(LoadAsImage: Boolean);
public
constructor Create(AProcessHandle: THandle);
destructor Destroy; override;
procedure GetInfoFromImage(const FileName: string; ImageBase: Pointer;
FirstSectionSize: NativeUInt; LoadAsImage: Boolean = True);
function GetSectionArAddr(Value: Pointer): TSection;
property Sections: TList<TSection> read FSections;
property Directoryes: TList<TDirectoryArray> read FDirectoryes;
property EntryPoints: TList<Pointer> read FEntryPoints;
property TLSCallbacks: TList<TTLSCallback> read FTLSCallbacks;
end;
implementation
{ TPEImage }
constructor TPEImage.Create(AProcessHandle: THandle);
begin
FProcessHandle := AProcessHandle;
FSections := TList<TSection>.Create;
FDirectoryes := TList<TDirectoryArray>.Create;
FEntryPoints := TList<Pointer>.Create;
FTLSCallbacks := TList<TTLSCallback>.Create;
end;
destructor TPEImage.Destroy;
begin
FTLSCallbacks.Free;
FEntryPoints.Free;
FDirectoryes.Free;
FSections.Free;
inherited;
end;
procedure TPEImage.EnumDirectories(LoadAsImage: Boolean);
type
PLSTable32 = ^TLSTable32;
TLSTable32 = record
StartAddressOfRawData,
EndAddressOfRawData,
AddressOfIndex,
AddressOfCallBacks: UInt32;
end;
PLSTable64 = ^TLSTable64;
TLSTable64 = record
StartAddressOfRawData,
EndAddressOfRawData,
AddressOfIndex,
AddressOfCallBacks: UInt64;
end;
const
DirectoryStr: array [0..14] of string =
('export', 'import', 'resource', 'exception',
'security', 'basereloc', 'debug', 'copyright',
'globalptr', 'tls', 'load_config', 'bound_import',
'iat', 'delay_import', 'com');
var
I, A: Integer;
dwDirSize: DWORD;
DirAddr: Pointer;
Directory: TDirectoryArray;
// это все для работы с калбэками
pTLSCursor: PULONG_PTR;
pTLSTable: array [0..SizeOf(TLSTable64) - 1] of Byte;
NumberOfBytesWritten: SIZE_T;
TLSCallbackTable: array of Byte;
TLSCallbackTableCursor: Byte;
pCallBack: Pointer;
CallbackData: TTLSCallback;
function GetNextCallback: Pointer;
begin
if FImage64 then
begin
Result := Pointer(PUint64(@TLSCallbackTable[TLSCallbackTableCursor])^);
Inc(TLSCallbackTableCursor, 8);
end
else
begin
Result := Pointer(PDWORD(@TLSCallbackTable[TLSCallbackTableCursor])^);
Inc(TLSCallbackTableCursor, 4);
end;
end;
begin
ZeroMemory(@Directory, SizeOf(TDirectoryArray));
Directory.Count := 0;
for I := 0 to 14 do
begin
// Получаем адрес директории
DirAddr := ImageDirectoryEntryToData(FImageInfo.MappedAddress,
True, I, dwDirSize);
if DirAddr <> nil then
begin
Inc(Directory.Count);
Directory.Data[I].Flag := dfDirectory;
Directory.Data[I].Caption := ShortString(DirectoryStr[I]);
Directory.Data[I].Address := NativeUint(FImageBase) +
NativeUint(DirAddr) - NativeUint(FImageInfo.MappedAddress);
Directory.Data[I].Size := dwDirSize;
// дополнительно рассчитываем адреса всех TLS Callback
if I = IMAGE_DIRECTORY_ENTRY_TLS then
begin
// рассчитываем адрес TLS таблицы у удаленном АП
pTLSCursor := PULONG_PTR(NativeUint(FImageBase) +
NativeUint(DirAddr) - NativeUint(FImageInfo.MappedAddress));
// читаем начало TLS таблицы
if not ReadProcessMemory(FProcessHandle, pTLSCursor,
@pTLSTable[0], SizeOf(pTLSTable), NumberOfBytesWritten) then Continue;
// читаем саму таблицу каллбэков
SetLength(TLSCallbackTable, 256);
if FImage64 then
pTLSCursor := Pointer(PLSTable64(@pTLSTable[0])^.AddressOfCallBacks)
else
pTLSCursor := Pointer(PLSTable32(@pTLSTable[0])^.AddressOfCallBacks);
// Проверка, а вдруг мы читаем не из модуля
if (ULONG_PTR(pTLSCursor) < ULONG_PTR(FImageBase)) or
(ULONG_PTR(pTLSCursor) > (ULONG_PTR(FImageBase) + FImageInfo.SizeOfImage)) then
Continue;
// вторая проверка, а мы вообще иинициализированы?
if not LoadAsImage then Exit;
if not ReadProcessMemory(FProcessHandle,
pTLSCursor, @TLSCallbackTable[0], Length(TLSCallbackTable),
NumberOfBytesWritten) then Continue;
// читаем их последовательно (по 4 или 8 байт в зависимости от битности)
A := 0;
TLSCallbackTableCursor := 0;
pCallBack := GetNextCallback;
while pCallBack <> nil do
begin
CallbackData.Caption := ShortString('TLS Callback ' + IntToStr(A));
CallbackData.Address := pCallBack;
TLSCallbacks.Add(CallbackData);
Inc(A);
if A > 31 then // 32 калбэка? Серьезно?!!!
Break;
pCallBack := GetNextCallback;
end;
end;
end;
end;
FDirectoryes.Add(Directory);
end;
procedure TPEImage.EnumSections;
var
ImageSectionHeader: PImageSectionHeader;
I, Index: Integer;
Section: TSection;
COFFOffset, SectionNameOffset: NativeUInt;
SectionName: array [0..255] of AnsiChar;
begin
ImageSectionHeader := FImageInfo.Sections;
COFFOffset := FImageInfo.FileHeader.FileHeader.PointerToSymbolTable +
FImageInfo.FileHeader.FileHeader.NumberOfSymbols * SizeOf(TCoffSymbol);
for I := 0 to Integer(FImageInfo.NumberOfSections) - 1 do
begin
Section.Caption := Copy(ShortString(
PAnsiChar(@ImageSectionHeader^.Name[0])), 1, IMAGE_SIZEOF_SHORT_NAME);
if (COFFOffset <> 0) and (Section.Caption[1] = '/') then
begin
if TryStrToInt(Copy(string(Section.Caption), 2, 7), Index) then
begin
SectionNameOffset := COFFOffset + NativeUInt(Index);
SectionNameOffset := SectionNameOffset + NativeUint(FImageInfo.MappedAddress);
SectionName[255] := #0;
CopyMemory(@SectionName[0], Pointer(SectionNameOffset), 255);
Section.Caption := ShortString(PAnsiChar(@SectionName[0]));
end;
end;
Section.Address := NativeUint(FImageBase) + ImageSectionHeader^.VirtualAddress;
Section.Size := AlignedSectionSize(FImageInfo, ImageSectionHeader^.SizeOfRawData);
Section.IsCode := IsExecute(ImageSectionHeader^.Characteristics);
Section.IsData := IsWrite(ImageSectionHeader^.Characteristics);
FSections.Add(Section);
Inc(ImageSectionHeader);
end;
end;
procedure TPEImage.GetInfoFromImage(const FileName: string; ImageBase: Pointer;
FirstSectionSize: NativeUInt; LoadAsImage: Boolean);
var
Section: TSection;
begin
FImageBase := ImageBase;
if MapAndLoad(PAnsiChar(AnsiString(FileName)), nil, @FImageInfo, True, True) then
try
FImage64 := FImageInfo.FileHeader^.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
Section.Caption := 'PEHeader';
Section.Address := NativeUint(ImageBase);
Section.Size := FirstSectionSize;
Section.IsCode := False;
Section.IsData := False;
FSections.Add(Section);
if FImageInfo.FileHeader.OptionalHeader.AddressOfEntryPoint <> 0 then
FEntryPoints.Add(Pointer(NativeUInt(ImageBase) +
FImageInfo.FileHeader.OptionalHeader.AddressOfEntryPoint));
EnumSections;
if FProcessHandle <> 0 then
EnumDirectories(LoadAsImage);
finally
UnMapAndLoad(@FImageInfo);
end;
end;
function TPEImage.GetSectionArAddr(Value: Pointer): TSection;
var
I: TSection;
begin
ZeroMemory(@Result, SizeOf(TSection));
for I in FSections do
if I.Address <= NativeUInt(Value) then
if I.Address + I.Size > NativeUInt(Value) then
Exit(I);
end;
end.