forked from ircop/nfq_filter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnfq.cpp
More file actions
867 lines (747 loc) · 23.1 KB
/
nfq.cpp
File metadata and controls
867 lines (747 loc) · 23.1 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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
#include "sender.h"
#include <getopt.h>
#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <linux/netfilter.h>
#include <unordered_map>
#include <mutex>
#include <pthread.h>
#include <time.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <libnetfilter_queue/libnetfilter_queue.h>
#include "parser.h"
#include "config.h"
#define NF_IP_PRE_ROUTING 0
#define NF_IP_LOCAL_IN 1
#define NF_IP_FORWARD 2
#define NF_IP_LOCAL_OUT 3
#define NF_IP_POST_ROUTING 4
#define iphdr(x) ((struct iphdr *)(x))
#define tcphdr(x) ((struct tcphdr *)(x))
#define PREROUTING 0
#define POSTROUTING 4
#define OUTPUT 3
#define BUFSIZE 4096
#define PROG_VER "0.11"
#define PROG_NAME "nfq_filter"
using namespace std;
typedef struct {
unsigned long size,resident,share,text,lib,data,dt;
} statm_t;
// prototypes:
void print_options(void); // print runtime options
void on_quit(void); // on normal exit callback function
void read_config( std::string file ); // reading config file
void read_domains(); // reading domains file
void read_urls(); // reading urls file
inline std::string trim( std::string& str );
void *tcap_packet_function( void *threadarh );
void *twrite_log_function( void *);
void *tread_conf_function( void *);
void writelog( const char *fmt, ... );
void writedebug( bool stamp, const char *fmt, ... );
short int netlink_loop(unsigned short int queuenum);
static int nfqueue_cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *data);
char *get_src_ip_str( char *payload );
char *get_dst_ip_str( char *payload );
int get_tcp_src_port(char *payload);
int get_tcp_dst_port(char *payload);
unsigned long djb2( unsigned char *str );
void read_mem( statm_t &result );
void getData( unsigned char* data, int size, char *result );
// global vars:
std::string domains_file = "/etc/nfq/domains";
std::string urls_file = "/etc/nfq/urls";
std::string logfilename = "/tmp/nfq_filter.log";
std::string redirect_url = "http://google.com";
std::string debug_from_ip = "";
std::string debug_ip_file = "";
std::string pidfile = "";
int debug_ip = 0;
std::unordered_map<std::string, int> domains;
std::unordered_map<unsigned long, std::string> urls;
std::mutex Mutex;
std::mutex MutexHandle;
std::mutex log_main;
std::mutex log_ip;
std::mutex log_debug;
long int filtered, captured;
char tmp[4096];
CSender *Sender;
FILE *f_log;
FILE *f_debug;
FILE *f_debug_ip;
int daemonized;
int debug = 1;
unsigned short int queuenum;
int buffer_size;
int queue_start;
int queue_end;
bool multiqueued;
int main( int argc, char * argv[] )
{
filtered = 0;
int ret = 0;
daemonized = 0;
std::string config_file("/etc/nfq_filter.cfg");
// check input params
if( argc < 2 ) {
print_options();
exit( -1 );
}
// check for root user
if( getuid() != 0 ) {
fprintf(stderr, "\n%s Version %s\n", PROG_NAME, PROG_VER);
fprintf(stderr, "This program should run as root only.\n");
exit(-1);
}
// register function to be called at normal program termination
ret = atexit(on_quit);
if( ret ) {
fprintf( stderr, "Cannot register exit function, terminating.\n");
exit(-1);
}
const struct option longopts[] =
{
{"config", 1, 0, 'c'},
{"version", 0, 0, 'v'},
{"help", 0, 0, 'h'},
{"daemonize", 0, 0, 'd'},
{0,0,0,0},
};
int index;
int iarg=0;
queuenum = 0;
while( iarg != -1 )
{
iarg = getopt_long(argc, argv, "c:vhd", longopts, &index);
switch(iarg) {
case 'c':
if( optarg ) {
config_file = string(optarg);
}
break;
case 'h':
print_options();
exit(-1);
case 'v':
fprintf(stderr, "%s ver. %s\n", PROG_NAME, PROG_VER);
exit(-1);
case 'd':
daemonized = 1;
break;
case '?':
fprintf(stderr, "\nInvalid option or missing parameter, use `nfq -h` for hepl.\n\n");
exit(-1);
}
}
read_config( config_file );
sprintf( tmp, "\n--------------------------\nStarting program.\n\nBuffer size:\t%i\nLog file:\t%s\nDebug:\t\t%i\n", buffer_size, logfilename.c_str(), debug ) ;
if( multiqueued )
sprintf( tmp, "%sMultiqueued:\ttrue\nQueues:\t\t%i-%i\n", tmp, queue_start, queue_end );
else
sprintf( tmp, "%sMultiqueued:\tfalse\nQueue:\t\t%i\n", tmp, queuenum );
f_log = fopen(logfilename.c_str(), "a");
f_debug = fopen("/tmp/nfq_debug.txt", "a");
if( f_log == NULL ) {
printf("%s\n", "Can't open logfile!\n");
exit(-1);
}
if( pidfile == "" ) {
printf("Can't read pid file from config!");
exit(-1);
}
// Debug single ip?
if( debug_from_ip != "" && debug_ip_file != "" ) {
debug_ip = 1;
f_debug_ip = fopen( debug_ip_file.c_str(), "a" );
if( f_debug_ip == NULL ) {
printf("%s\n", "Can't open debug single ip file!\n");
exit(-1);
}
setlinebuf(f_debug_ip);
fprintf( f_debug_ip, "%s", "Debug ip started...");
}
if( daemonized == 1 )
printf( "%s", tmp );
writelog( "%s", tmp );
// Initialization;
read_domains();
read_urls();
fprintf(stderr, "\nURLs and Domains files reading done.\n");
// Daemonizing ( if needed )
if( daemonized == 1 ) {
printf("%s", "Daemonizing...\n");
int pid = fork();
if( pid == -1 )
{
printf("Error: daemonizing failed! (%s)\n", strerror(errno));
return(-1);
} else if (!pid) {
// This is already child
printf("Daemonized.\n");
umask(0);
setsid();
chdir("/");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
} else {
// this is parent
return pid;
}
// Write own pidfile
FILE *fpid = fopen( pidfile.c_str(), "w+");
if( fpid ) {
fprintf(fpid, "%u", getpid());
fclose(fpid);
} else {
writelog("%s", "Can't open pidfile! Exiting.\n");
exit(-1);
}
}
Sender = new CSender( debug, redirect_url );
//////////////////////////////////////////
// without threads //
//////////////////////////////////////////
// netlink_loop( (unsigned short int) queuenum );
// exit(-1);
pthread_t twrite_log, tread_conf;
if( !multiqueued ) {
// Starting threads
pthread_t tcap_packet;
// Main thread
ret = pthread_create(&tcap_packet, NULL, tcap_packet_function, (void *) &queuenum);
if( ret ) {
printf("- ERROR(1): return code from pthread_create: %d\n", ret);
exit(-1);
}
} else {
/*
int thread_num = queue_end - queue_start + 1;
//pthread_t * workers = malloc( sizeof(pthread_t) * thread_num);
pthread_t workers[thread_num];
for( unsigned short int qnum = queue_start; qnum <= queue_end; qnum++ ) {
printf("QNUM: %i\n", qnum);
ret = pthread_create( &workers[qnum], NULL, tcap_packet_function, (void *) &qnum );
if( ret != 0 ) {
printf("- Error %d during pthread_create!\n", ret);
exit(-1);
}
}
*/
printf("%s\n", "Multi-queueing not works yet.");
exit(-1);
}
// Log statistics thread
ret = pthread_create(&twrite_log, NULL, twrite_log_function, (void *)NULL);
if( ret ) {
printf("- ERROR(2): return code from pthread_create: %d\n", ret);
exit(-1);
}
// Reread config files
ret = pthread_create( &tread_conf, NULL, tread_conf_function, (void *)NULL);
if( ret ) {
printf(" ERROR(3): return code from pthread_create: %d\n", ret);
exit(-1);
}
statm_t mem;
char buf[128];
while(1){
sleep(100);
read_mem(mem);
writelog( "Parent memory usage:\t%ld\n", mem.size );
}
// fclose( f_log );
// fclose( f_debug );
// if( debug_ip == 1 )
// fclose( f_debug_ip );
pthread_exit(NULL);
}
void read_config( std::string file )
{
Config *cfg = new Config ( file );
if( !cfg->getParam( "queue", queuenum ) )
queuenum = 0;
if( !cfg->getParam("logfile", logfilename) )
logfilename = "/tmp/nfq_filter.log";
if( !cfg->getParam("pidfile", pidfile) )
pidfile = "";
if( !cfg->getParam("debug", debug) )
debug = 1;
if( !cfg->getParam("domainlist", domains_file ) )
domains_file = "";
if( !cfg->getParam("urllist", urls_file) )
urls_file = "";
if( !cfg->getParam("redirect_url", redirect_url) )
redirect_url = "http://www.google.com";
if( !cfg->getParam("debug_from_ip", debug_from_ip) )
debug_from_ip = "";
if( !cfg->getParam("debug_ip_file", debug_ip_file) )
debug_ip_file = "";
if( !cfg->getParam("buffer_size", buffer_size) )
buffer_size = 8388608;
if( cfg->getQueues( queue_start, queue_end ) )
multiqueued = true;
else {
queue_start = 0;
queue_end = 0;
multiqueued = false;
}
return;
}
void read_domains()
{
// reading domain names file 'domains.txt'
ifstream dfile;
string dline;
dfile.open( domains_file );
if( !dfile )
{
fprintf(stderr, "\nCan not open domains.txt!\n");
return;
}
domains.clear();
while( !dfile.eof() ) {
getline(dfile, dline);
dline = trim(dline);
if( dline.length() > 3 ) {
domains[dline] = 1;
}
}
return;
}
void read_urls()
{
ifstream ufile;
string uline;
ufile.open( urls_file );
if( !ufile )
{
fprintf(stderr, "\nCan not open urls.txt!\n");
return;
}
urls.clear();
while( !ufile.eof() ) {
getline(ufile, uline);
uline = trim(uline);
unsigned long hash = djb2( (unsigned char *)uline.c_str() );
if( uline.length() > 3 ) {
urls[hash] = uline;
}
}
return;
}
void print_options(void)
{
printf("\n%s Version %s", PROG_NAME, PROG_VER);
printf("\n\nSyntax: nfq <-c config_file> [ -h ] [ -d ]\n\n");
printf(" -c\t\t- specify config file to read\n");
printf(" -h\t\t- displays this help and exit.\n");
printf(" -d\t\t- run this program as daemon\n\n");
}
void on_quit(void)
{
// printf("Program terminated.\n");
}
inline std::string trim( std::string& str )
{
str.erase( 0, str.find_first_not_of(' '));
str.erase( str.find_last_not_of(' ')+1);
return str;
}
void *tcap_packet_function( void *threadarg )
{
unsigned short int qnum = *((int* ) threadarg ) - 1;
// printf("Thread: sniffing packet started for queue_num %i\n", *(unsigned short int *) threadarg);
printf("Thread: sniffing packet started for queue_num %i\n", qnum );
netlink_loop(*(unsigned short int *) threadarg);
pthread_exit(NULL);
}
void *tread_conf_function( void *)
{
printf("Thread: read config files...started\n");
while( 1 ) {
sleep(1800); // 30 mins.
writelog("%s", " - Re-reading domains and urls files...\n");
MutexHandle.lock();
Mutex.lock();
read_domains();
read_urls();
Mutex.unlock();
MutexHandle.unlock();
}
pthread_exit(NULL);
}
void *twrite_log_function( void *)
{
printf("Thread: write log file...started\n");
statm_t mem;
char buf[128];
while(1){
// writedebug(true, "%s", " twrite_log_function... ");
sleep(120);
read_mem(mem);
// writelog( "\n--- stats ---\nFiltered: %lu\nCaptured: %lu\nMemory: %ld\nDomains size: %i\nURLs size: %i\n", filtered, captured, mem.size, domains.size(), urls.size() );
// writedebug(false, "%s", "done! sleep... ");
}
pthread_exit(NULL);
}
void writelog( const char *fmt, ... ) {
if( f_log == NULL ) {
printf("Log file is not opened! Exiting.\n");
exit(-1);
}
time_t now = time(0);
struct tm tstruct;
char b[80];
tstruct = *localtime(&now);
strftime(b, sizeof(b), "%d.%m.%Y %X", &tstruct );
// mutex for main log
log_main.lock();
fprintf( f_log, "%s:\t", b ); // datetime
va_list arg;
va_start( arg, fmt );
vfprintf( f_log, fmt, arg );
va_end(arg);
if( daemonized == 0 ) {
va_start( arg, fmt );
printf( "%s:", b );
vprintf( fmt, arg );
va_end(arg);
}
fflush( f_log );
// free mutex
log_main.unlock();
}
void writedebug( bool stamp, const char *fmt, ... ) {
if( f_debug == NULL ) {
printf("Debug file is not opened! Exiting.\n");
exit(-1);
}
time_t now = time(0);
struct tm tstruct;
char b[80];
tstruct = *localtime(&now);
strftime(b, sizeof(b), "%d.%m.%Y %X", &tstruct );
log_debug.lock();
if( stamp )
fprintf( f_debug, "\n%s:\t", b ); // datetime
va_list arg;
va_start( arg, fmt );
vfprintf( f_debug, fmt, arg );
va_end(arg);
if( daemonized == 0 ) {
va_start( arg, fmt );
printf( "%s:", b );
vprintf( fmt, arg );
va_end(arg);
}
fflush( f_debug );
log_debug.unlock();
}
short int netlink_loop(unsigned short int queuenum)
{
struct nfq_handle *h;
struct nfq_q_handle *qh;
struct nfnl_handle *nh;
int fd,rv;
char buf[BUFSIZE];
// open library handle
h = nfq_open();
if( !h ) {
printf("Error during nfq_open()\n");
exit(-1);
}
// unbind all existing nfq handlers for AF_INET
if( nfq_unbind_pf(h, AF_INET) < 0 ) {
printf("Error during nfq_unbind_pf()\n");
exit(-1);
}
// bind queue connection handle to process packets
if( nfq_bind_pf( h, AF_INET ) < 0 ) {
printf("Error during nfq_bind_pf()\n");
exit(-1);
}
printf("NFQ: Binding to queue '%hd'\n", queuenum);
// create queue
qh = nfq_create_queue(h, queuenum, &nfqueue_cb, NULL);
if( !qh ) {
printf("Error during nfq_create_queue()\n");
exit(-1);
}
// set buffer size
//set the amount of data to copy to userspace for each packet in queue
if( nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0 ) {
printf("Can't set packet copy mode ( nfq_set_mode() )\n");
exit(-1);
}
// returns netlink handle associated to given queue handle.
nh = nfq_nfnlh(h);
// returns file descriptor for the netlink connection associated with the given queue connection handle.
// Can be used for receiving the queue packets for processing.
fd = nfnl_fd(nh);
// while( ( rv = recv(fd, buf, sizeof(buf), 0) ) && rv >= 0 ) {
for( ;; ) {
if( (rv = recv(fd, buf, sizeof(buf), 0) ) >= 0 ) {
// triggers an associated callback function for the given packet received from the queue.
// Packets can be read from the queue using nfq_fd() and recv().
MutexHandle.lock();
nfq_handle_packet(h, buf, rv);
MutexHandle.unlock();
continue;
} else if( rv == -1 ) {
// some error
switch( errno ) {
case EAGAIN:
perror("ERROR: EAGAIN"); writelog("%s", "ERROR: EAGAIN"); break;
case EBADF:
perror("ERROR: EBADF: Bad file descriptor!"); writelog("ERROR: EBADF: Bad file descriptor! %s\n", strerror(errno) ); break;
case ECONNRESET:
perror("ERROR: ECONNRESET: NFQ Socket connection reset!"); writelog("ERROR: ECONNRESET: NFQ Socket connection reset! %s\n", strerror(errno) ); break;
case ETIMEDOUT:
perror("ERROR: ETIMEDOUT: NFQ Socket connection timeout!"); writelog("ERROR: ETIMEDOUT: NFQ Socket connection timeout! %s\n", strerror(errno) ); break;
case ENOBUFS:
perror("ERROR: ENOBUFS: app is not fast enough. Increase socket buffer size by nfnl_rcvbufsiz(): ");
writelog("%s\n", "ERROR: ENOBUFS: App is not fast enough, increase socket buffer size by nfnl_rcvbufsiz()\n" );
break;
default:
perror("Unknown error code!");
writelog("Unknown error code: %d: %s\n", errno, strerror(errno) );
break;
}
}
}
// unbind before exit
printf("NFQUEUE: unbinding from queue '%hd'\n", queuenum);
nfq_destroy_queue(qh);
nfq_close(h);
return(0);
}
static int nfqueue_cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *data)
{
struct nfqnl_msg_packet_hdr *ph;
ph = nfq_get_msg_packet_hdr(nfa);
// writedebug(true, "%s", "Next queue: ");
// Process packet only if it's prerouting:
if( ph && ph->hook == NF_IP_PRE_ROUTING ) {
// captured++;
// writedebug(false, "%s", "captured++; ");
// processing packet
int id=0;
int size=0;
char *full_packet; // packet data
unsigned char *data;
int len=0;
// writedebug(false, "%s", " | 1 | ");
id = ntohl( ph->packet_id );
size = nfq_get_payload(nfa, (unsigned char **)&full_packet);
len = nfq_get_payload(nfa, &data);
int id_protocol = full_packet[9]; // identify ip protocol
// writedebug(false, "%s", " | 2 | ");
int iphlen = iphdr(data)->ihl*4;
int tcphlen = tcphdr(data+iphlen)->doff*4;
int hlen = iphlen + tcphlen;
int ofs = iphlen + sizeof(struct tcphdr);
// writedebug(false, "%s", " | 3 | ");
if( len == hlen ) {
// writedebug(false, "%s", " | 3-1 | ");
Mutex.lock();
nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
Mutex.unlock();
// writedebug(false, "%s", " | 3-2 | ");
return(0);
}
// writedebug(false, "%s", " | 4 | ");
// Process only TCP proto:
if( id_protocol == IPPROTO_TCP ) {
// writedebug(false, "%s", "IPPROTO_TCP; ");
char src_ip[32], dst_ip[32];
strcpy( src_ip, get_src_ip_str(full_packet) );
strcpy( dst_ip, get_dst_ip_str(full_packet) );
// parce tcp header:
struct tcphdr* tcph;
char *pkt_data_ptr = NULL;
pkt_data_ptr = full_packet + sizeof(struct ip);
tcph = (struct tcphdr *) pkt_data_ptr;
char hdr[120];
sprintf(hdr, "%c%c%c%c%c%c Seq: 0x%x Ack: 0x%x Win: 0x%x TcpLen: %d\n",
(tcph->urg ? 'U' : '*'),(tcph->ack ? 'A' : '*'),(tcph->psh ? 'P' : '*'),
(tcph->rst ? 'R' : '*'),(tcph->syn ? 'S' : '*'),(tcph->fin ? 'F' : '*'),
ntohl(tcph->seq), ntohl(tcph->ack_seq),
ntohs(tcph->window), 4*tcph->doff);
char result[4096] = {0};
getData( (unsigned char*)full_packet + sizeof(struct ip) + (4*tcph->doff), size - (tcph->doff*4) - sizeof(struct ip), result );
std::string res = result;
http_request r;
// writedebug(false, "%s", "parse_http(); ");
if( !parse_http( res, &r ) ) {
if( debug_ip == 1 && debug_from_ip == src_ip ) {
fprintf( f_debug_ip, " - Packet captured: %s:%d -> %s:%d :: Header: %s", src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr );
fprintf( f_debug_ip, "%s\nFull packet:\n%s", "parse_http() failed.", res.c_str() );
}
// writedebug(false, "%s", "!parse_http(); ");
Mutex.lock();
nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
Mutex.unlock();
// writedebug(false, "%s", "set_verdict; return; ");
return(0);
} else {
// fprintf( f_debug_ip, "%s", " - PARSED HTTP - \n");
string host = r.host;
string url = r.full_url;
string method = r.method;
string full_url = r.full_url;
// writedebug(false, "%s", "Mutex.lock(); ");
Mutex.lock();
// Check in domain list
if( domains.find( host ) != domains.end() ) {
Mutex.unlock();
// writedebug(false, "%s", "domain found; ");
if( debug > 0 )
writelog(" - Packet filtered by DOMAIN: %s (%s) :: %s:%d -> %s:%d :: Header: %s", host.c_str(), full_url.c_str(), src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr );
if( debug == 2 || debug == 4 )
writelog("Full packet:\n%s", res.c_str() );
if( debug_ip == 1 && debug_from_ip == src_ip ) {
fprintf( f_debug_ip, " - Packet filtered by DOMAIN: %s (%s) :: %s:%d -> %s:%d :: Header: %s", host.c_str(), full_url.c_str(), src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr );
fprintf( f_debug_ip, "Full packet:\n%s", res.c_str() );
}
Sender->Redirect( get_tcp_src_port(full_packet), get_tcp_dst_port(full_packet),
/*user ip*/src_ip, dst_ip,
/*acknum*/ tcph->ack_seq, /*seqnum*/ tcph->seq,
/* flag psh */ (tcph->psh ? 1 : 0 ) );
// filtered++;
Mutex.lock();
nfq_set_verdict(qh, id, NF_DROP, 0, NULL);
Mutex.unlock();
return(0);
} else {
// writedebug(false, "%s", "domain !found; ");
// Get hash of this url
unsigned long url_hash = djb2( (unsigned char*)full_url.c_str() );
if( urls.find( url_hash ) != urls.end() ) {
// writedebug(false, "%s", "url found; ");
Mutex.unlock();
if( debug > 0 )
writelog(" - Packet filtered by URL: %s :: %s:%d -> %s:%d :: Header: %s", full_url.c_str(), src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr );
if( debug == 2 || debug == 4 )
writelog("Full packet:\n%s", res.c_str() );
if( debug_ip == 1 && debug_from_ip == src_ip ) {
fprintf(f_debug_ip, " - Packet filtered by URL: %s :: %s:%d -> %s:%d :: Header: %s", full_url.c_str(), src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr );
fprintf(f_debug_ip, "Full packet:\n%s", res.c_str() );
}
Sender->Redirect( get_tcp_src_port(full_packet), get_tcp_dst_port(full_packet),
src_ip, dst_ip, tcph->ack_seq, tcph->seq,
(tcph->psh ? 1 : 0 ) );
// filtered++;
Mutex.lock();
nfq_set_verdict( qh, id, NF_DROP, 0, NULL);
Mutex.unlock();
return(0);
}
Mutex.unlock();
// writedebug(false, "%s", "Mutex.unlock(); ");
}
if( debug_ip == 1 && debug_from_ip == src_ip ) {
fprintf(f_debug_ip, "Packet NOT filtered: %s:%d -> %s:%d,\tHeader: %sHost: %s :: URL: %s\nFull packet:\n%s", src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr, host.c_str(), full_url.c_str(), res.c_str() );
}
// HTTP parsed, but packet not filtered:
if( debug == 3 || debug == 4 )
writelog("Packet NOT filtered: %s:%d -> %s:%d,\tHeader: %s\nHost: %s :: URL: %s\n", src_ip, get_tcp_src_port(full_packet), dst_ip, get_tcp_dst_port(full_packet), hdr, host.c_str(), full_url.c_str() );
if( debug == 4 )
writelog("Full packet:\n%s", res.c_str() );
// writedebug(false, "%s", "Packet NOT filtered. ");
}
}
// writedebug(false, "%s", "Packet released. set_verdict&return; \n");
// let the packet continue. NF_ACCEPT will pass the packet.
Mutex.lock();
nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
Mutex.unlock();
return(0);
} else {
printf("NFQUEUE: can't get msg packet header.\n");
return(1); // 0=ok, 0+ = soft err, 0- = hard err
}
Mutex.lock();
nfq_set_verdict(qh, ntohl( ph->packet_id ), NF_ACCEPT, 0, NULL);
Mutex.unlock();
return(0);
}
char *get_src_ip_str( char *payload )
{
struct ip *iph = (struct ip *) payload;
// printf("SOURCE_IP: %s\n", inet_ntoa(iph->ip_src));
return(inet_ntoa(iph->ip_src));
}
char *get_dst_ip_str( char *payload )
{
struct ip *iph = (struct ip *) payload;
// printf("DST_IP: %s\n", inet_ntoa(iph->ip_dst));
return(inet_ntoa(iph->ip_dst));
}
int get_tcp_src_port(char *payload) {
char *pkt_data_ptr = NULL;
pkt_data_ptr = payload + sizeof(struct ip);
struct tcphdr *tcph = (struct tcphdr *) pkt_data_ptr;
return( ntohs(tcph->source) );
}
int get_tcp_dst_port(char *payload) {
char *pkt_data_ptr = NULL;
pkt_data_ptr = payload + sizeof(struct ip);
struct tcphdr *tcph = (struct tcphdr *) pkt_data_ptr;
return(ntohs(tcph->dest));
}
void getData( unsigned char* data, int size, char *result )
{
for (u_int i=0; (i < size) ; i++)
{
sprintf( result, "%s%c", result, data[i]) ;
}
return;
}
// hashing
unsigned long djb2( unsigned char *str )
{
unsigned long hash = 5381;
int c;
while( c = *str++ )
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
void read_mem(statm_t &result )
{
/*
unsigned long dummy;
const char* statm_path = "/proc/self/statm";
FILE *f = fopen( statm_path, "r" );
if( !f ) {
writelog( "%s", (char *)"Cant open /proc/self/statm!\n");
exit(-1);
}
if( 7 != fscanf(f,"%ld %ld %ld %ld %ld %ld %ld", &result.size,&result.resident,&result.share,&result.text,&result.lib,&result.data,&result.dt))
{
writelog("%s\n", "ERROR! Can't read mem!");
perror(statm_path);
return;
}
writelog("\n---meminfo---\n%ld %ld %ld", result.size, result.share, result.data);
fclose(f);
*/
}