-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpacketbl.c
1870 lines (1608 loc) · 56.2 KB
/
packetbl.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
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2004 Russell Miller
Copyright 2017 Alvaro Cano <[email protected]>
Copyright 2019 Nicolas Gudino <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "packetbl.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <ctype.h>
#include <syslog.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
#include <errno.h>
#include <linux/netfilter.h>
#include <dotconf.h>
#include <libpool.h>
#include <pthread.h>
#include <stdarg.h>
#include <signal.h>
#include "directresolv.h"
#ifdef USE_SOCKSTAT
#include <sys/socket.h>
#include <sys/un.h>
#endif
#ifdef HAVE_FIREDNS
#include <firedns.h>
#endif
#ifndef BUFFERSIZE
#define BUFFERSIZE 65536
#endif
#ifdef USE_CACHE
# ifndef USE_CACHE_DEF_LEN
# define USE_CACHE_DEF_LEN 8192
# endif
# ifndef USE_CACHE_DEF_TTL
# define USE_CACHE_DEF_TTL 3600
# endif
#endif
# define TH_FIN 0x01
# define TH_SYN 0x02
# define TH_RST 0x04
# define TH_PUSH 0x08
# define TH_ACK 0x10
# define TH_URG 0x20
# include <libnetfilter_queue.h>
# define SET_VERDICT nfq_set_verdict
# define PBL_HANDLE nfq_q_handle
# define PBL_SET_MODE nfq_set_mode
# define PBL_COPY_PACKET NFQNL_COPY_PACKET
# define PBL_ID_T u_int32_t
# define PBL_ERRSTR ""
#define MAXBUF 4096
#define DEBUG(x, y) if (conf.debug >= x) { printf(y "\n"); }
#define LOGGING(x, de, string) if (conf.debug >= x) { printf(y "\n"); }
struct packet_info {
//~ unsigned short int b1;
uint8_t b1;
uint8_t b2;
uint8_t b3;
uint8_t b4;
int s_port;
int d_port;
int flags;
};
struct cidr {
uint32_t ip;
uint32_t network;
uint32_t processed; /* network, but as a bitmask */
};
struct config_entry {
char *string;
struct config_entry *next;
struct packet_info ip;
struct cidr cidr;
};
// parameters to create a thread
struct thr_arg
{
struct nfq_q_handle *queue_handle; // nf_queue id
struct packet_info ip;
int id;
};
struct thr_parameters
{
pthread_attr_t *thr_attr; // argument
pthread_t *thr; // parameters
};
struct config_entry *blacklistbl = NULL;
struct config_entry *whitelistbl = NULL;
struct config_entry *blacklist = NULL;
struct config_entry *whitelist = NULL;
// Execution parameters
// Only check configuration file
int arg_debug = 0;
int arg_quiet = 0;
char * packetbl_configfile = NULL;
char * packetbl_pidfile = NULL;
// to query to a alternative nameserver
struct bl_context {
int permissions;
const char *current_end_token;
pool_t *pool;
};
static pthread_mutex_t lock_queue;
static pthread_mutex_t lock_cache;
static pthread_mutex_t lock_count;
// thread counter
volatile int thread_count;
static double
cur_time(void)
{
return time(NULL) * 1000000.0;
}
enum permissions {
O_ROOT = 1,
O_HOSTSECTION = 2,
O_LAST = 4
};
static DOTCONF_CB(host_section_open);
static DOTCONF_CB(common_section_close);
static DOTCONF_CB(common_option);
static DOTCONF_CB(toggle_option);
static DOTCONF_CB(facility_option);
static const char *end_host = "</host>";
char msgbuf[BUFFERSIZE];
struct config {
int allow_non25;
int allow_nonsyn;
int default_accept;
int dryrun;
int log_facility;
int log_level;
int queueno;
int quiet;
int debug;
int queue_size;
int threads_max;
};
static struct config conf = { 0, 0, 1, 0, LOG_DAEMON, 5, 0, 1, 0, 0, 0};
struct pbl_stat_info {
uint32_t cacheaccept;
uint32_t cachereject;
uint32_t whitelistblhits;
uint32_t blacklistblhits;
uint32_t whitelisthits;
uint32_t blacklisthits;
uint32_t fallthroughhits;
uint32_t totalpackets;
};
static struct pbl_stat_info statistics = { 0, 0, 0, 0, 0, 0, 0, 0 };
#ifdef USE_CACHE
struct packet_cache_t {
uint32_t ipaddr;
time_t expires;
int action;
};
volatile struct packet_cache_t *packet_cache = NULL;
uint32_t packet_cache_len = USE_CACHE_DEF_LEN;
uint16_t packet_cache_ttl = USE_CACHE_DEF_TTL;
#endif
struct config_entry *hostlistcache = NULL;
void logmsg(const int priority, const int debug, const char *fmt, ...);
#if NETFILTERQUEUE_VERSION_NUMBER == 0
int get_packet_info(char *payload, struct packet_info *ip);
#else
int get_packet_info(unsigned char *payload, struct packet_info *ip);
#endif
int check_packet_list(const struct packet_info *ip, struct config_entry *list);
int check_packet_dnsbl(const struct packet_info *ip, struct config_entry *list);
int parse_cidr(struct config_entry *ce);
/* int validate_blacklist(char *); */
void parse_config( void );
void print_help ( void );
void parse_arguments(int argc, char **argv);
void pbl_init_sockstat(void);
static void get_ip_string(const struct packet_info *ip);
static void pbl_set_verdict(struct PBL_HANDLE *h, PBL_ID_T id, unsigned int verdict);
static int callback_threads(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *thread_hd);
void pbl_callback(void *data);
static const configoption_t options[] = {
{"<host>", ARG_NONE, host_section_open, NULL, O_ROOT},
{"</host>", ARG_NONE, common_section_close, NULL, O_ROOT},
{"blacklistbl", ARG_STR, common_option, NULL, O_HOSTSECTION},
{"whitelistbl", ARG_STR, common_option, NULL, O_HOSTSECTION},
{"whitelist", ARG_STR, common_option, NULL, O_HOSTSECTION},
{"blacklist", ARG_STR, common_option, NULL, O_HOSTSECTION},
{"fallthroughaccept", ARG_TOGGLE, toggle_option, NULL, O_ROOT},
{"allownonport25", ARG_TOGGLE, toggle_option, NULL, O_ROOT},
{"allownonsyn", ARG_TOGGLE, toggle_option, NULL, O_ROOT},
{"dryrun", ARG_TOGGLE, toggle_option, NULL, O_ROOT},
{"quiet", ARG_TOGGLE, toggle_option, NULL, O_ROOT},
#ifdef USE_CACHE
{"cachettl", ARG_INT, toggle_option, NULL, O_ROOT},
{"cachesize", ARG_INT, toggle_option, NULL, O_ROOT},
#endif
{"logfacility", ARG_STR, facility_option, NULL, O_ROOT},
{"loglevel", ARG_INT, toggle_option, NULL, O_ROOT},
{"queueno", ARG_INT, toggle_option, NULL, O_ROOT},
{"queuesize", ARG_INT, toggle_option, NULL, O_ROOT},
{"threadmax", ARG_INT, toggle_option, NULL, O_ROOT},
LAST_OPTION
};
FUNC_ERRORHANDLER(error_handler) {
fprintf(stderr, "[error] %s\n", msg);
return 1;
}
void sig_term_handler(int signum, siginfo_t *info, void *ptr) {
logmsg(0, LOG_INFO, "Terminating %s",packetbl_pidfile);
unlink (packetbl_pidfile);
exit(EXIT_SUCCESS);
}
void catch_sigterm() {
static struct sigaction _sigact;
memset(&_sigact, 0, sizeof(_sigact));
_sigact.sa_sigaction = sig_term_handler;
_sigact.sa_flags = SA_SIGINFO;
sigaction(SIGTERM, &_sigact, NULL);
}
/*
* Log an error to the syslog or to stderr
*/
void logmsg(const int debug, const int priority, const char *fmt, ...) {
char buf[MAXBUF + 1];
va_list ap;
buf[MAXBUF] = '\0';
va_start(ap, fmt);
vsnprintf(buf, MAXBUF, fmt, ap);
va_end(ap);
if (debug >= 0) {
if(conf.debug > debug) {
printf("%s\n", buf);
}
}
if (conf.log_level >= priority) {
syslog(priority, "%s", buf);
}
}
/*
* SYNOPSIS:
* void daeomize(void);
*
* NOTES:
* This function accomplishes everything needed to become a daemon.
* Including closing standard in/out/err and forking.
* It returns nothing, on failure the program must abort.
*
*/
void daemonize(void) {
pid_t pid;
FILE *pidf;
chdir("/");
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
setsid();
pid = fork();
if (pid > 0) {
pidf = fopen ( packetbl_pidfile , "w");
if (!pidf) {
logmsg(0, LOG_ERR, "Can't write PID %d to %s", (int)pid, packetbl_pidfile);
} else {
fprintf(pidf, "%d\n", (int)pid);
fclose(pidf);
}
exit(EXIT_SUCCESS);
}
if (pid < 0) {
logmsg(0, LOG_ERR, "Fork failed while daemonizing: %s", strerror(errno));
exit(EXIT_FAILURE);
}
}
#ifdef USE_CACHE
/*
* SYNOPSIS:
* static uint32_t packet_cache_hash(
* const struct packet_info ip
* );
*
* ARGUMENTS:
* struct packet_info ip Structure containing information about the
* IP address to create the hash.
*
* RETURN VALUE:
* An integer representing the hash value is returned. This value *MAY BE*
* greater than the size of the hash table, so it should be checked before
* use.
*
* NOTES:
*
* CURRENT IMPLEMENTATION NOTES (do not rely on this for design):
* Currently, only the IP portion of the structure is used for computing the
* hash.
* The current implementation will never return a value greater than 21675
* so having a hash table larger than that would be wasteful.
*
*/
static uint32_t packet_cache_hash(const struct packet_info ip) {
uint32_t hash = 0;
hash = ip.b1 << 6;
hash += ip.b2 << 4;
hash += ip.b3 << 2;
hash += ip.b4;
return hash;
}
/*
* SYNOPSIS:
* void packet_cache_clear(void);
*
* ARGUMENTS:
* (none)
*
* RETURN VALUE:
* (none)
*
* NOTES:
* This function must succeed even if "packet_cache" is NULL.
* This function initializes the values inside the previously allocated
* "packet_cache" array to safe values so that we may check entries
* safely.
*
*/
void packet_cache_clear(void) {
uint32_t i;
if (packet_cache==NULL) return;
for (i=0; i<packet_cache_len; i++) {
packet_cache[i].ipaddr = 0;
packet_cache[i].action = NF_ACCEPT;
packet_cache[i].expires = 0;
}
return;
}
#endif
/*
* SYNOPSIS:
* static uint32_t packet_info_to_ip(
* const struct packet_info ip
* );
*
* ARGUMENTS:
* struct packet_info ip Structure containing IP fields to convert to
* a 32bit unsigned integer.
*
* RETURN VALUE:
* This function returns a 32bit unsigned integer that represents a
* "one-to-one" mapping of IP octets and integer addresses, it will not
* overlap, therefore.
*
* NOTES:
*
*/
static uint32_t packet_info_to_ip(const struct packet_info ip) {
return ((ip.b1 & 0xff) << 24) |
((ip.b2 & 0xff) << 16) |
((ip.b3 & 0xff) << 8) |
(ip.b4 & 0xff);
}
/*
* SYNOPSIS:
* int packet_check_ip(
* const struct packet_info ip
* );
*
* ARGUMENTS:
* struct packet_info ip Structure containing information about
* packet to check.
*
* RETURN VALUE:
* "packet_check_ip" returns an action to supply to "pbl_set_verdict".
* Currently, it will be one of NF_DROP or NF_ACCEPT but other values should
* be accounted for. The supplied information is checked against the
* configued DNS RBLs and Whitelists to determine the appropriate action.
*
* NOTES:
* This function may return stale entries due to caching.
* This function MUST continue to work if "packet_cache" is NULL.
*
*/
int packet_check_ip(const struct packet_info ip) {
int retval = NF_ACCEPT;
struct pbl_stat_info *statics_pointer = &statistics;
#ifdef USE_CACHE
uint32_t ipaddr_check;
uint32_t cache_hash = 0;
time_t currtime;
char *actionstr;
currtime = time(NULL);
ipaddr_check = packet_info_to_ip(ip);
if (packet_cache_len > 0) {
cache_hash = packet_cache_hash(ip) % packet_cache_len;
}
if (cache_hash>0 && cache_hash<packet_cache_len && packet_cache != NULL) {
if (packet_cache[cache_hash].ipaddr==ipaddr_check
&& packet_cache[cache_hash].expires>currtime) {
get_ip_string(&ip);
retval = packet_cache[cache_hash].action;
switch (retval) {
case NF_DROP:
actionstr="reject";
statics_pointer->cachereject++;
break;
case NF_ACCEPT:
actionstr="accept";
statics_pointer->cacheaccept++;
break;
default:
actionstr="???";
break;
}
if (!conf.quiet) {
logmsg(0, LOG_INFO, "[Found in cache (%s)] [%s]", actionstr, msgbuf);
}
return retval;
}
}
#endif
/* the get_ip_string is set AFTER the check_packet_*
* calls because of the possibility they could screw with
* msgbuf. They shouldn't, really, but better safe than
* sorry, at least for now. */
if (check_packet_list(&ip, whitelist) == 1) {
get_ip_string(&ip);
if (!conf.quiet) {
logmsg(0, LOG_NOTICE, "[accept whitelist] [%s]", msgbuf);
}
statics_pointer->whitelisthits++;
retval=NF_ACCEPT;
} else
if (check_packet_list(&ip, blacklist) == 1) {
get_ip_string(&ip);
if (!conf.quiet) {
logmsg(0, LOG_NOTICE, "[reject blacklist] [%s]", msgbuf);
}
statics_pointer->blacklisthits++;
retval=NF_DROP;
} else
if (check_packet_dnsbl(&ip, whitelistbl) == 1) {
get_ip_string(&ip);
if (!conf.quiet) {
logmsg(0, LOG_NOTICE, "[accept dnsbl] [%s]", msgbuf);
}
statics_pointer->whitelistblhits++;
retval=NF_ACCEPT;
} else
if (check_packet_dnsbl(&ip, blacklistbl) == 1) {
get_ip_string(&ip);
if (!conf.quiet) {
logmsg(0, LOG_NOTICE, "[reject dnsbl] [%s]", msgbuf);
}
statics_pointer->blacklistblhits++;
retval=NF_DROP;
} else {
get_ip_string(&ip);
if (conf.default_accept == 1) {
if (!conf.quiet) {
logmsg(0, LOG_INFO, "[accept fallthrough] [%s]", msgbuf);
}
retval=NF_ACCEPT;
} else {
if (!conf.quiet) {
logmsg(0, LOG_INFO, "[reject fallthrough] [%s]", msgbuf);
}
retval=NF_DROP;
}
statics_pointer->fallthroughhits++;
}
#ifdef USE_CACHE
pthread_mutex_lock(&lock_cache);
/* Put current action into the cache. */
if (packet_cache != NULL) {
packet_cache[cache_hash].ipaddr = ipaddr_check;
packet_cache[cache_hash].action = retval;
packet_cache[cache_hash].expires = currtime + packet_cache_ttl;
}
pthread_mutex_unlock(&lock_cache);
#endif
return retval;
}
void pbl_callback( void*arguments ) {
int ret=0;
if (conf.debug>3) {
pthread_mutex_lock(&lock_count);
thread_count++;
logmsg(3, LOG_DEBUG, "Thread openned [%d]", thread_count);
pthread_mutex_unlock(&lock_count);
}
// function parameters
struct packet_info ip;
struct nfq_q_handle *qh = ((struct thr_arg *)arguments)->queue_handle;
int id = ((struct thr_arg *)arguments)->id;
memcpy(&ip, &((struct thr_arg *)arguments)->ip, sizeof( struct packet_info ));
free(arguments);
arguments=NULL;
ret = packet_check_ip(ip);
if (ret == NF_ACCEPT || ret == NF_DROP) {
logmsg(2, LOG_DEBUG, "Got packet from %hhu.%hhu.%hhu.%hhu: %d", ip.b1, ip.b2, ip.b3, ip.b4, ret);
pbl_set_verdict(qh, id, ret);
}
if (conf.debug > 3) {
pthread_mutex_lock(&lock_count);
thread_count--;
logmsg(3, LOG_DEBUG, "Thread closed [%d]", thread_count);
pthread_mutex_unlock(&lock_count);
}
return;
}
// Create a new thread for the current packet
static int callback_threads(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg,
struct nfq_data *nfa, void *thread_attr) {
// Creating thread parameters
struct thr_arg *argp=NULL;
int id = 0;
int ret=0;
struct nfqnl_msg_packet_hdr *ph=NULL;
#if NETFILTERQUEUE_VERSION_NUMBER == 0
char *nfdata=NULL;
#else
unsigned char *nfdata=NULL;
#endif
struct packet_info ip;
ph = nfq_get_msg_packet_hdr(nfa);
if (ph != NULL ) {
id = ntohl(ph->packet_id);
}
ret = nfq_get_payload(nfa, &nfdata);
/* what return codes here? */
ret = get_packet_info( nfdata, &ip);
pthread_mutex_unlock(&lock_queue);
if (ret == -1) {
pbl_set_verdict(qh, id, NF_ACCEPT);
logmsg(0, LOG_ERR, "Error reading packet. Accepting packet.");
return 1;
}
if (conf.threads_max) {
pthread_mutex_lock(&lock_count);
if ( thread_count > conf.threads_max ){
pthread_mutex_unlock(&lock_count);
pbl_set_verdict(qh, id, NF_ACCEPT);
logmsg(0, LOG_ERR, "Thread queue full. Accepting packet.");
return 1;
}
pthread_mutex_unlock(&lock_count);
}
if((argp = malloc(sizeof(struct thr_arg))) == NULL) {
pbl_set_verdict(qh, id, NF_ACCEPT);
logmsg(0, LOG_ERR, "thr_arg malloc");
return 1;
}
argp->queue_handle = qh;
argp->id = id;
memcpy(&argp->ip, &ip, sizeof( struct packet_info ));
if ( pthread_create( ((struct thr_parameters *)thread_attr)->thr, ( (struct thr_parameters *)thread_attr)->thr_attr, (void *)&pbl_callback, (void *)argp) != 0 ) {
free(argp);
pbl_set_verdict(qh, id, NF_ACCEPT);
logmsg(0, LOG_ERR, "Error creating thread: %d.",thread_count);
}
return 0;
}
/*
* SYNOPSIS:
* static void pbl_set_verdict(
* const struct PBL_HANDLE *h,
* ipq_id_t id,
* unsigned int verdict
* );
*
* ARGUMENTS:
* struct PBL_HANDLE *h IP Queue handle, must not be NULL
* ipq_id_t id XXX: Id ???
* unsigned int verdict Verdict to assign this packet in the queue.
*
* RETURN VALUE:
* (none)
*
* NOTES:
* This function calls ipq_set_verdict() to the appropriate "verdict"
* It must be able to handle the condition where "conf.dryrun" is set
* causing all "verdict" values to be treated as NF_ACCEPT regardless
* of their actual value.
*
*/
static void pbl_set_verdict(struct PBL_HANDLE *h, PBL_ID_T id, unsigned int verdict) {
pthread_mutex_lock(&lock_queue);
if (conf.dryrun == 1) {
SET_VERDICT(h, id, NF_ACCEPT, 0, NULL);
} else {
SET_VERDICT(h, id, verdict, 0, NULL);
}
pthread_mutex_unlock(&lock_queue);
}
/*
* SYNOPSIS:
* int main(
* int argc,
* char **argv
* );
*
* ARGUMENTS:
* int argc "Argument Count," number of valid elements
* in the "argv" array too.
* char **argv "Argument Vector," array of pointers to the
* arguments passed to this process.
*
* RETURN VALUE:
* This function should never return, since we are a daemon. The parent
* process exits with success (EXIT_SUCCESS) from daemonize();
*
* NOTES:
* This is the function that should be called before any others, it does
* many important initialization routines (reading configuration file,
* setting up the IP Queue routines, system logging, etc) and provides
* the main loop where packets are read and processed.
*
*/
int main(int argc, char **argv) {
struct PBL_HANDLE *handle=NULL;
char buf[BUFFERSIZE];
struct nfq_handle *h;
struct nfnl_handle *nh;
int fd;
struct stat fbuf;
int rv;
pthread_attr_t thr_attr;
pthread_t thr;
#ifdef USE_NF_FAILOPEN
uint32_t flags = NFQA_CFG_F_FAIL_OPEN;
uint32_t mask = NFQA_CFG_F_FAIL_OPEN;
#endif
struct thr_parameters new_thr_arg;
new_thr_arg.thr = &thr;
new_thr_arg.thr_attr = &thr_attr;
thread_count=0;
pthread_mutex_init(&lock_count, NULL);
// debug level
conf.debug = 0;
conf.threads_max = 0;
if (stat("/proc/net/netfilter/nfnetlink_queue", &fbuf) == ENOENT) {
fprintf(stderr, "Please make sure you have\ncompiled a kernel with the Netfilter QUEUE target built in, or loaded the appropriate module.\n");
exit(EXIT_FAILURE);
}
catch_sigterm();
/* Parse execution arguments. */
parse_arguments(argc, argv);
/* Parse our configuration data. */
parse_config();
if (conf.dryrun == 1 && conf.log_level<5) {
conf.log_level=5;
}
openlog("packetbl", LOG_PID, conf.log_facility);
if ( arg_debug ) {
conf.debug=arg_debug;
}
if ( arg_quiet == 1 ) {
conf.quiet = 1;
}
logmsg(0, LOG_DEBUG, "Debug level %d", conf.debug);
logmsg(0, LOG_DEBUG, "Linking to queue %d", conf.queueno);
if (conf.debug == 0) {
daemonize();
}
#ifdef USE_SOCKSTAT
pbl_init_sockstat();
#endif
#ifdef USE_CACHE
if (packet_cache_len > 0) {
/* Allocate space for the packet cache if a positive number of
elements is requested. */
packet_cache = malloc(sizeof(*packet_cache) * packet_cache_len);
} else {
packet_cache = NULL;
}
packet_cache_clear();
#endif
/* thread stuff */
pthread_attr_init(&thr_attr);
pthread_attr_setdetachstate(&thr_attr, PTHREAD_CREATE_DETACHED);
// initializing nfqueue
logmsg(2, LOG_DEBUG, "Creating nfq handle...");
if ((h = nfq_open()) == NULL) {
logmsg(1, LOG_ERR, "Couldn't create nfq handle: %s", strerror(errno));
exit(EXIT_FAILURE);
}
logmsg(2, LOG_DEBUG, "unbinding nfq handle...");
if (nfq_unbind_pf(h, AF_INET) < 0) {
logmsg(1, LOG_ERR, "Couldn't unbind nf_queue handler for AF_INET");
exit(EXIT_FAILURE);
}
logmsg(2, LOG_DEBUG, "binding nfq handle...");
if (nfq_bind_pf(h, AF_INET) < 0) {
logmsg(1, LOG_ERR, "Couldn't bind ns_queue handler for AF_INET");
exit(EXIT_FAILURE);
}
logmsg(2, LOG_DEBUG, "creating queue...");
if ((handle = nfq_create_queue(h, conf.queueno, &callback_threads, (void*)&new_thr_arg)) == NULL) {
logmsg(1, LOG_ERR, "nfq_create_queue failed");
exit(EXIT_FAILURE);
}
#ifdef USE_NF_FAILOPEN
logmsg(2, LOG_DEBUG, "Configuring fail-open flag...");
// Accept packet if queue is full
if (nfq_set_queue_flags(handle, mask, flags) == -1) {
logmsg(1, LOG_ERR, "nfq_set_queue_flags failed");
exit(EXIT_FAILURE);
}
#endif
if ((PBL_SET_MODE(handle, PBL_COPY_PACKET, BUFFERSIZE)) == -1) {
logmsg(1, LOG_ERR, "ipq_set_mode error: %s", PBL_ERRSTR);
if (errno == 111) {
logmsg(0, LOG_ERR, "try loading the ip_queue module");
}
exit(EXIT_FAILURE);
}
// configure a queue size
if (conf.queue_size)
{
if ( nfq_set_queue_maxlen ( handle, conf.queue_size ) ) {
logmsg(1, LOG_ERR, "nfq_set_queue_maxlen");
exit(EXIT_FAILURE);
}
}
logmsg(1, LOG_INFO, "packetbl started successfully");
/* main packet processing loop. This loop should never terminate
* unless a signal is received or some other unforeseen thing
* happens.
*/
while (1) {
nh = nfq_nfnlh(h);
fd = nfnl_fd(nh);
logmsg(2, LOG_DEBUG, "Entering main loop.");
while ((rv = recv(fd, buf, sizeof(buf), 0)) > 0) {
if (rv>0)
{
pthread_mutex_lock(&lock_queue);
logmsg(2, LOG_DEBUG, "Handling a packet");
nfq_handle_packet(h, buf, rv);
logmsg(2, LOG_DEBUG, "End handling a packet");
}
logmsg(2, LOG_DEBUG, "Packet got.");
statistics.totalpackets++;
}
}
}
/*
* SYNOPSIS:
* int get_packet_info(
* ipq_packet_msg_t *packet,
* struct packet_info *ip
* );
*
* ARGUMENTS:
* ipq_packet_msg_t *packet IP Queue supplied packet headers
* struct packet_info *ip Structure to be filled in.
*
* RETURN VALUE:
* 0 is returned on success, non-zero indicates that the packet could not
* be properly processed (i.e., it's off the wrong protocol or version).
*
* NOTES:
* This function fills in the previously allocated "ip" parameter with
* data from the "packet" parameter.
*
*/
#if NETFILTERQUEUE_VERSION_NUMBER == 0
int get_packet_info(char *payload, struct packet_info *ip) {
#else
int get_packet_info(unsigned char *payload, struct packet_info *ip) {
#endif
int version;
int ip_header_length, header_size;
if (ip == NULL || payload == NULL) {
return -1;
}
ip->s_port = 0;
ip->d_port = 0;
/* Get IP Version Byte 1 of IP Header */
version = payload[0] & 0xF0;
version >>= 4;
/* Get IP Header length Byte 2 of IP Header
* Header length is usually 20, or 5 32-bit words */
ip_header_length = payload[0] & 0x0F;
header_size = ip_header_length * 4;
/* We're not handling IPV6 packets yet. I'll probably rewrite
* this whole damned thing in C++ first. */
if (version != 4) {
return -1;
}
/* IP Address Bytes 13 - 16 of IP header */
ip->b1 = payload[12];
ip->b2 = payload[13];
ip->b3 = payload[14];
ip->b4 = payload[15];
/* Source Port Bytes 21 - 22 of IP Header
* Bytes 1 - 2 of TCP Header */
ip->s_port = payload[header_size] * 256;
ip->s_port += payload[header_size + 1];
/* Destination Port Bytes 23 - 24 of IP Header
* Bytes 3 - 4 of TCP Header */
ip->d_port = payload[header_size + 2] * 256;
ip->d_port += payload[header_size + 3];
/* TCP Flags Byte 14 of TCP header
* Last six bits
* We're only interested at present in the SYN Flag.
* But there's no reason not to copy all of them, the operation
* would take pretty much the same time anyway. */
ip->flags = payload[header_size + 13] & 0x3F;
/* Returning -1, at present accepts the packet unconditionally. */
if (conf.allow_non25 == 0 && ip->d_port != 25) {
return -1;
}
if ((conf.allow_nonsyn == 0) && ((ip->flags & TH_SYN) == 0)) {
return -1;
}
/* Return success */
return 0;
}
/*
* SYNOPSIS:
* void parse_config( void );
*
* ARGUMENTS:
* (none)
*
* RETURN VALUE:
* (none)
*
* NOTES:
* This function parses the configuration file and sets the appropriate
* global variables. It may cause the program to abort with a failure