libPeConv
A library to load, manipulate, dump PE files.
Loading...
Searching...
No Matches
fix_imports.cpp
Go to the documentation of this file.
3#include "peconv/file_util.h"
4
5#include <iostream>
6#include <algorithm>
7
8using namespace peconv;
9
10template <typename FIELD_T>
11size_t find_addresses_to_fill(FIELD_T call_via, FIELD_T thunk_addr, LPVOID modulePtr, size_t moduleSize, IN const peconv::ExportsMapper& exportsMap, OUT std::set<ULONGLONG> &addresses)
12{
13 size_t addrCounter = 0;
14 do {
15 LPVOID call_via_ptr = (LPVOID)((ULONGLONG)modulePtr + call_via);
16 if (call_via_ptr == nullptr) break;
17
18 LPVOID thunk_ptr = (LPVOID)((ULONGLONG)modulePtr + thunk_addr);
19 if (thunk_ptr == nullptr) break;
20
21 if (!validate_ptr(modulePtr, moduleSize, thunk_ptr, sizeof(FIELD_T))) {
22 break;
23 }
24 if (!validate_ptr(modulePtr, moduleSize, call_via_ptr, sizeof(FIELD_T))) {
25 break;
26 }
27 FIELD_T *thunk_val = reinterpret_cast<FIELD_T*>(thunk_ptr);
28 FIELD_T *call_via_val = reinterpret_cast<FIELD_T*>(call_via_ptr);
29 if (*call_via_val == 0) {
30 //nothing to fill, probably the last record
31 break;
32 }
33
34 ULONGLONG searchedAddr = ULONGLONG(*call_via_val);
35 if (exportsMap.find_export_by_va(searchedAddr) != nullptr) {
36 addresses.insert(searchedAddr);
37 addrCounter++;
38 }
39 //---
40 call_via += sizeof(FIELD_T);
41 thunk_addr += sizeof(FIELD_T);
42 } while (true);
43
44 return addrCounter;
45}
46
47std::set<std::string> get_all_dlls_exporting_function(ULONGLONG func_addr, const peconv::ExportsMapper& exportsMap)
48{
49 std::set<std::string> currDllNames;
50 //1. Get all the functions from all accessible DLLs that correspond to this address:
51 const std::set<ExportedFunc>* exports_for_va = exportsMap.find_exports_by_va(func_addr);
52 if (!exports_for_va) {
53 std::cerr << "Cannot find any DLL exporting: " << std::hex << func_addr << std::endl;
54 return currDllNames; //empty
55 }
56 //2. Iterate through their DLL names and add them to a set:
57 for (std::set<ExportedFunc>::iterator strItr = exports_for_va->begin();
58 strItr != exports_for_va->end();
59 ++strItr)
60 {
61 currDllNames.insert(strItr->libName);
62 }
63 return currDllNames;
64}
65
66std::set<std::string> get_dlls_intersection(const std::set<std::string> &dllNames, const std::set<std::string> &currDllNames)
67{
68 std::set<std::string> resultSet;
69 std::set_intersection(dllNames.begin(), dllNames.end(),
70 currDllNames.begin(), currDllNames.end(),
71 std::inserter(resultSet, resultSet.begin())
72 );
73 return resultSet;
74}
75
76//find the name of the DLL that can cover all the addresses of imported functions
77std::string find_covering_dll(std::set<ULONGLONG> &addresses, const peconv::ExportsMapper& exportsMap)
78{
79 std::set<std::string> mainDllsSet;
80 std::set<std::string> reserveDllSet;
81 bool isFresh = true;
82
83 // the earliest addresses are more significant for the final decision on what DLL to choose
84 // so, they should be processed at the end
85 std::set<ULONGLONG>::iterator addrItr;
86
87 for (addrItr = addresses.begin(); addrItr != addresses.end(); ++addrItr) {
88 ULONGLONG searchedAddr = *addrItr;
89 //---
90 // 1. Find all the DLLs exporting this particular function (can be forwarded etc)
91 std::set<std::string> currDllNames = get_all_dlls_exporting_function(searchedAddr, exportsMap);
92
93 //2. Which of those DLLs covers also previous functions from this series?
94 if (isFresh) {
95 //if no other function was processed before, set the current DLL set as the total set
96 mainDllsSet = currDllNames;
97 isFresh = false;
98 continue;
99 }
100 // find the intersection between the total set and the current set
101 std::set<std::string> resultSet = get_dlls_intersection(mainDllsSet, currDllNames);
102 if (resultSet.size() > 0) {
103 //found intersection, overwrite the main set
104 mainDllsSet = resultSet;
105 continue;
106 }
107 // if no intersection found in the main set, check if there is any in the reserved set:
108 resultSet = get_dlls_intersection(reserveDllSet, currDllNames);
109 if (resultSet.size() > 0) {
110 //found intersection, overwrite the main set
111 reserveDllSet = mainDllsSet; // move the current to the reserve
112 mainDllsSet = resultSet;
113 continue;
114 }
115 // no intersection found with any of the sets:
116 reserveDllSet = currDllNames; //set is as a reserved DLL: to be used if it will reoccur
117 }
118 if (mainDllsSet.size() > 0) {
119 const std::string main_dll = *(mainDllsSet.begin());
120 return main_dll;
121 }
122 return "";
123}
124
126{
127 std::string found_name = find_covering_dll(this->addresses, this->exportsMap);
128 if (found_name.length() == 0) {
129#ifdef _DEBUG
130 std::cerr << "Cannot find a covering DLL" << std::endl;
131#endif
132 return false;
133 }
134 this->dllName = found_name;
135#ifdef _DEBUG
136 std::cout << "[+] Found DLL name: " << found_name << std::endl;
137#endif
138 return true;
139}
140
141size_t map_addresses_to_functions(std::set<ULONGLONG> &addresses,
142 IN const std::string &chosenDll,
143 IN const peconv::ExportsMapper& exportsMap,
144 OUT std::map<ULONGLONG, std::set<ExportedFunc>> &addr_to_func,
145 OUT std::set<ULONGLONG> &not_found
146)
147{
148 std::set<ULONGLONG> coveredAddresses;
149 std::set<ULONGLONG>::iterator addrItr;
150 for (addrItr = addresses.begin(); addrItr != addresses.end(); ++addrItr) {
151
152 ULONGLONG searchedAddr = *addrItr;
153
154 const std::set<ExportedFunc>* exports_for_va = exportsMap.find_exports_by_va(searchedAddr);
155 if (exports_for_va == nullptr) {
156 not_found.insert(searchedAddr);
157#ifdef _DEBUG
158 std::cerr << "Cannot find any DLL exporting: " << std::hex << searchedAddr << std::endl;
159#endif
160 continue;
161 }
162
163 for (std::set<ExportedFunc>::iterator strItr = exports_for_va->begin();
164 strItr != exports_for_va->end();
165 ++strItr)
166 {
167 std::string dll_name = strItr->libName;
168 if (dll_name != chosenDll) {
169 continue;
170 }
171 ExportedFunc func = *strItr;
172 addr_to_func[searchedAddr].insert(func);
173 coveredAddresses.insert(searchedAddr);
174 }
175 if (addr_to_func.find(searchedAddr) == addr_to_func.end()) {
176 const ExportedFunc* func = exportsMap.find_export_by_va(searchedAddr);
177 not_found.insert(searchedAddr);
178#ifdef _DEBUG
179 std::cerr << "[WARNING] A function: " << func->toString() << " not found in the covering DLL: " << chosenDll << std::endl;
180#endif
181 }
182 }
183 return coveredAddresses.size();
184}
185
187{
188 //reset all stored info:
189 this->mappedDllName = dll;
190 if (this->addrToFunc.size() > 0) {
191 this->addrToFunc.clear();
192 }
193 this->notFound.clear();
194
195 const size_t coveredCount = map_addresses_to_functions(this->addresses, dll, this->exportsMap, this->addrToFunc, this->notFound);
196#ifdef _DEBUG
197 if (notFound.size()) {
198 std::cout << "[-] Not all addresses are covered! Not found: " << std::dec << notFound.size() << std::endl;
199 } else {
200
201 std::cout << "All covered!" << std::endl;
202 }
203#endif
204 return coveredCount;
205}
206
207void ImpsNotCovered::insert(DWORD thunkRVA, ULONGLONG searchedAddr)
208{
209#ifdef _DEBUG
210 std::cerr << "[-] Function not recovered: [" << std::hex << searchedAddr << "] " << std::endl;
211#endif
212 thunkToAddr[thunkRVA] = searchedAddr;
213}
214
215
216bool peconv::fix_imports(IN OUT PVOID modulePtr, IN size_t moduleSize, IN const peconv::ExportsMapper& exportsMap, OUT OPTIONAL peconv::ImpsNotCovered* notCovered)
217{
218 bool skip_bound = false; // skip boud imports?
219 IMAGE_DATA_DIRECTORY *importsDir = peconv::get_directory_entry((const BYTE*) modulePtr, IMAGE_DIRECTORY_ENTRY_IMPORT);
220 if (importsDir == NULL) {
221 return true; // done! no imports -> nothing to fix
222 }
223 bool is64 = peconv::is64bit((BYTE*)modulePtr);
224 DWORD maxSize = importsDir->Size;
225 DWORD impAddr = importsDir->VirtualAddress;
226
227 IMAGE_IMPORT_DESCRIPTOR* lib_desc = NULL;
228 DWORD parsedSize = 0;
229#ifdef _DEBUG
230 printf("---IMP---\n");
231#endif
232
233 while (parsedSize < maxSize) {
234
235 lib_desc = (IMAGE_IMPORT_DESCRIPTOR*)(impAddr + parsedSize + (ULONG_PTR) modulePtr);
236 if (!validate_ptr(modulePtr, moduleSize, lib_desc, sizeof(IMAGE_IMPORT_DESCRIPTOR))) {
237#ifdef _DEBUG
238 std::cout << "[-] Invalid descriptor pointer!\n";
239#endif
240 return false;
241 }
242 parsedSize += sizeof(IMAGE_IMPORT_DESCRIPTOR);
243 if (lib_desc->OriginalFirstThunk == NULL && lib_desc->FirstThunk == NULL) {
244 break;
245 }
246 const bool is_bound = (lib_desc->TimeDateStamp == (-1));
247 if (is_bound && skip_bound) {
248 continue;
249 }
250#ifdef _DEBUG
251 printf("Imported Lib: %x : %x : %x\n", lib_desc->FirstThunk, lib_desc->OriginalFirstThunk, lib_desc->Name);
252#endif
253
254 std::string lib_name = "";
255 if (lib_desc->Name != 0) {
256 LPSTR name_ptr = (LPSTR)((ULONGLONG) modulePtr + lib_desc->Name);
257 if (validate_ptr(modulePtr, moduleSize, name_ptr, sizeof(char) * MIN_DLL_LEN)) {
258 lib_name = (LPSTR)((ULONGLONG) modulePtr + lib_desc->Name);
259 }
260 }
261
262 DWORD call_via = lib_desc->FirstThunk;
263 DWORD thunk_addr = lib_desc->OriginalFirstThunk; // warning: it can be NULL!
264 std::set<ULONGLONG> addresses;
265 if (!is64) {
266 find_addresses_to_fill<DWORD>(call_via, thunk_addr, modulePtr, moduleSize, exportsMap, addresses);
267 } else {
268 find_addresses_to_fill<ULONGLONG>(call_via, thunk_addr, modulePtr, moduleSize, exportsMap, addresses);
269 }
270 ImportedDllCoverage dllCoverage(addresses, exportsMap);
271 bool is_all_covered = dllCoverage.findCoveringDll();
272 bool is_lib_erased = false;
273
274 lib_name = get_dll_shortname(lib_name); //without extension
275
276 if (lib_name.length() == 0) {
277 is_lib_erased = true;
278 if (is_all_covered) {
279 // set a name of the covering DLL:
280 lib_name = dllCoverage.dllName;
281 }
282 }
283 if (lib_name.length() == 0) {
284 //could not find a relevant DLL
285 continue;
286 }
287#ifdef _DEBUG
288 std::cout << lib_name << std::endl;
289#endif
290 if (!dllCoverage.mapAddressesToFunctions(lib_name)) {
291 // cannot find any functions imported from this DLL
292 continue;
293 }
294 //everything mapped, now recover it:
295 ImportsUneraser impUneraser(modulePtr, moduleSize);
296 if (!impUneraser.uneraseDllImports(lib_desc, dllCoverage, notCovered)) {
297 return false;
298 }
299 if (is_lib_erased) {
300 const std::string dll_with_ext = exportsMap.get_dll_fullname(dllCoverage.dllName);
301 impUneraser.uneraseDllName(lib_desc, dll_with_ext);
302 }
303 }
304#ifdef _DEBUG
305 std::cout << "---------" << std::endl;
306#endif
307 return true;
308}
std::string toString() const
const std::set< ExportedFunc > * find_exports_by_va(ULONGLONG va) const
const peconv::ExportsMapper & exportsMap
size_t mapAddressesToFunctions(const std::string &_mappedDllName)
std::set< ULONGLONG > notFound
Definition fix_imports.h:95
std::set< ULONGLONG > & addresses
std::map< ULONGLONG, std::set< ExportedFunc > > addrToFunc
Definition fix_imports.h:90
bool uneraseDllName(IMAGE_IMPORT_DESCRIPTOR *lib_desc, const std::string &dll_name)
bool uneraseDllImports(IN OUT IMAGE_IMPORT_DESCRIPTOR *lib_desc, IN ImportedDllCoverage &dllCoverage, OUT OPTIONAL ImpsNotCovered *not_covered)
void insert(DWORD thunkRVA, ULONGLONG searchedAddr)
std::map< DWORD, ULONGLONG > thunkToAddr
Definition fix_imports.h:41
Functions related to operations on files. Wrappers for read/write.
std::string find_covering_dll(std::set< ULONGLONG > &addresses, const peconv::ExportsMapper &exportsMap)
size_t map_addresses_to_functions(std::set< ULONGLONG > &addresses, IN const std::string &chosenDll, IN const peconv::ExportsMapper &exportsMap, OUT std::map< ULONGLONG, std::set< ExportedFunc > > &addr_to_func, OUT std::set< ULONGLONG > &not_found)
std::set< std::string > get_all_dlls_exporting_function(ULONGLONG func_addr, const peconv::ExportsMapper &exportsMap)
size_t find_addresses_to_fill(FIELD_T call_via, FIELD_T thunk_addr, LPVOID modulePtr, size_t moduleSize, IN const peconv::ExportsMapper &exportsMap, OUT std::set< ULONGLONG > &addresses)
std::set< std::string > get_dlls_intersection(const std::set< std::string > &dllNames, const std::set< std::string > &currDllNames)
Functions and classes responsible for fixing Import Table. A definition of ImportedDllCoverage class.
#define MIN_DLL_LEN
Definition fix_imports.h:21
A definition of ImportsUneraser class - for recovery of a partialy erased Import Table.
bool fix_imports(IN OUT PVOID modulePtr, IN size_t moduleSize, IN const peconv::ExportsMapper &exportsMap, OUT OPTIONAL peconv::ImpsNotCovered *notCovered)
bool validate_ptr(IN const void *buffer_bgn, IN size_t buffer_size, IN const void *field_bgn, IN size_t field_size)
bool is64bit(IN const BYTE *pe_buffer)
IMAGE_DATA_DIRECTORY * get_directory_entry(IN const BYTE *pe_buffer, IN DWORD dir_id, IN bool allow_empty=false)
std::string get_dll_shortname(const std::string &str)