libPeConv
A library to load, manipulate, dump PE files.
Loading...
Searching...
No Matches
imports_loader.cpp
Go to the documentation of this file.
2
3#include "peconv/util.h"
4#include "peconv/logger.h"
5
6using namespace peconv;
7
9{
10public:
11 FillImportThunks(BYTE* _modulePtr, size_t _moduleSize, t_function_resolver* func_resolver)
12 : ImportThunksCallback(_modulePtr, _moduleSize), funcResolver(func_resolver)
13 {
14 }
15
16 virtual bool processThunks(LPSTR lib_name, ULONG_PTR origFirstThunkPtr, ULONG_PTR firstThunkPtr)
17 {
18 if (this->is64b) {
19#ifdef _WIN64 // loader is 64 bit, allow to load imports for 64-bit payload:
20 IMAGE_THUNK_DATA64* desc = reinterpret_cast<IMAGE_THUNK_DATA64*>(origFirstThunkPtr);
21 ULONGLONG* call_via = reinterpret_cast<ULONGLONG*>(firstThunkPtr);
22 return processThunks_tpl<ULONGLONG, IMAGE_THUNK_DATA64>(lib_name, desc, call_via, IMAGE_ORDINAL_FLAG64);
23#else
24 LOG_ERROR("Cannot fill imports into 64-bit PE via 32-bit loader.");
25 return false;
26#endif
27 }
28 else {
29#ifndef _WIN64 // loader is 32 bit, allow to load imports for 32-bit payload:
30 IMAGE_THUNK_DATA32* desc = reinterpret_cast<IMAGE_THUNK_DATA32*>(origFirstThunkPtr);
31 DWORD* call_via = reinterpret_cast<DWORD*>(firstThunkPtr);
32 return processThunks_tpl<DWORD, IMAGE_THUNK_DATA32>(lib_name, desc, call_via, IMAGE_ORDINAL_FLAG32);
33#else
34 LOG_ERROR("Cannot fill imports into 32-bit PE via 64-bit loader.");
35 return false;
36#endif
37 }
38 }
39
40protected:
41 template <typename T_FIELD, typename T_IMAGE_THUNK_DATA>
42 bool processThunks_tpl(LPSTR lib_name, T_IMAGE_THUNK_DATA* desc, T_FIELD* call_via, T_FIELD ordinal_flag)
43 {
44 if (!this->funcResolver) {
45 return false;
46 }
47
48 const bool is_by_ord = (desc->u1.Ordinal & ordinal_flag) != 0;
49
50 FARPROC hProc = nullptr;
51 if (is_by_ord) {
52 T_FIELD raw_ordinal = desc->u1.Ordinal & (~ordinal_flag);
53 LOG_DEBUG("raw ordinal: 0x%llx.", (unsigned long long)raw_ordinal);
54 hProc = funcResolver->resolve_func(lib_name, MAKEINTRESOURCEA(raw_ordinal));
55
56 }
57 else {
58 PIMAGE_IMPORT_BY_NAME by_name = (PIMAGE_IMPORT_BY_NAME)((ULONGLONG)modulePtr + desc->u1.AddressOfData);
59 if (!validate_ptr(modulePtr, moduleSize, by_name, sizeof(IMAGE_IMPORT_BY_NAME))) {
60 LOG_ERROR("Invalid pointer to IMAGE_IMPORT_BY_NAME.");
61 return false;
62 }
63 const LPSTR func_name = reinterpret_cast<LPSTR>(by_name->Name);
64 if (!is_valid_string(modulePtr, moduleSize, func_name)) {
65 LOG_ERROR("Invalid pointer to function name.");
66 return false;
67 }
68 LOG_DEBUG("name: %s.", func_name);
69 hProc = this->funcResolver->resolve_func(lib_name, func_name);
70 }
71 if (!hProc) {
72 LOG_ERROR("Could not resolve the function.");
73 return false;
74 }
75 (*call_via) = reinterpret_cast<T_FIELD>(hProc);
76 return true;
77 }
78
79 //fields:
81};
82
83//---
84
89{
90public:
91 CollectThunksCallback(BYTE* _vBuf, size_t _vBufSize, std::set<DWORD>& _fields)
92 : ImportThunksCallback(_vBuf, _vBufSize), vBuf(_vBuf), vBufSize(_vBufSize),
93 fields(_fields)
94 {
95 }
96
97 virtual bool processThunks(LPSTR libName, ULONG_PTR origFirstThunkPtr, ULONG_PTR va)
98 {
99 if (!va) {
100 return false; // invalid thunk
101 }
102 const ULONGLONG module_base = reinterpret_cast<ULONGLONG>(this->vBuf);
103 if (va < module_base) {
104 return false; // not this module
105 }
106 if (va >= module_base + this->vBufSize) {
107 return false; // not this module
108 }
109 DWORD thunk_rva = MASK_TO_DWORD(va - module_base);
110 fields.insert(thunk_rva);
111 return true;
112 }
113
114 std::set<DWORD>& fields;
115 BYTE* vBuf;
116 size_t vBufSize;
117};
118
119//---
120
122{
123public:
124 CollectImportsCallback(BYTE* _modulePtr, size_t _moduleSize, std::map<DWORD, ExportedFunc*> &_thunkToFunc)
125 : ImportThunksCallback(_modulePtr, _moduleSize), thunkToFunc(_thunkToFunc)
126 {
127 }
128
129 virtual bool processThunks(LPSTR lib_name, ULONG_PTR origFirstThunkPtr, ULONG_PTR firstThunkPtr)
130 {
131 if (this->is64b) {
132 IMAGE_THUNK_DATA64* desc = reinterpret_cast<IMAGE_THUNK_DATA64*>(origFirstThunkPtr);
133 ULONGLONG* call_via = reinterpret_cast<ULONGLONG*>(firstThunkPtr);
134 return processThunks_tpl<ULONGLONG, IMAGE_THUNK_DATA64>(lib_name, desc, call_via, IMAGE_ORDINAL_FLAG64);
135
136 }
137 else {
138
139 IMAGE_THUNK_DATA32* desc = reinterpret_cast<IMAGE_THUNK_DATA32*>(origFirstThunkPtr);
140 DWORD* call_via = reinterpret_cast<DWORD*>(firstThunkPtr);
141 return processThunks_tpl<DWORD, IMAGE_THUNK_DATA32>(lib_name, desc, call_via, IMAGE_ORDINAL_FLAG32);
142 }
143 }
144
145protected:
146 template <typename T_FIELD, typename T_IMAGE_THUNK_DATA>
147 bool processThunks_tpl(LPSTR lib_name, T_IMAGE_THUNK_DATA* desc, T_FIELD* call_via, T_FIELD ordinal_flag)
148 {
149 if (!call_via) {
150 return false;
151 }
152
153 const std::string short_name = peconv::get_dll_shortname(lib_name);
154 const bool is_by_ord = (desc->u1.Ordinal & ordinal_flag) != 0;
155 ExportedFunc *func = nullptr;
156
157 if (is_by_ord) {
158 T_FIELD raw_ordinal = desc->u1.Ordinal & (~ordinal_flag);
159 func = new ExportedFunc(short_name, IMAGE_ORDINAL64(raw_ordinal));
160 }
161 else {
162 PIMAGE_IMPORT_BY_NAME by_name = (PIMAGE_IMPORT_BY_NAME)((ULONGLONG)modulePtr + desc->u1.AddressOfData);
163 if (!validate_ptr(modulePtr, moduleSize, by_name, sizeof(IMAGE_IMPORT_BY_NAME))) {
164 LOG_ERROR("Invalid pointer to IMAGE_IMPORT_BY_NAME.");
165 return false;
166 }
167 const LPSTR func_name = reinterpret_cast<LPSTR>(by_name->Name);
168 if (!is_valid_string(modulePtr, moduleSize, func_name)) {
169 LOG_ERROR("Invalid pointer to function name.");
170 return false;
171 }
172 const WORD ordinal = by_name->Hint;
173 func = new ExportedFunc(short_name, func_name, ordinal);
174 }
175 if (!func) {
176 return false;
177 }
178 const DWORD rva = MASK_TO_DWORD((ULONG_PTR)call_via - (ULONG_PTR)modulePtr);
179 thunkToFunc[rva] = func;
180 return true;
181 }
182
183 std::map<DWORD, ExportedFunc*> &thunkToFunc;
184};
185
186
187//---
188
189template <typename T_FIELD, typename T_IMAGE_THUNK_DATA>
190bool process_imp_functions_tpl(BYTE* modulePtr, size_t module_size, LPSTR lib_name, DWORD call_via, DWORD thunk_addr, IN ImportThunksCallback *callback)
191{
192 bool is_ok = true;
193
194 T_FIELD *thunks = (T_FIELD*)((ULONGLONG)modulePtr + thunk_addr);
195 T_FIELD *callers = (T_FIELD*)((ULONGLONG)modulePtr + call_via);
196
197 for (size_t index = 0; true; index++) {
198 if (!validate_ptr(modulePtr, module_size, &callers[index], sizeof(T_FIELD))) {
199 break;
200 }
201 if (!validate_ptr(modulePtr, module_size, &thunks[index], sizeof(T_FIELD))) {
202 break;
203 }
204 if (callers[index] == 0) {
205 //nothing to fill, probably the last record
206 return true;
207 }
208 LPVOID thunk_ptr = &thunks[index];
209 T_IMAGE_THUNK_DATA* desc = reinterpret_cast<T_IMAGE_THUNK_DATA*>(thunk_ptr);
210 if (!validate_ptr(modulePtr, module_size, desc, sizeof(T_IMAGE_THUNK_DATA))) {
211 break;
212 }
213 if (!desc->u1.Function) {
214 break;
215 }
216 T_FIELD ordinal_flag = (sizeof(T_FIELD) == sizeof(ULONGLONG)) ? IMAGE_ORDINAL_FLAG64 : IMAGE_ORDINAL_FLAG32;
217 bool is_by_ord = (desc->u1.Ordinal & ordinal_flag) != 0;
218 if (!is_by_ord) {
219 PIMAGE_IMPORT_BY_NAME by_name = (PIMAGE_IMPORT_BY_NAME)((ULONGLONG)modulePtr + desc->u1.AddressOfData);
220 if (!validate_ptr(modulePtr, module_size, by_name, sizeof(IMAGE_IMPORT_BY_NAME))) {
221 break;
222 }
223 }
224 //when the callback is called, all the pointers should be already verified
225 if (!callback->processThunks(lib_name, (ULONG_PTR)&thunks[index], (ULONG_PTR)&callers[index])) {
226 is_ok = false;
227 }
228 }
229 return is_ok;
230}
231
232//Walk through the table of imported DLLs (starting from the given descriptor) and execute the callback each time when the new record was found
233bool process_dlls(BYTE* modulePtr, size_t module_size, IMAGE_IMPORT_DESCRIPTOR *first_desc, IN ImportThunksCallback *callback)
234{
235 bool isAllFilled = true;
236 LOG_DEBUG("---IMP---");
237 const bool is64 = is64bit((BYTE*)modulePtr);
238 IMAGE_IMPORT_DESCRIPTOR* lib_desc = nullptr;
239
240 for (size_t i = 0; true; i++) {
241 lib_desc = &first_desc[i];
242 if (!validate_ptr(modulePtr, module_size, lib_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
243 break;
244 }
245 if (!lib_desc->OriginalFirstThunk && !lib_desc->FirstThunk) {
246 break;
247 }
248 LPSTR lib_name = (LPSTR)((ULONGLONG)modulePtr + lib_desc->Name);
249 if (!peconv::is_valid_import_name(modulePtr, module_size, lib_name)) {
250 //invalid name
251 return false;
252 }
253 DWORD call_via = lib_desc->FirstThunk;
254 DWORD thunk_addr = lib_desc->OriginalFirstThunk;
255 if (!thunk_addr) {
256 thunk_addr = lib_desc->FirstThunk;
257 }
258 LOG_DEBUG("Imported Lib: 0x%lx : 0x%lx : 0x%lx", lib_desc->FirstThunk, lib_desc->OriginalFirstThunk, lib_desc->Name);
259 bool all_solved = false;
260 if (is64) {
261 all_solved = process_imp_functions_tpl<ULONGLONG, IMAGE_THUNK_DATA64>(modulePtr, module_size, lib_name, call_via, thunk_addr, callback);
262 }
263 else {
264 all_solved = process_imp_functions_tpl<DWORD, IMAGE_THUNK_DATA32>(modulePtr, module_size, lib_name, call_via, thunk_addr, callback);
265 }
266 if (!all_solved) {
267 isAllFilled = false;
268 }
269 }
270 LOG_DEBUG("---------");
271 return isAllFilled;
272}
273
274bool peconv::process_import_table(IN BYTE* modulePtr, IN SIZE_T moduleSize, IN ImportThunksCallback *callback)
275{
276 if (moduleSize == 0) { //if not given, try to fetch
277 moduleSize = peconv::get_image_size((const BYTE*)modulePtr);
278 }
279 if (moduleSize == 0) return false;
280
281 IMAGE_DATA_DIRECTORY *importsDir = get_directory_entry((BYTE*)modulePtr, IMAGE_DIRECTORY_ENTRY_IMPORT);
282 if (!importsDir) {
283 return true; //no import table
284 }
285 const DWORD impAddr = importsDir->VirtualAddress;
286 IMAGE_IMPORT_DESCRIPTOR *first_desc = (IMAGE_IMPORT_DESCRIPTOR*)(impAddr + (ULONG_PTR)modulePtr);
287 if (!peconv::validate_ptr(modulePtr, moduleSize, first_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
288 return false;
289 }
290 return process_dlls(modulePtr, moduleSize, first_desc, callback);
291}
292
293bool peconv::load_imports(BYTE* modulePtr, t_function_resolver* func_resolver)
294{
295 size_t moduleSize = peconv::get_image_size((const BYTE*)modulePtr);
296 if (moduleSize == 0) return false;
297
298 bool is64 = is64bit((BYTE*)modulePtr);
299 bool is_loader64 = false;
300#ifdef _WIN64
301 is_loader64 = true;
302#endif
303 if (is64 != is_loader64) {
304 LOG_ERROR("Loader/Payload bitness mismatch.");
305 return false;
306 }
307
308 default_func_resolver default_res;
309 if (!func_resolver) {
310 func_resolver = &default_res;
311 }
312
313 FillImportThunks callback(modulePtr, moduleSize, func_resolver);
314 return peconv::process_import_table(modulePtr, moduleSize, &callback);
315}
316
317// A valid name must contain printable characters. Empty name is also acceptable (may have been erased)
318bool peconv::is_valid_import_name(const PBYTE modulePtr, const size_t moduleSize, LPSTR lib_name)
319{
320 bool is_terminated = false;
321 for (size_t i = 0; i < MAX_PATH; i++) {
322 if (!peconv::validate_ptr(modulePtr, moduleSize, lib_name, sizeof(char))) {
323 return false;
324 }
325 char next_char = *lib_name;
326 if (next_char == '\0') {
327 is_terminated = true;
328 break;
329 }
330 if (next_char < 0x20 || next_char >= 0x7E) {
331 return false;
332 }
333 lib_name++;
334 }
335 return is_terminated;
336}
337
338namespace {
339 template <typename FIELD_T>
340 bool _has_valid_import_table(const PBYTE modulePtr, size_t moduleSize, size_t maxCount = 0)
341 {
342 IMAGE_DATA_DIRECTORY* importsDir = get_directory_entry((BYTE*)modulePtr, IMAGE_DIRECTORY_ENTRY_IMPORT);
343 if (!importsDir) return false;
344
345 const DWORD impAddr = importsDir->VirtualAddress;
346 if (impAddr == 0 || impAddr >= moduleSize) {
347 return false;
348 }
349 IMAGE_IMPORT_DESCRIPTOR* lib_desc = nullptr;
350 size_t parsedSize = 0;
351 size_t valid_records = 0;
352
353 bool is_terminated = false;
354 while (parsedSize < moduleSize) { // import table size doesn't matter
355
356 if (maxCount != 0 && valid_records >= maxCount) {
357 break; // break when the hardlimit was hit
358 }
359 lib_desc = (IMAGE_IMPORT_DESCRIPTOR*)((ULONG_PTR)impAddr + parsedSize + (ULONG_PTR)modulePtr);
360 if (!peconv::validate_ptr(modulePtr, moduleSize, lib_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
361 return false;
362 }
363 parsedSize += sizeof(IMAGE_IMPORT_DESCRIPTOR);
364
365 if (!lib_desc->OriginalFirstThunk && !lib_desc->FirstThunk) {
366 is_terminated = true;
367 break;
368 }
369 LPSTR lib_name = (LPSTR)((ULONGLONG)modulePtr + lib_desc->Name);
370 if (!is_valid_import_name(modulePtr, moduleSize, lib_name)) return false;
371
372 DWORD call_via = lib_desc->FirstThunk;
373 DWORD thunk_addr = lib_desc->OriginalFirstThunk;
374 if (!thunk_addr) thunk_addr = lib_desc->FirstThunk;
375
376 FIELD_T* thunks = (FIELD_T*)((ULONGLONG)modulePtr + thunk_addr);
377 if (!peconv::validate_ptr(modulePtr, moduleSize, thunks, sizeof(FIELD_T))) return false;
378
379 FIELD_T* callers = (FIELD_T*)((ULONGLONG)modulePtr + call_via);
380 if (!peconv::validate_ptr(modulePtr, moduleSize, callers, sizeof(FIELD_T))) return false;
381
382 valid_records++;
383 }
384 return is_terminated && (valid_records > 0);
385 }
386};
387
388bool peconv::has_valid_import_table(const PBYTE modulePtr, size_t moduleSize, size_t maxCount)
389{
390 if (peconv::is64bit(modulePtr)) {
391 return _has_valid_import_table<ULONGLONG>(modulePtr, moduleSize, maxCount);
392 }
393 return _has_valid_import_table<DWORD>(modulePtr, moduleSize, maxCount);
394}
395
396bool peconv::collect_thunks(IN BYTE* modulePtr, IN SIZE_T moduleSize, OUT std::set<DWORD>& thunk_rvas)
397{
398 CollectThunksCallback collector(modulePtr, moduleSize, thunk_rvas);
399 return peconv::process_import_table(modulePtr, moduleSize, &collector);
400}
401
402bool peconv::collect_imports(IN BYTE* modulePtr, IN SIZE_T moduleSize, OUT ImportsCollection &collection)
403{
404 CollectImportsCallback collector(modulePtr, moduleSize, collection.thunkToFunc);
405 return peconv::process_import_table(modulePtr, moduleSize, &collector);
406}
407
#define MASK_TO_DWORD(val)
Definition: buffer_util.h:12
CollectImportsCallback(BYTE *_modulePtr, size_t _moduleSize, std::map< DWORD, ExportedFunc * > &_thunkToFunc)
bool processThunks_tpl(LPSTR lib_name, T_IMAGE_THUNK_DATA *desc, T_FIELD *call_via, T_FIELD ordinal_flag)
virtual bool processThunks(LPSTR lib_name, ULONG_PTR origFirstThunkPtr, ULONG_PTR firstThunkPtr)
std::map< DWORD, ExportedFunc * > & thunkToFunc
virtual bool processThunks(LPSTR libName, ULONG_PTR origFirstThunkPtr, ULONG_PTR va)
CollectThunksCallback(BYTE *_vBuf, size_t _vBufSize, std::set< DWORD > &_fields)
std::set< DWORD > & fields
FillImportThunks(BYTE *_modulePtr, size_t _moduleSize, t_function_resolver *func_resolver)
bool processThunks_tpl(LPSTR lib_name, T_IMAGE_THUNK_DATA *desc, T_FIELD *call_via, T_FIELD ordinal_flag)
virtual bool processThunks(LPSTR lib_name, ULONG_PTR origFirstThunkPtr, ULONG_PTR firstThunkPtr)
t_function_resolver * funcResolver
virtual FARPROC resolve_func(LPCSTR lib_name, LPCSTR func_name)=0
bool process_dlls(BYTE *modulePtr, size_t module_size, IMAGE_IMPORT_DESCRIPTOR *first_desc, IN ImportThunksCallback *callback)
bool process_imp_functions_tpl(BYTE *modulePtr, size_t module_size, LPSTR lib_name, DWORD call_via, DWORD thunk_addr, IN ImportThunksCallback *callback)
Parsing and filling the Import Table.
Compile-time configurable logging macros for peconv.
#define LOG_DEBUG(fmt,...)
Definition: logger.h:80
#define LOG_ERROR(fmt,...)
Definition: logger.h:60
bool has_valid_import_table(const PBYTE modulePtr, size_t moduleSize, size_t max_count=0)
bool is_valid_string(LPVOID modulePtr, const size_t moduleSize, const CHAR_T *name_ptr, const size_t max_len=260)
Definition: util.h:61
bool process_import_table(IN BYTE *modulePtr, IN SIZE_T moduleSize, IN ImportThunksCallback *callback)
bool validate_ptr(IN const void *buffer_bgn, IN size_t buffer_size, IN const void *field_bgn, IN size_t field_size)
Definition: buffer_util.cpp:9
DWORD get_image_size(IN const BYTE *payload)
bool collect_thunks(IN BYTE *modulePtr, IN SIZE_T moduleSize, OUT std::set< DWORD > &thunk_rvas)
bool is64bit(IN const BYTE *pe_buffer)
bool is_valid_import_name(const PBYTE modulePtr, const size_t moduleSize, LPSTR lib_name)
IMAGE_DATA_DIRECTORY * get_directory_entry(IN const BYTE *pe_buffer, IN DWORD dir_id, IN bool allow_empty=false)
bool collect_imports(IN BYTE *modulePtr, IN SIZE_T moduleSize, OUT ImportsCollection &collection)
std::string get_dll_shortname(const std::string &str)
bool load_imports(BYTE *modulePtr, t_function_resolver *func_resolver=nullptr)
Miscellaneous utility functions.