-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathdependencycheck.cpp
311 lines (244 loc) · 7.67 KB
/
dependencycheck.cpp
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
// Copyright (c) 2016 SMART Technologies. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "dependencycheck.h"
#include "activationcontext.h"
#include "peparser.h"
#include "widestring.h"
#include "json/json.h"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <set>
namespace fs = boost::filesystem;
namespace peparser
{
bool IsNonExecutablePE(const fs::path& path)
{
auto ext = boost::algorithm::to_lower_copy(path.extension().wstring());
return ext == L"" || ext == L".dll" || ext == L".cpl" || ext == L".sys";
}
std::list<fs::path> ListFiles(const fs::path& path, const std::function<bool(const fs::path&)>& filter)
{
std::list<fs::path> files;
if (fs::is_directory(path))
std::for_each(fs::directory_iterator(path), fs::directory_iterator(), [&](const fs::path& path)
{
files.splice(files.end(), ListFiles(path, filter));
});
else
if (filter(path))
files.push_back(path);
return files;
}
std::wstring GetModuleFileName(HMODULE handle)
{
if (!handle)
return std::wstring();
std::wstring path;
path.resize(MAX_PATH);
auto size = GetModuleFileName(handle, &path[0], MAX_PATH);
auto err = GetLastError();
if (size > 0)
path.resize(size);
return path;
}
std::wstring FindLoadedDll(boost::filesystem::path name, const boost::filesystem::path& parentPath)
{
if (name.extension().empty())
name.replace_extension(L".");
// when dll is loaded by an executable, loader will have the path to the folder it is in, and will pick up dll's dependencies from there (among other places)
// when loading dll's dependencies on its own, have to simulate that with PATH
std::wstring pathEnv;
wchar_t* buf = nullptr;
size_t size = 0;
if (_wdupenv_s(&buf, &size, L"PATH"))
{
if (buf)
pathEnv.assign(buf, size);
free(buf);
}
_wputenv((L"PATH=" + parentPath.wstring() + L";" + pathEnv).c_str());
auto handle = LoadLibraryEx(name.wstring().c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);
auto path = GetModuleFileName(handle);
FreeLibrary(handle);
_wputenv((L"PATH=" + pathEnv).c_str());
return path;
}
std::wstring FindDll(const boost::filesystem::path& name, const boost::filesystem::path& parentPath)
{
std::wstring path;
path.resize(MAX_PATH);
auto size = SearchPath(NULL, name.wstring().c_str(), NULL, MAX_PATH, &path[0], NULL);
path.resize(size);
return path;
}
PEBinaryPtr CollectDependencies(const boost::filesystem::path& path, PEBinaryMap& cache)
{
if (path.empty())
return PEBinaryPtr();
bool x64 = false;
if (!PEParser::IsPE(path.wstring(), x64))
return PEBinaryPtr();
#ifdef _WIN64
if (!x64)
return PEBinaryPtr();
#else
if (x64)
return PEBinaryPtr();
#endif
std::vector<std::string> imports, delayedImports;
{
PEParser pe(path.wstring());
pe.Open(false);
imports = pe.DllImports();
delayedImports = pe.DelayedDllImports();
}
ActivationContextHandler context(path.wstring(), true);
PEBinaryPtr peBinary(new PEBinary);
peBinary->path = path;
peBinary->resolved = true;
peBinary->manifestLoaded = context.IsActivated();
cache[boost::algorithm::to_lower_copy(path.wstring())] = peBinary;
auto processImports = [&](const std::vector<std::string>& imports, bool delayed)
{
for (auto& import : imports)
{
auto loadedPath = FindLoadedDll(import, path.parent_path());
ImportPtr dll(new Import);
dll->name = MultiByteToWideString(import);
dll->delayLoad = delayed;
peBinary->dependencies.push_back(dll);
auto knownDll = cache.find(boost::algorithm::to_lower_copy(loadedPath));
if (knownDll != cache.end())
dll->pe = knownDll->second;
else
dll->pe = CollectDependencies(loadedPath, cache);
if (!dll->delayLoad && (!dll->pe || !dll->pe->resolved))
peBinary->resolved = false;
}
};
processImports(imports, false);
processImports(delayedImports, true);
return peBinary;
}
void PrintDependencyTree(std::wostream& out, ImportPtr node, int depth, PrintedSet& cache, bool missingOnly)
{
if (!node)
return;
if (missingOnly && node->pe && node->pe->resolved)
return;
std::wstring offset;
if (depth > 0)
offset.resize(depth, L'\t');
out
<< offset
<< ((node->pe && node->pe->resolved) ? L"[ ]" : L"[!]")
<< ((node->delayLoad) ? L"[D]" : L"[ ]")
<< ((node->pe && node->pe->manifestLoaded) ? L"[M]" : L"[ ]")
<< L" "
<< node->name
<< L" -> "
<< (node->pe ? node->pe->path.wstring() : L"")
<< L"\n";
if (!node->pe)
return;
auto lowercasePath = boost::algorithm::to_lower_copy(node->pe->path.string());
if (cache.end() != cache.find(lowercasePath))
return;
cache.insert(lowercasePath);
for (auto it = node->pe->dependencies.begin(); it != node->pe->dependencies.end(); ++it)
PrintDependencyTree(out, *it, depth + 1, cache, missingOnly);
}
void PrintDependencyTree(std::wostream& out, const PEBinaryPtr& root, PrintedSet cache, bool missingOnly)
{
if (!root)
return;
if (missingOnly && root->resolved)
return;
out
<< (root->resolved ? L"[ ]" : L"[!]")
<< L"[ ]"
<< (root->manifestLoaded ? L"[M] " : L"[ ] ")
<< root->path.wstring()
<< L"\n";
for (auto& pe : root->dependencies)
PrintDependencyTree(out, pe, 1, cache, missingOnly);
}
std::string NormalizePath(const std::string& in)
{
return boost::replace_all_copy(in, "\\", "/");
}
std::string PrintDependencyTreeJson(const PEBinaryPtr& rootPE, const PEBinaryMap& binaries, bool missingOnly)
{
json::Object root;
json::Array binariesArray;
for (auto& pe : binaries)
{
if (!pe.second)
continue;
if (missingOnly && pe.second->resolved)
continue;
json::Object object;
object["id"] = NormalizePath(pe.second->path.string());
object["resolved"] = pe.second->resolved;
object["manifest"] = pe.second->manifestLoaded;
json::Array imports;
for (auto& import : pe.second->dependencies)
{
if (missingOnly && import->pe && import->pe->resolved)
continue;
json::Object object;
object["id"] = NormalizePath((import->pe) ? import->pe->path.string() : WideStringToMultiByte(import->name));
object["delayed"] = import->delayLoad;
object["name"] = WideStringToMultiByte(import->name);
imports.push_back(object);
};
object["imports"] = imports;
binariesArray.push_back(object);
};
root["binaries"] = binariesArray;
if (rootPE)
{
root["id"] = NormalizePath(rootPE->path.string());
root["resolved"] = rootPE->resolved;
root["type"] = "singlefile";
}
else
root["type"] = "cachedump";
return json::Serialize(root);
}
void LoadSystemPath()
{
HKEY key = NULL;
bool success = false;
std::wstring rawValue;
LSTATUS err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", 0, KEY_READ, &key);
if (err == ERROR_SUCCESS)
{
DWORD size = 0;
err = RegQueryValueEx(key, L"Path", 0, NULL, NULL, &size);
if (err == ERROR_SUCCESS)
{
rawValue.resize(size / sizeof(std::wstring::value_type), L'\0');
err = RegQueryValueEx(key, L"Path", 0, NULL, (BYTE*)&rawValue[0], &size);
if (err == ERROR_SUCCESS)
{
DWORD expandedSize = ExpandEnvironmentStrings(rawValue.c_str(), NULL, 0);
if (expandedSize != 0)
{
std::wstring expandedValue;
expandedValue.resize(expandedSize, L'\0');
expandedSize = ExpandEnvironmentStrings(rawValue.c_str(), &expandedValue[0], expandedSize);
if (expandedSize != 0)
{
rawValue.swap(expandedValue);
success = true;
}
}
}
}
RegCloseKey(key);
}
if (success && !rawValue.empty())
SetEnvironmentVariableW(L"Path", rawValue.c_str());
}
}