forked from Qualys/log4jscanwin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cpp
395 lines (353 loc) · 13.6 KB
/
Utils.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
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
#include "stdafx.h"
#include "Utils.h"
#include "minizip/unzip.h"
#include "minizip/iowin32.h"
#include "zlib/zlib.h"
constexpr wchar_t* qualys_program_data_locaton = L"%ProgramData%\\Qualys";
constexpr wchar_t* report_sig_output_file = L"log4j_findings.out";
constexpr wchar_t* report_sig_status_file = L"status.txt";
FILE* status_file = nullptr;
std::vector<std::wstring> error_array;
std::wstring A2W(const std::string& str) {
int length_wide = MultiByteToWideChar(CP_ACP, 0, str.data(), -1, NULL, 0);
wchar_t *string_wide = static_cast<wchar_t*>(_alloca((length_wide * sizeof(wchar_t)) + sizeof(wchar_t)));
MultiByteToWideChar(CP_ACP, 0, str.data(), -1, string_wide, length_wide);
std::wstring result(string_wide, length_wide - 1);
return result;
}
std::string W2A(const std::wstring& str) {
int length_ansi = WideCharToMultiByte(CP_ACP, 0, str.data(), -1, NULL, 0, NULL, NULL);
char* string_ansi = static_cast<char*>(_alloca(length_ansi + sizeof(char)));
WideCharToMultiByte(CP_ACP, 0, str.data(), -1, string_ansi, length_ansi, NULL, NULL);
std::string result(string_ansi, length_ansi - 1);
return result;
}
bool SanitizeContents(std::string& str) {
std::string::iterator iter = str.begin();
while (iter != str.end()) {
if (*iter == '\r') {
iter = str.erase(iter);
} else {
++iter;
}
}
return true;
}
bool StripWhitespace(std::string& str) {
while (1) {
if (str.length() == 0) break;
if (!isascii(str[0])) break;
if (!isspace(str[0])) break;
str.erase(0, 1);
}
int n = (int)str.length();
while (n > 0) {
if (!isascii(str[n - 1])) break;
if (!isspace(str[n - 1])) break;
n--;
}
str.erase(n, str.length() - n);
return true;
}
bool GetDictionaryValue(std::string& dict, std::string name,
std::string defaultValue, std::string& value) {
if (std::string::npos != dict.find(name.c_str(), 0)) {
size_t pos = dict.find(name.c_str(), 0);
size_t eol = dict.find("\n", pos);
value = dict.substr(pos + name.size(), eol - (pos + name.size()));
return true;
}
value = defaultValue;
return false;
}
bool ExpandEnvironmentVariables(const wchar_t* source, std::wstring& destination) {
try {
DWORD dwReserve = ExpandEnvironmentStrings(source, NULL, 0);
if (dwReserve == 0) {
return false;
}
destination.resize(dwReserve);
DWORD dwWritten = ExpandEnvironmentStrings(source, &destination[0],
(DWORD)destination.size());
if (dwWritten == 0) {
return false;
}
// dwWritten includes the null terminating character
destination.resize(dwWritten - 1);
} catch (std::bad_alloc&) {
return false;
}
return true;
}
bool DirectoryExists(const wchar_t* dirPath) {
if (dirPath == NULL) {
return false;
}
DWORD fileAttr = GetFileAttributes(dirPath);
return (fileAttr != INVALID_FILE_ATTRIBUTES &&
(fileAttr & FILE_ATTRIBUTE_DIRECTORY));
}
std::wstring GetScanUtilityDirectory() {
wchar_t path[MAX_PATH] = {0};
std::wstring utility_dir;
if (GetModuleFileName(NULL, path, _countof(path))) {
utility_dir = path;
std::wstring::size_type pos = std::wstring(utility_dir).find_last_of(L"\\");
utility_dir = utility_dir.substr(0, pos);
}
return utility_dir;
}
std::wstring GetReportDirectory() {
std::wstring destination_dir;
std::wstring report_dir;
if (ExpandEnvironmentVariables(qualys_program_data_locaton,
destination_dir)) {
if (!DirectoryExists(destination_dir.c_str())) {
_wmkdir(destination_dir.c_str());
}
report_dir = destination_dir;
}
if (report_dir.empty()) {
report_dir = GetScanUtilityDirectory();
}
return report_dir;
}
std::wstring GetSignatureReportFilename() {
return GetReportDirectory() + L"\\" + report_sig_output_file;
}
std::wstring GetSignatureStatusFilename() {
return GetReportDirectory() + L"\\" + report_sig_status_file;
}
int LogStatusMessage(const wchar_t* fmt, ...) {
int retval = 0;
va_list ap;
if (fmt == NULL) return 0;
va_start(ap, fmt);
retval = vfwprintf(stdout, fmt, ap);
va_end(ap);
if (status_file) {
va_start(ap, fmt);
retval = vfwprintf(status_file, fmt, ap);
va_end(ap);
fflush(status_file);
}
return retval;
}
bool OpenSignatureStatusFile() {
errno_t err = _wfopen_s(&status_file, GetSignatureStatusFilename().c_str(), L"w+");
return (EINVAL != err);
}
bool CloseSignatureStatusFile() {
if (status_file) {
fclose(status_file);
}
return true;
}
int DumpGenericException(const wchar_t* szExceptionDescription,
DWORD dwExceptionCode, PVOID pExceptionAddress) {
LogStatusMessage(
L"Unhandled Exception Detected - Reason: %s (0x%x) at address 0x%p\n\n",
szExceptionDescription, dwExceptionCode, pExceptionAddress);
return 0;
}
int DumpExceptionRecord(PEXCEPTION_POINTERS pExPtrs) {
PVOID pExceptionAddress = pExPtrs->ExceptionRecord->ExceptionAddress;
DWORD dwExceptionCode = pExPtrs->ExceptionRecord->ExceptionCode;
switch (dwExceptionCode) {
case 0xE06D7363:
DumpGenericException(L"Out Of Memory (C++ Exception)", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_ACCESS_VIOLATION:
wchar_t szStatus[256];
wchar_t szSubStatus[256];
wcscpy_s(szStatus, L"Access Violation");
wcscpy_s(szSubStatus, L"");
if (pExPtrs->ExceptionRecord->NumberParameters == 2) {
switch (pExPtrs->ExceptionRecord->ExceptionInformation[0]) {
case 0: // read attempt
swprintf_s(szSubStatus, L"read attempt to address 0x%p",
(void*)pExPtrs->ExceptionRecord->ExceptionInformation[1]);
break;
case 1: // write attempt
swprintf_s(szSubStatus, L"write attempt to address 0x%p",
(void*)pExPtrs->ExceptionRecord->ExceptionInformation[1]);
break;
}
}
LogStatusMessage(
L"Unhandled Exception Detected - Reason: %s(0x%x) at address 0x%p %s\n\n",
szStatus, dwExceptionCode, pExceptionAddress, szSubStatus);
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
DumpGenericException(L"Data Type Misalignment", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_BREAKPOINT:
DumpGenericException(L"Breakpoint Encountered", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_SINGLE_STEP:
DumpGenericException(L"Single Instruction Executed", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
DumpGenericException(L"Array Bounds Exceeded", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
DumpGenericException(L"Float Denormal Operand", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
DumpGenericException(L"Divide by Zero", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_INEXACT_RESULT:
DumpGenericException(L"Float Inexact Result", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_INVALID_OPERATION:
DumpGenericException(L"Float Invalid Operation", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_OVERFLOW:
DumpGenericException(L"Float Overflow", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_STACK_CHECK:
DumpGenericException(L"Float Stack Check", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_FLT_UNDERFLOW:
DumpGenericException(L"Float Underflow", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
DumpGenericException(L"Integer Divide by Zero", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_INT_OVERFLOW:
DumpGenericException(L"Integer Overflow", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_PRIV_INSTRUCTION:
DumpGenericException(L"Privileged Instruction", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_IN_PAGE_ERROR:
DumpGenericException(L"In Page Error", dwExceptionCode, pExceptionAddress);
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
DumpGenericException(L"Illegal Instruction", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
DumpGenericException(L"Noncontinuable Exception", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_STACK_OVERFLOW:
DumpGenericException(L"Stack Overflow", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_INVALID_DISPOSITION:
DumpGenericException(L"Invalid Disposition", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_GUARD_PAGE:
DumpGenericException(L"Guard Page Violation", dwExceptionCode,
pExceptionAddress);
break;
case EXCEPTION_INVALID_HANDLE:
DumpGenericException(L"Invalid Handle", dwExceptionCode,
pExceptionAddress);
break;
case CONTROL_C_EXIT:
DumpGenericException(L"Ctrl+C Exit", dwExceptionCode, pExceptionAddress);
break;
default:
DumpGenericException(L"Unknown exception", dwExceptionCode,
pExceptionAddress);
break;
}
return 0;
}
LONG CALLBACK CatchUnhandledExceptionFilter(PEXCEPTION_POINTERS pExPtrs) {
WCHAR szMiniDumpFileName[MAX_PATH];
HANDLE hDumpFile = NULL;
SYSTEMTIME sysTime;
SECURITY_ATTRIBUTES saMiniDumpSecurity;
LogStatusMessage(L"Run status : Failed\n");
// Attempt to dump an unhandled exception banner just in case things are
// so bad that a minidump cannot be created.
DumpExceptionRecord(pExPtrs);
// Create a directory to dump the minidump files into
SecureZeroMemory(&saMiniDumpSecurity, sizeof(saMiniDumpSecurity));
saMiniDumpSecurity.nLength = sizeof(saMiniDumpSecurity);
saMiniDumpSecurity.bInheritHandle = FALSE;
// Construct a valid minidump filename that will be unique.
// Use the '.mdmp' extension so it'll be recognize by the Windows debugging
// tools.
GetLocalTime(&sysTime);
swprintf_s(szMiniDumpFileName,
L"%s\\%0.2d%0.2d%0.4d%d%0.2d%0.2d%0.4d.mdmp",
GetScanUtilityDirectory().c_str(),
sysTime.wMonth,
sysTime.wDay,
sysTime.wYear,
sysTime.wHour,
sysTime.wMinute,
sysTime.wSecond,
sysTime.wMilliseconds);
LogStatusMessage(L"Creating minidump file %s with crash details.\n",
szMiniDumpFileName);
// Create the file to dump the minidump data into...
//
hDumpFile = CreateFile(szMiniDumpFileName, GENERIC_WRITE, NULL, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDumpFile != INVALID_HANDLE_VALUE) {
MINIDUMP_EXCEPTION_INFORMATION eiMinidumpInfo;
SecureZeroMemory(&eiMinidumpInfo, sizeof(eiMinidumpInfo));
eiMinidumpInfo.ThreadId = GetCurrentThreadId();
eiMinidumpInfo.ExceptionPointers = pExPtrs;
eiMinidumpInfo.ClientPointers = FALSE;
//
// Write the Mini Dump to disk
//
if (!MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), hDumpFile,
(MINIDUMP_TYPE)(MiniDumpNormal |
MiniDumpWithPrivateReadWriteMemory |
MiniDumpWithDataSegs | MiniDumpWithHandleData |
MiniDumpWithFullMemoryInfo |
MiniDumpWithThreadInfo |
MiniDumpWithUnloadedModules |
MiniDumpWithIndirectlyReferencedMemory),
&eiMinidumpInfo, NULL, NULL)) {
// Either the state of the process is beyond our ability to be able
// to scape together a usable dump file or we are on XP/2k3 and
// not all of the dump flags are supported. Retry using dump flags
// that are supported by XP.
//
if (!MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), hDumpFile,
(MINIDUMP_TYPE)(MiniDumpNormal |
MiniDumpWithPrivateReadWriteMemory |
MiniDumpWithDataSegs | MiniDumpWithHandleData),
&eiMinidumpInfo, NULL, NULL)) {
// Well out XP/2k3 compatible list of parameters didn't work, it
// doesn't look like we will be able to get anything useful.
//
// Close things down and delete the file if it exists.
//
SAFE_CLOSE_HANDLE(hDumpFile);
DeleteFile(szMiniDumpFileName);
LogStatusMessage(L"Failed to create minidump file %s.\n", szMiniDumpFileName);
}
}
SAFE_CLOSE_HANDLE(hDumpFile);
}
TerminateProcess(GetCurrentProcess(),
pExPtrs->ExceptionRecord->ExceptionCode);
return 0;
}