-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.c
620 lines (531 loc) · 18.3 KB
/
project.c
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
* proxy server that detects malware.
*
*/
#include <arpa/inet.h>
#include <clamav.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <zlib.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <netinet/in.h>
#define PROXY_PORT 8080
#define QUEUE_SIZE 15
#define BUF_SIZE 1024
#define CHUNK_SIZE 65536
// defines the structure to pass parameters between the parent thread and child
// thread. feel free to extend this struct as required.
typedef struct {
int socket_id;
struct cl_engine* cl_engine;
} thread_params_t;
// forward declarations for functions
void* proxy_thread(void*);
int scan(char *inputFile, struct cl_engine* engine);
int decompress(char *inputFile, char *outputFile);
char* getLine(int ws);
int filesize (char* filename);
void merge_files(char* file1, char* file2);
// executive entrypoint
int main(int argc, char** argv) {
// init libclamav
if (cl_init(CL_INIT_DEFAULT) != CL_SUCCESS) {
printf("could not init clamAV.\n");
return 1;
}
// load virus db and compile the av engine
struct cl_engine* engine = cl_engine_new();
const char* db_dir = cl_retdbdir();
unsigned int signature_count = 0;
printf("loading from database at %s\n", db_dir);
if (cl_load(db_dir, engine, &signature_count, CL_DB_STDOPT) != CL_SUCCESS ||
cl_engine_compile(engine) != CL_SUCCESS) {
printf("failed to load db/compile AV engine.\n");
return 1;
}
printf("%d virus signatures loaded.\n", signature_count);
// create a socket to listen on
int s = socket(AF_INET, SOCK_STREAM, 0);
if (s == -1) {
printf("could not create socket. reason: %s\n", strerror(errno));
return 1;
}
// setup socket options such that the port can be reused quickly after
// program termination
struct sockaddr_in local_sockaddr;
local_sockaddr.sin_family = AF_INET;
local_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
local_sockaddr.sin_port = htons(PROXY_PORT);
int one = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
printf("could not set socket options. reason: %s\n", strerror(errno));
return 1;
}
// bind socket to the sockaddr_in structure
if (bind(s, (struct sockaddr*) &local_sockaddr,
sizeof(local_sockaddr)) == -1) {
printf("could not bind to socket. reason: %s\n", strerror(errno));
return 1;
}
// set socket to listening mode
if (listen(s, QUEUE_SIZE) == -1) {
printf("could not listen on socket. reason: %s\n", strerror(errno));
}
while (1) {
// wait for a TCP connection. the accept() function will block until the
// TCP handshake is complete.
struct sockaddr_in remote_sockaddr;
socklen_t address_len = sizeof(remote_sockaddr);
int client; // client socket
client = accept(s, (struct sockaddr*) &remote_sockaddr, &address_len);
if (client == -1) continue;
// setup thread parameters
pthread_t tid;
thread_params_t* params = (thread_params_t*)
malloc(sizeof(thread_params_t));
if (params == NULL) {
printf("error allocating memory.\n");
return 1;
}
params->socket_id = client;
params->cl_engine = engine;
// create the thread and pass the parameters over
if (pthread_create(&tid, NULL, proxy_thread, params) != 0) {
printf("error creating thread.\n");
return 1;
}
}
// free up scan engine (do this once you no longer need to scan files)
cl_engine_free(engine);
return 0;
}
// thread entrypoint for code to handle a single proxy connection
void* proxy_thread(void* args) {
// cast parameters back to native data type, copy the params and free up mem
thread_params_t* params = (thread_params_t*) args;
int socket_id = params->socket_id;
struct cl_engine* cl_engine = params->cl_engine;
free(params);
args = NULL;
params = NULL;
printf("connection accepted on socket %d.\n", socket_id);
// detach the thread so the parent doesn't have to wait on it
pthread_detach(pthread_self());
// this sample code simply reads out what was received on the socket.
// when you start the proxy and run firefox, you'll see the HTTP request
// printed on screen.
//
// note that because the proxy is multithreaded, you may see an interleaving
// of printf() outputs from different threads.
char buf[BUF_SIZE];
int bytes_received;
while ((bytes_received = recv(socket_id, buf, sizeof(buf)-1, 0)) > 0) {
buf[bytes_received] = 0;
printf("--- RECEVIED FROM CLIENT: --- \n%s\n", buf);
// ------------------------------------ //
// --- PARSE FILE NAME FROM REQUEST --- //
// ------------------------------------ //
char* hostname;
char get_request[5] = "GET";
char post_request[5] = "POST";
char host_position[5] = "Host:";
char* tokens;
char* rest = buf;
// Ensure is GET or POST
if (strncmp(buf, get_request, 3) != 0 && strncmp(buf, post_request, 4) != 0) {
printf("ERROR: Neither a GET nor POST request");
break;
}
char buf_copy[BUF_SIZE];
memcpy(buf_copy, buf, sizeof(buf));
// If encrypted, tokens will hold the full url
tokens = strtok_r(buf, " ", &rest);
tokens = strtok_r(NULL, " ", &rest);
if (strncmp(tokens, "http", 4) == 0) {
tokens = strtok_r(tokens, "//", &rest); //do we need to add this to non encrypted too?
tokens = strtok_r(NULL, "/", &rest);
hostname = tokens;
} else {
printf("ERROR: GET/POST request in nonstandard format");
break;
}
// If not encrypted, get hostname
if (hostname == NULL) {
do {
if (strncmp(tokens, host_position, 5) == 0) {
hostname = strtok_r(NULL, " ", &rest);
printf("%s\n", hostname);
break;
}
tokens = strtok_r(NULL, " ", &rest);
} while (tokens != NULL);
}
// ------------------------------ //
// --- CONNECT TO HOST SOCKET --- //
// ------------------------------ //
struct hostent* he;
struct sockaddr_in server;
/* resolve hostname */
if ((he = gethostbyname((const char*)hostname) ) == NULL ) {
printf("hostname null"); /* error */
}
/* copy the network address to sockaddr_in structure */
memcpy(&server.sin_addr, he->h_addr_list[0], he->h_length);
server.sin_family = AF_INET;
server.sin_port = htons(80);
int ws = socket(AF_INET, SOCK_STREAM, 0); //ws = web socket
if (ws == -1) {
printf("could not create web socket. reason: %s\n", strerror(errno));
break;
}
//connect to web socket
if ( connect(ws, (struct sockaddr *)&server, sizeof(server) ) < 0) {
printf("could not connect to host socket. reason: %s\n", strerror(errno));
break;
}
printf("successfully connected to host on socket %d\n", ws);
// ---------------------------- //
// --- SEND REQUEST TO HOST --- //
// ---------------------------- //
int bytes_sent = 0;
if ((bytes_sent = send(ws, buf_copy, strlen(buf_copy), 0)) < 0) {
printf("could not send to web socket. reason: %s\n", strerror(errno));
break;
}
// -------------------------------------------- //
// --- SET UP FILE SYSTEM FOR HOST RESPONSE --- //
// -------------------------------------------- //
char file_name[] = "temp_XXXXXX";
FILE* web_data;
mkdtemp(file_name);
if (file_name == NULL){
printf("error creating temp directory");
}
//because C hates string concatenation
char* raw_filename = malloc(strlen(file_name)+6);
strcpy(raw_filename, file_name);
strcat(raw_filename, "/data");
char* unzip_filename = malloc(strlen(file_name)+12);
strcpy(unzip_filename, file_name);
strcat(unzip_filename, "/unzip_data");
char* zip_filename = malloc(strlen(file_name)+10);
strcpy(zip_filename, file_name);
strcat(zip_filename, "/zip_data");
web_data = fopen(raw_filename, "wb+");
fclose(web_data);
web_data = fopen(unzip_filename, "wb+");
fclose(web_data);
web_data = fopen(zip_filename, "wb+");
fclose(web_data);
// ------------------------------------------ //
// ------- RECEIVE RESPONSE FROM HOST ------- //
// --- HANDLES CHUNKED AND G-ZIPPED FILES --- //
// ------------------------------------------ //
char* line;
int chunk_size = 0;
int chunk_bytes_rec = 0;
int chunked = 0;
int decomp = 0;
long length = 0;
char* con_len;
//reads through header if chunked, otherwise reads everything
while ((line = getLine(ws)) != NULL) {
web_data = fopen(raw_filename, "ab");
fwrite(line, sizeof(char), strlen(line), web_data);
fclose(web_data);
printf("%s", line);
if (strcasecmp(line, "transfer-encoding: chunked\r\n") == 0) {
chunked = 1;
}
if (strcasecmp(line, "transfer-encoding: chunked, gzip\r\n") == 0){
chunked = 1;
decomp = 1;
}
if (strcasecmp(line, "transfer-encoding: gzip, chunked\r\n") == 0){
chunked = 1;
decomp = 1;
}
if (strncasecmp(line, "Content-Encoding: gzip", 22) == 0) {
decomp = 1;
}
if (strncasecmp(line, "Content-Length:", 15) == 0) {
char* tokens;
tokens = strtok_r(line, ": ", &con_len);
tokens = strtok_r(NULL, ": ", &con_len);
length = strtol(tokens, &con_len, 10);
}
if (!strcmp(line, "\r\n")) {
break;
}
free(line);
}
// PROCESS CHUNKED DATA
while (chunked == 1) { //set chunked from header parsing
line = getLine(ws); //line with chunk size, don't want to write that to file
if (line == NULL) {
break;
}
chunk_size = strtol(line, NULL, 16);
if (chunk_size > 0) {
char* chunk_buf = malloc(chunk_size);
bzero(chunk_buf, chunk_size);
if ((chunk_bytes_rec = recv(ws, chunk_buf, chunk_size, 0)) > 0) {
if (decomp == 1){
web_data = fopen(zip_filename, "ab");
}
else {
web_data = fopen(raw_filename, "ab");
}
fwrite(chunk_buf, sizeof(char), chunk_bytes_rec, web_data);
fclose(web_data);
}
}
else if (chunk_size == 0) { //last chunk in msg
while ((line = getLine(ws)) != NULL) { //while lines left in msg
if (decomp == 1){
web_data = fopen(zip_filename, "ab");
}
else {
web_data = fopen(raw_filename, "ab");
}
fwrite(line, sizeof(char), strlen(line), web_data);
fclose(web_data);
}
}
else {
printf("error in chunking\n");
}
}
//PROCESS NON CHUNKED DATA
if (chunked == 0){
int size = (int) length; //replace iwth content length
char* chunk_buf = malloc(size+1);
bzero(chunk_buf, size);
int msg_bytes_rec = 0;
while (msg_bytes_rec < size) {
if ((chunk_bytes_rec = recv(ws, chunk_buf, size, 0)) > 0) {
if (decomp == 1){
web_data = fopen(zip_filename, "ab");
}
else {
web_data = fopen(raw_filename, "ab");
}
fwrite(chunk_buf, sizeof(char), chunk_bytes_rec, web_data);
fclose(web_data);
}
msg_bytes_rec += chunk_bytes_rec;
}
}
// ------------------------------- //
// --- DECOMPRESS IF NECESSARY --- //
// ------------------------------- //
if (decomp == 1) {
decompress(zip_filename, unzip_filename);
}
// ----------------- //
// --- SCAN FILE --- //
// ----------------- //
int clean = 0;
if (decomp == 1) {
clean = scan(unzip_filename, cl_engine);
}
else {
clean = scan(raw_filename, cl_engine);
}
// ---------------------- //
// --- SEND TO CLIENT --- //
// -----------------------//
if (clean == 0) {
if (decomp == 1) {
merge_files(raw_filename, zip_filename);
}
web_data = fopen(raw_filename, "rb+");
}
else {
web_data = fopen("malware_detected.html", "r");
}
int fd = fileno(web_data);
struct stat sb;
fstat(fd, &sb);
off_t offset = 0;
bytes_sent = sendfile(socket_id, fd, &offset, (int)sb.st_size);
fclose(web_data);
// ---------------------------- //
// --- CLEAN ALL THE THINGS --- //
// ---------------------------- //
remove((const char*)raw_filename);
remove((const char*)unzip_filename);
free(raw_filename);
free(unzip_filename);
rmdir(file_name);
close(ws);
close(socket_id);
}
// if control got here, the socket was closed or had an error. either way,
// execution cannot continue so close the socket and terminate the thread.
close(socket_id);
printf("connection closed on socket %d\n", socket_id);
return NULL;
}
/* Scans a file with clam AV
*
*/
int scan(char *inputFile, struct cl_engine* engine) {
// perform the scan. if you need to scan multiple files, you do not need to
// re-initialize/compile the scan engine. just keep calling cl_scanfile(),
// once for each new file you want to scan. the function should be
// thread safe.
const char* virus_name;
int scan_result;
long unsigned int scanned; // unimportant. its use in cl_scanfile can be
// replaced with NULL. see manual for
// documentation.
scan_result = cl_scanfile(inputFile, &virus_name, &scanned, engine,
CL_SCAN_STDOPT);
switch (scan_result) {
case CL_VIRUS:
printf("[X] found virus: [%s]\n", virus_name);
return 1;
case CL_CLEAN:
printf("[O] clean.\n");
break;
default: // should not get here
break;
}
// all done
return 0;
}
/* Decompresses a file
*
*/
int decompress(char *inputFile, char *outputFile) {
// prepare input file for reading
FILE* in_fp;
uint8_t in_buf[CHUNK_SIZE]; // read file 64kb at a time
if ((in_fp = fopen(inputFile, "r")) == NULL) {
printf("unable to open %s for reading\n", inputFile);
return 1;
}
// prepare output file for writing
FILE* out_fp;
uint8_t out_buf[CHUNK_SIZE]; // write file 64kb at a time
if ((out_fp = fopen(outputFile, "w")) == NULL) {
printf("unable to open %s for writing.\n", outputFile);
return 1;
}
// setup decompressor state and initialize the decompressor.
// you need to do this once (setup state + call inflateInit2()) for each file
// to be decompressed. after initializing the decompressor, it must be
// cleaned up via inflateEnd().
//
// read the documentation to find out more about the structure members.
// if you are lazy, just adapt this code for your project.
z_stream stream_info;
stream_info.zalloc = Z_NULL;
stream_info.zfree = Z_NULL;
stream_info.avail_in = 0;
stream_info.next_in = Z_NULL;
stream_info.next_out = Z_NULL;
stream_info.total_out = 0;
if (inflateInit2(&stream_info, 16+MAX_WBITS) != Z_OK) {
printf("error initializing decompressor.\n");
return 1;
}
// the outer loop reads out the file one chunk (ie 16kb) at a time
// and sends them to the decompressor.
int inflate_result;
int bytes_to_write;
do {
stream_info.avail_in = fread(in_buf, 1, sizeof(in_buf), in_fp);
stream_info.next_in = in_buf;
if (stream_info.avail_in == 0) break; // no more data to read so done
// the inner loop decompresses one chunk from the file. it may take
// several iterations to completely write out the compressed contents.
do {
stream_info.avail_out = sizeof(out_buf);
stream_info.next_out = out_buf;
// perform actual decompression. after decompressing, the contents are
// stored in out_buf. this is where it gets tricky -- zlib doesn't
// tell you how many bytes the decompressed data occupies. instead, it
// reuses the stream_info.avail_out to indicate how many bytes in the
// output buffer are still available post-decompression. a value of 0
// indicates that the entire output buffer was used, so more
// decompression of the input chunk is required. anything more than 0
// means that the complete output buffer wasn't required, implying that
// the current input chunk is all decompressed.
inflate_result = inflate(&stream_info, Z_SYNC_FLUSH);
if (inflate_result != Z_OK && inflate_result != Z_STREAM_END) {
printf("error decompressing file. zlib err: %d\n", inflate_result);
inflateEnd(&stream_info);
return 1;
}
// write decompressed data to file
bytes_to_write = sizeof(out_buf) - stream_info.avail_out;
if (fwrite(out_buf, 1, bytes_to_write, out_fp) != bytes_to_write) {
printf("error writing decompressed contents to file.\n");
inflateEnd(&stream_info);
return 1;
}
} while (stream_info.avail_out == 0); // avail_out == 0 means more to
// decompress for this chunk.
} while (inflate_result != Z_STREAM_END); // stream end means every chunk
// in the file has been
// decompressed.
// cleanup the decompressor after each file -- this is important!
inflateEnd(&stream_info);
// close up files
fclose(in_fp);
fclose(out_fp);
// all done
return 0;
}
char* getLine(int fd) {
char c = 0, p = 0;
char* line = 0;
int size = 1;
int pos = 0;
while(read(fd, &c, 1)!=0) {
if(pos + 1 == size) {
size *= 2;
line = realloc(line, size);
}
line[pos++] = c;
if(p == '\r' && c == '\n') break;//this is a new line
p = c;
}
if(line)
line[pos++] = 0;
return line;
}
int filesize (char* filename) {
FILE* web_data;
if ((web_data = fopen(filename, "rb")) == NULL) {
printf("couldnt open file %s in filesize.\n", filename);
return -1;
}
int fd = fileno(web_data);
struct stat sb;
fstat(fd, &sb);
printf("%s file size: %d\n", filename, (int)sb.st_size);
fclose(web_data);
return (int)sb.st_size;
}
void merge_files(char* file1, char* file2) {
int f2_size = filesize(file2); //zipped file
FILE* merged_file = fopen(file1, "ab"); //open header file for appending
FILE* zipped_file = fopen(file2, "rb+");
char* ptr = malloc(f2_size+1);
while (fread(ptr, sizeof(char), f2_size, zipped_file) > 0){
fwrite(ptr, sizeof(char), f2_size, merged_file);
}
fclose(zipped_file);
fclose(merged_file);
}