-
Notifications
You must be signed in to change notification settings - Fork 9
/
sniff2ban.c
2582 lines (2306 loc) · 59.9 KB
/
sniff2ban.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
/*
* sniff2ban.c: Scan for intrusions
*
* Copyright (C) 2009-2024 Nigel Horne, [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* This program does not need to be thread safe
*
* TODO: more error checking
* TODO: Handle TCP packets out of order and/or fragmented (libpcap may do
* this already) and sequence numbers
* TODO: Consider netfilter/ULOG on Linux
* TODO: Support UDP
* TODO: Connect to spamassassin (probably not needed if you use Sanesecurity)
* FIXME: On Solaris10 I see "too many open files" errors.
* TODO: Handle background/foreground by enabling/disabling promiscuous mode
* TODO: --enable-http-scanning should be a runtime not a compile time option
* TODO: condsider libipq (iptables-dev on Debian)
* TODO: use INSTREAM when talking to clamd, and stop creating the temp files
* TODO: to avoid clamd timeout and dropping the IDSESSION, send PING from time
* to time
* TODO: SMTP_SCANNING - look for 'possible SMTP attack'
*
* Version 0.07 21/12/09
* Version 0.10 12/2/10
*/
/* RFC791 = IP */
/* RFC793 = TCP */
#if HAVE_CONFIG_H
#include "config.h"
#endif
/* no LIBPCAP (raw mode) only works on Linux */
#if !defined(C_LINUX) && !defined(HAVE_LIBPCAP)
#error You must install libpcap
#endif
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#include <unistd.h>
#include <signal.h>
#include <pwd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <net/if.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_IP_COMPAT_H
#include <netinet/ip_compat.h>
#endif
#ifdef HAVE_NETINET_IN_SYSTM_H
#include <netinet/in_systm.h>
#endif
#ifdef HAVE_NETINET_IF_ETHER_H
#include <netinet/if_ether.h>
#endif
#ifdef HAVE_NET_IF_ETHER_H
#include <net/if_ether.h>
#endif
#ifdef HAVE_SYS_ETHERNET_H
#include <sys/ethernet.h>
#endif
#ifdef HAVE_NET_ETHERNET_H
#include <net/ethernet.h>
#endif
#include <netinet/ip.h>
#include <netinet/tcp.h>
#ifdef HAVE_LIBPCAP
#include <pcap.h>
#endif
#include <string.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <fcntl.h>
#include <time.h>
#include <syslog.h>
#include <getopt.h>
#include <ctype.h>
#ifdef HAVE_ARPA_NAMESER_H
#include <arpa/nameser.h>
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
#include <arpa/nameser_compat.h>
#endif
#ifdef HAVE_RESOLV_H
#include <resolv.h>
#endif
#include <assert.h>
#include <dirent.h>
#include "hashtable.h"
#define MAXBYTES 2048
#ifdef SITES_ENABLED_DIR
#define MINSCANSIZE 8
#else
#define MINSCANSIZE 64
#endif
#define MAXSCANSIZE 1024L*1024L
#define TIMEALIVE 60 /*
* After this number of seconds assume the
* connection has closed
*/
#define MIN_SCAN_OFTEN_SECS 5 /* Do not scan a file more often than this */
#if(defined(AUTH_LOG) || defined(DOVECOT_LOG))
#define MAX_FAILURES 3 /* Any more than this and you can't get in */
#endif
union ip_addr {
in_addr_t i;
unsigned char c[4];
};
struct key {
union ip_addr saddr;
union ip_addr daddr;
in_port_t sport;
in_port_t dport;
};
struct value {
char *filename;
off_t nbytes;
time_t lastscanned;
time_t lastwritten;
unsigned int infected:1;
unsigned int forcescan:1;
FILE *fp;
};
static struct whitelist {
union ip_addr addr;
uint32_t mask;
struct whitelist *next;
} *whitelist, *whitelist_tail;
static struct sacredlist {
const char *program;
struct sacredlist *next;
} *sacredlist, *sacredlist_tail;
#ifdef SITES_ENABLED_DIR
static struct apachehosts {
const char *name;
struct apachehosts *next;
} *apachehosts;
#endif
#ifdef CLAMD_CONF
static const char *sockname; /* talk to clamd: pathname or host */
static in_port_t sockport; /* talk to clamd: if host */
static int clamd_socket;
#endif
#ifdef SITES_ENABLED_DIR
/*
* This blocks legitimate access to services such as phpmyadmin and
* crossdomain.xml, but you can get around that by whitelisting the client
*/
static const char *http_probes[] = {
"GET //mysql/",
"GET /mysql//scripts/setup.php",
"GET /admin/mysql/scripts/setup.php",
"GET /user/soapCaller.bs",
"GET /w00tw00t.at.",
"GET /test.w00t:)",
/*"GET /w00tw00t.at.ISC.SANS.DFind:)",*/
/*"GET /w00tw00t.at.blackhats.romanian.anti-sec:)",*/
"GET /pma//scripts/setup.php",
"GET /pma/scripts/setup.php",
"HEAD /pma/scripts/setup.php",
"GET //zencart//install.txt",
"GET /horde//README", /* Mambo */
"GET /cube/README", /* Morfeus */
"GET /roundcubemail/README", /* Morfeus */
"GET /round/README", /* Morfeus */
"GET //phpMyAdmin//scripts/setup.php",
"GET /phpmyadmin/scripts/setup.php", /* Toata dragostea mea pentru iEdi */
"GET //phpmyadmin/",
"GET /phpmyadmin//scripts/setup.php",
"GET /phpmyadmin/scripts/setup.php",
"GET //phpmyadmin/config/config.inc.php?p=phpinfo();",
"GET /phpMyAdmin-", /* ZmEu */
"GET //phpMyAdmin/",
"GET /phpMyAdmin/",
"GET /phpMyAdmin-2.10.0.0/scripts/setup.php",
"GET /admin",
"GET /e107_files/e107.css", /* Toata dragostea mea pentru diavola */
"GET /controls/ps3-dbadmin/scripts/setup.php", /* Toata dragostea mea pentru iEdi */
"GET /thisdoesnotexistahaha.php",
"GET //themes/NukeNews/",
"GET /adxmlrpc.php",
"GET /cart/install.txt", /* Toata dragostea mea pentru diavola */
/* "GET //pma/config/config.inc.php?p=phpinfo();", */
"GET //pma/", /* Made by ZmEu @ WhiteHat Team - www.whitehat.ro */
"GET /scripts/setup.php", /* ZmEu */
"GET //sql/", /* ZmEu */
"GET //PHPMYADMIN/", /* ZmEu */
"GET //dbadmin/config/config.inc.php?p=phpinfo();",
"GET //horde/util/barcode.php?type=../../../../../../../../../../../../../etc/passwd",
"GET //web-console/css//dtree.css",
"GET /webdav/test",
"GET /webdav/index.html",
"GET /crossdomain.xml",
"GET //phpldapadmin/htdocs/",
"GET //PMA2005/",
"GET /jmx-console/", /* FHScan Core 1.1 */
"GET /vicidial/welcome.php",
"GET /calendar/AUTHORS",
"GET /appConf.htm",
"HEAD /manager/status",
"HEAD /manager/html",
"GET /appserv/main.php",
"GET /3rdparty/phpMyAdmin",
"GET /_phpMyAdmin/scripts/setup.php",
"GET /sqladmin/scripts/setup.php",
"GET /sqlmanager/scripts/setup.php",
"GET /sql/scripts/setup.php",
"GET /SQL/scripts/setup.php",
"GET /sqlweb/scripts/setup.php",
"GET /xampp/phpmyadmin/scripts/setup.php",
"GET /admin/index.php",
"GET /phpMyAdmin-2/index.php",
"GET //phpMyAdmin-2/",
"GET /translators.html",
"GET //typo3/phpmyadmin/index.php",
"GET /xmlrpc.php HTTP/1.1",
"GET /wp-login.php HTTP/1.1",
"POST /cgi-bin/php?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64+%73%61%66%65%5F%6D%6F%64%65%3D%6F%66%66+%2D%64+%73%75%68%6F%73%69%6E%2E%73%69%6D%75%6C%61%74%69%6F%6E%3D%6F",
"GET /phppath/php",
"GET //administrator/components/",
"GET /administrator/index.php",
"GET /myadmin/scripts/setup.php",
"GET /HNAP1/",
"GET /phpTest/zologize/axa.php",
"GET /cgi-bin/rtpd.cgi?/bin/busybox",
"GET /muieblackcat",
"GET /admin/fckeditor/editor/filemanager/browser/default/connectors/test.html",
"GET /bxbx/bxb/bx.php",
"GET /xpxp/xpx/xp.php",
"GET /zbzb/zbz/zb.php",
"GET /qpqp/qpq/qp.php",
"GET /juju/juj/ju.php",
"HEAD /fckeditor/editor/filemanager/browser/default/connectors/aspx/connector.aspx",
"POST http://vlad-tepes.bofh.it/freenode-proxy-checker.txt",
"GET /tmUnblock.cgi",
"POST http://check.proxyradar.com",
"GET /server-status?HTTP_POST=%\"%6346#%#/ˠ%\"#423|;&HTTP_CGI_GET=GRESYYK\"K&J\"#L523D2G23H23", /* apache 0day by @hxmonsegur */
"GET /MyAdmin/scripts/setup.php",
"GET /PMA2011/scripts/setup.php",
"GET /PMA2012/scripts/setup.php",
"GET /engine/log.txt",
"GET /stalker_portal/server/adm/users/users-list-json",
"GET /_asterisk/",
"GET /login.cgi/cli=aa",
"masscan/",
"GET /plugins/weathermap/configs/conn.php?",
"GET /invoker/readonly",
"GET /cools.php?id=wget",
"GET /aastra/aastra.cfg",
"GET /dana-na/jam/querymanifest.cgi?component=preConfiguration",
"POST /dns-query",
"POST /editBlackAndWhiteList",
"GET /?XDEBUG_SESSION_START=phpstorm",
"GET ../../",
"POST /api/jsonws/invoke",
"GET /?a=fetch&content=<php>die(@md5(HelloThinkCMF))</php>",
"POST /cgi-bin/mainfunction.cgi",
"GET /shell?cd+/tmp;rm+-rf+*;wget",
"/${jndi:ldap://",
"GET /wp-includes/id3/license.txt/wp/wp-includes/wlwmanifest.xml",
"GET /vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php",
/* OpenWRT hack */
"GET /cgi-bin/luci/;stok=/locale?form=country&operation=write&country",
"..%252Fetc%252Fpasswd",
"GET /forum/viewforum.php?f=6&f=..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252Fetc%252Fpasswd",
NULL
};
static size_t *http_probelens;
#endif
int sniff_insert(struct hashtable *h, struct key *k, struct value *v);
struct value *sniff_search(struct hashtable *h, struct key *k);
struct value *sniff_remove(struct hashtable *h, struct key *k);
DEFINE_HASHTABLE_INSERT(sniff_insert, struct key, struct value)
DEFINE_HASHTABLE_SEARCH(sniff_search, struct key, struct value)
DEFINE_HASHTABLE_REMOVE(sniff_remove, struct key, struct value)
static int add_to_whitelist(const char *address);
static int add_ip_to_whitelist(const char *address);
static int add_to_sacred(const char *program);
static unsigned int iphash(const void *p);
static int hasheq(const void *p1, const void *p2);
static int scan(struct value *v, union ip_addr saddr, union ip_addr daddr, in_port_t dport);
static void kill_route(union ip_addr addr_host_order);
static void allow_route(union ip_addr addr_host_order);
static void allow_route(union ip_addr addr);
static void onexit(void);
#ifdef CLAMD_CONF
static int clamscan(const char *file, char *virusname, const char *socketpath, in_port_t port);
static int unix_socket(const char *socket_name);
static int ip_socket(const char *hostname, in_port_t portnum);
static int recv_data(int s, int tsecs, char *buf, size_t len);
static void close_clamd_socket(void);
static int send_data(int fd, const void *buff, unsigned int count, const char *socketpath);
#endif
static void hashtable_iterate(struct hashtable *h, int scanthem, int foreceunlink);
static void destroy(struct hashtable *h, struct key *k, struct value *v);
static const char *ipv4tostr(char *s, union ip_addr addr_host_order);
#ifdef CLAMD_CONF
static int getsocknamefromclamdconf(char *buf);
#else
#define getsocknamefromclamdconf(buf) (0)
#endif
static int iswhitelisted(const union ip_addr *host_order_addr);
#ifdef SITES_ENABLED_DIR
static void setup_apache_hosts(void);
#endif
#ifdef SITES_ENABLED_DIR
static in_port_t http_port;
#endif
static struct hashtable *hashtable;
static int droproutes;
static int stopping;
static int verbose = 0;
static int killprograms;
static int timealive = TIMEALIVE;
static const char *tmpdir;
#if(defined(AUTH_LOG) || defined(DOVECOT_LOG))
static int max_failures = MAX_FAILURES;
#endif
int
main(int argc, char *const *argv)
{
#ifndef IPPROTO_TCP
const struct protoent *protoent;
int tcp;
#endif
const char *interface, *pidfile = NULL;
const struct passwd *passwd;
struct key *kprealloc = NULL;
int dont_drop_self = 0;
int dont_scan_white_listed = 0;
#ifdef SITES_ENABLED_DIR
int i;
const char **probe;
#endif
#ifdef HAVE_LIBPCAP
bpf_u_int32 deviceaddr, devicemask;
pcap_t *pcap;
struct bpf_program fp;
char errbuf[PCAP_ERRBUF_SIZE];
#else
int sock;
short flags;
const struct sockaddr_in *etheraddr;
struct ifreq ifreq;
struct sockaddr_in sin;
#endif
char buf[BUFSIZ];
for(;;) {
int opt_index = 0;
const char *args = "dhkp:sS:t:T:vVw:W";
static struct option long_options[] = {
{
"drop-routes", 0, NULL, 'd'
}, {
"dont-drop-self", 0, NULL, 's'
}, {
"help", 0, NULL, 'h'
}, {
"kill-programs", 0, NULL, 'k'
}, {
#if(defined(AUTH_LOG) || defined(DOVECOT_LOG))
"maximum-failures", 0, NULL, 'm'
}, {
#endif
"pidfile", 1, NULL, 'p'
}, {
"sacred-program", 1, NULL, 'S'
}, {
"time-alive", 1, NULL, 't'
}, {
"tmpdir", 1, NULL, 'T'
}, {
"verbose", 0, NULL, 'v'
}, {
"version", 0, NULL, 'V'
}, {
"white-list", 1, NULL, 'w'
}, {
"dont-scan-white-listed", 0, NULL, 'W'
}, {
NULL, 0, NULL, '\0'
}
};
int ret = getopt_long(argc, argv, args, long_options, &opt_index);
if(ret == -1)
break;
else if(ret == 0)
continue;
switch(ret) {
case 'd':
droproutes++;
break;
case 'p':
pidfile = optarg;
break;
case 'k':
killprograms++;
break;
#if(defined(AUTH_LOG) || defined(DOVECOT_LOG))
case 'm':
max_failures = atoi(optarg);
if(max_failures < 0) {
fprintf(stderr, "%s: -m argument can't be negative\n",
argv[0]);
return 1;
}
#endif
break;
case 's':
/*
* Useful when using sniff2ban to monitor
* outgoing emails where we want to see what's
* going on, but don't want to block all traffic
*/
dont_drop_self++;
break;
case 'T':
tmpdir = optarg;
break;
case 't':
timealive = atoi(optarg);
if(timealive < 0) {
fprintf(stderr, "%s: -t argument can't be negative\n",
argv[0]);
return 1;
}
break;
case 'v':
verbose++;
break;
case 'V':
puts(PACKAGE_STRING);
return 0;
case 'w':
if(!add_to_whitelist(optarg)) {
fprintf(stderr, "%s: Failed to whitelist %s\n",
argv[0], optarg);
return 1;
}
break;
case 'W':
dont_scan_white_listed++;
break;
case 'S':
if(!add_to_sacred(optarg)) {
fprintf(stderr, "%s: Failed to sacred list %s\n",
argv[0], optarg);
return 1;
}
break;
default:
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-T dir] [-t secs] [-v] [-w IP address] [ -V ] [ -W ] [-p pidfile] [-S sacred_program ] [ socket ] [ interface ]\n", argv[0]);
return 1;
}
}
/*
* Sanity checks
*/
if(!droproutes) {
if(whitelist) {
fputs("You have specified addresses to whitelist, but not to drop routes\n", stderr);
return 1;
}
if(dont_drop_self) {
fputs("You have specified the -s flag, but not the -d flag\n", stderr);
return 1;
}
}
if(sacredlist_tail && !killprograms) {
fputs("You have specified a sacred program list, but not requested to kill programs\n", stderr);
return 1;
}
#ifdef HAVE_LIBPCAP
if(optind == argc) {
interface = pcap_lookupdev(errbuf);
if(verbose && interface)
printf("%s: Monitoring %s for malware\n", argv[0], interface);
#ifdef CLAMD_CONF
if(!getsocknamefromclamdconf(buf)) {
/*
* No means to talk to clamd or interface given and
* there is no clamd.conf to work it out, therefore
* the socket must be given
*/
fputs("Couldn't determine how to talk to clamd\n", stderr);
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-t secs] [-v] [-w IP address] [ -W ] [-S sacred_program ] socket [ interface ]\n", argv[0]);
return 1;
}
if(verbose >= 2)
printf("%s: Using %s as the ClamAV socket\n", argv[0], buf);
sockname = buf;
#endif
} else if(optind == (argc - 1)) {
interface = pcap_lookupdev(errbuf);
if(verbose && interface)
printf("%s: Monitoring %s for malware\n", argv[0], interface);
#ifdef CLAMD_CONF
sockname = argv[optind++];
#endif
} else {
if(optind != (argc - 2)) {
if(!getsocknamefromclamdconf(buf)) {
/*
* No means to talk to clamd or interface given
* and there is no clamd.conf to work it out,
* therefore the socket must be given
*/
fputs("Couldn't determine how to talk to clamd\n", stderr);
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-t secs] [-v] [-w IP address] [ -W ] [-S sacred_program ] socket [ interface ]\n", argv[0]);
return 1;
}
if(verbose >= 2)
printf("%s: Using %s as the ClamAV socket\n", argv[0], buf);
#ifdef CLAMD_CONF
sockname = buf;
} else
sockname = argv[optind++];
#else
}
#endif
interface = NULL;
}
#elif defined(CLAMD_CONF)
if(optind != (argc - 2)) {
if(!getsocknamefromclamdconf(buf)) {
/* No means to talk to clamd or interface given */
fputs("Couldn't determine how to talk to clamd\n", stderr);
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-t secs] [-v] [-w IP address] [ -W ] [-S sacred_program ] socket [ interface ]\n", argv[0]);
return 1;
}
if(verbose >= 2)
printf("Using %s as the ClamAV socket\n", buf);
sockname = buf;
} else
sockname = argv[optind++];
if(sockname && (sockname[0] != '/')) {
char *ptr = strchr(sockname, ':');
if(ptr == NULL) {
fprintf(stderr, "%s: No port number given to talk to clamd in %s\n",
argv[0], sockname);
return 1;
}
*ptr++ = '\0';
if(!isdigit(*ptr)) {
fprintf(stderr, "%s: Invalid port number given '%s'\n",
argv[0], ptr);
return 1;
}
sockport = atoi(ptr);
if(sockport <= 0) {
fprintf(stderr, "%s: Invalid port number given '%s'\n",
argv[0], ptr);
return 1;
}
}
/* TODO: validate sockname by sending PING to clamd */
#endif
#ifdef HAVE_LIBPCAP
if(argv[optind])
interface = argv[optind];
if(interface == NULL) {
fputs("Couldn't determine a default device\n", stderr);
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-t secs] [-v] [-w IP address] [ -W ] [-S sacred_program ] [ socket ] interface\n", argv[0]);
return 1;
}
/* Open the device in promiscuous mode */
pcap = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf);
if(pcap == NULL) {
fprintf(stderr, "%s: Couldn't open device %s: %s\n",
argv[0], interface, errbuf);
return 2;
}
#else
interface = argv[optind];
if(interface == NULL) {
fputs("No Interface given\n", stderr);
fprintf(stderr, "Usage: %s [-d] [-k] [-s] [-t secs] [-v] [-w IP address] [ -W ] [-S sacred_program ] [ socket ] interface\n", argv[0]);
return 1;
}
/*
* Don't use ETH_P_IP so that we can catch FTP transfers
*/
if((sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
perror("socket");
return errno;
}
strncpy(ifreq.ifr_name, interface, IFNAMSIZ);
ioctl(sock, SIOCGIFFLAGS, &ifreq);
flags = ifreq.ifr_flags;
if(!(flags&IFF_PROMISC)) {
ifreq.ifr_flags |= IFF_PROMISC;
if(ioctl(sock, SIOCSIFFLAGS, &ifreq) < 0) {
perror("ioctl");
return errno;
}
}
#endif
if(dont_scan_white_listed && (!dont_drop_self) && (whitelist_tail == NULL))
puts("Warning: -W given, but not -w which is probably not what you wanted");
#ifdef SITES_ENABLED_DIR
if(verbose)
printf("%s: Will scan HTTP messages for sites listed in %s\n",
argv[0], SITES_ENABLED_DIR);
setup_apache_hosts();
#else
if(verbose >= 2)
printf("%s: Will not scan HTTP messages\n", argv[0]);
#endif
#ifdef AUTH_LOG
if(verbose)
printf("%s: Will scan SSH failures listed in %s\n",
argv[0], AUTH_LOG);
#endif
#ifdef DOVECOT_LOG
if(verbose)
printf("%s: Will scan Dovecot failures listed in %s\n",
argv[0], DOVECOT_LOG);
#endif
passwd = getpwnam("clamav");
if(!droproutes) {
if(passwd) {
if(setgid(passwd->pw_gid) < 0)
perror("setgid");
if(setuid(passwd->pw_uid) < 0)
perror("setuid");
} else
fputs("No ClamAV user - running as root is dangerous\n", stderr);
}
endpwent();
umask(077);
#ifdef HAVE_LIBPCAP
if(pcap_lookupnet(interface, &deviceaddr, &devicemask, errbuf) == -1) {
fprintf(stderr, "%s: Couldn't get address of device %s\n",
argv[0], interface);
return 3;
}
pcap_set_datalink(pcap, DLT_EN10MB);
#else
ioctl(sock, SIOCGIFADDR, &ifreq);
etheraddr = (const struct sockaddr_in *)&ifreq.ifr_addr;
memcpy(&sin, etheraddr, sizeof(struct sockaddr_in));
if(bind(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) < 0)
perror(inet_ntoa(sin.sin_addr));
#endif
if(dont_drop_self) {
if(whitelist == NULL)
whitelist_tail = whitelist = malloc(sizeof(struct whitelist));
else {
whitelist_tail->next = malloc(sizeof(struct whitelist));
whitelist_tail = whitelist_tail->next;
}
#ifdef HAVE_LIBPCAP
whitelist_tail->addr.i = deviceaddr;
pcap_setdirection(pcap, PCAP_D_IN);
if(verbose >= 2) {
struct in_addr addr;
union ip_addr mask;
addr.s_addr = deviceaddr;
mask.i = devicemask;
printf("%s: Not checking self (%s/%d.%d.%d.%d) for malware\n",
argv[0], inet_ntoa(addr),
mask.c[0], mask.c[1], mask.c[2], mask.c[3]);
}
whitelist_tail->mask = ntohl(devicemask);
#else
whitelist_tail->addr.i = etheraddr->sin_addr.s_addr;
whitelist_tail->mask = 0xFFFFFFFF;
#endif
whitelist_tail->next = NULL;
}
#ifndef IPPROTO_TCP
/* If IPPROTO_TCP isn't defined try /etc/protocols */
protoent = getprotoent("tcp");
if(protoent == NULL) {
fprintf(stderr, "%s: Can't work out the TCP protocol number\n",
argv[0]);
#ifdef HAVE_LIBPCAP
pcap_close(pcap);
#endif
return 3;
}
tcp = protoent->p_proto;
endprotoent();
#endif
#ifdef SITES_ENABLED_DIR
i = 0;
for(probe = http_probes; *probe; probe++)
i++;
http_probelens = malloc(i * sizeof(size_t));
if(http_probelens == NULL) {
fprintf(stderr, "%s: Out of memory\n", argv[0]);
#ifdef HAVE_LIBPCAP
pcap_close(pcap);
#endif
return 4;
}
i = 0;
for(probe = http_probes; *probe; probe++)
http_probelens[i++] = strlen(*probe);
#endif
#ifdef HAVE_LIBPCAP
if(pcap_compile(pcap, &fp, "tcp", 0, deviceaddr) >= 0) {
if(pcap_setfilter(pcap, &fp) < 0)
fprintf(stderr, "%s: Error setting filter \"tcp\"\n",
argv[0]);
} else
fprintf(stderr, "%s: Error with pcap_compile \"tcp\"\n",
argv[0]);
#endif
if(!verbose)
switch(fork()) {
case -1:
perror("fork");
return errno;
case 0:
/*close(0);
close(1);
close(2);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
dup(1);*/
break;
default:
return 0;
}
if(pidfile) {
/*
* Add a pidfile, useful for monit(1) and puppet(1)
* to restart if sniff2ban dies
*/
FILE *p = fopen(pidfile, "w");
if(p == NULL) {
perror(pidfile);
return errno;
}
fprintf(p, "%d\n", getpid());
fclose(p);
}
if(tmpdir == NULL) {
if(getenv("TMPDIR"))
tmpdir = getenv("TMPDIR");
else if(P_tmpdir)
tmpdir = P_tmpdir;
else
tmpdir = "/tmp";
}
openlog(argv[0], LOG_CONS|LOG_PID, LOG_DAEMON);
hashtable = create_hashtable(200, iphash, hasheq);
#ifdef HAVE_SIG_T
signal(SIGTERM, (sig_t)onexit);
signal(SIGINT, (sig_t)onexit);
#elif defined(HAVE_SIGHANDLER_T)
signal(SIGTERM, (__sighandler_t)onexit);
signal(SIGINT, (__sighandler_t)onexit);
#else
signal(SIGTERM, onexit);
signal(SIGINT, onexit);
#endif
atexit(onexit);
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN);
#endif
while(!stopping) {
ssize_t nbytes, payloadlength;
uint16_t sport, dport;
const struct ether_header *ethhdr;
#ifdef HAVE_STRUCT_IPHDR
const struct iphdr *iphdr;
#else
const struct ip *iphdr;
#endif
const struct tcphdr *tcphdr;
const unsigned char *ptr;
struct key *k;
struct value *v;
union ip_addr source_addr, dest_addr;
#ifdef HAVE_LIBPCAP
const u_char *buffer;
struct pcap_pkthdr header;
#else
unsigned char buffer[MAXBYTES];
#endif
#ifdef HAVE_LIBPCAP
buffer = pcap_next(pcap, &header);
if(buffer == NULL) {
/*fprintf(stderr, "%s: Error reading data from %s\n",
argv[0], interface);
hashtable_iterate(hashtable, 0, 1);
pcap_close(pcap);
return 1;*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
nbytes = header.len;
#else
nbytes = recvfrom(sock, buffer, sizeof(buffer), 0, NULL, NULL);
if(nbytes < 0) {
perror("recvfrom");
hashtable_iterate(hashtable, 0, 1);
close(sock);
return errno;
}
#endif
if(nbytes < (ssize_t)sizeof(struct ether_header)) {
puts("too small");
continue;
}
ethhdr = (const struct ether_header *)buffer;
#ifdef ETHERTYPE_IP
if(ntohs(ethhdr->ether_type) != ETHERTYPE_IP) {
/*printf("ether proto %d\n", ntohs(ethhdr->ether_type));*/
continue;
}
#else
if(ntohs(ethhdr->ether_type) != ETH_P_IP) {
/*printf("ether proto %d\n", ntohs(ethhdr->ether_type));*/
continue;
}
#endif
#ifdef HAVE_STRUCT_IPHDR
iphdr = (const struct iphdr *)&buffer[sizeof(struct ether_header)];
#ifdef IPPROTO_TCP
if((int)iphdr->protocol != IPPROTO_TCP) {
/*printf("IP proto %d\n", (int)iphdr->protocol);*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
#else
if((int)iphdr->protocol != tcp) {
/*printf("IP proto %d\n", (int)iphdr->protocol);*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
#endif
#else
iphdr = (const struct ip *)&buffer[sizeof(struct ether_header)];
if((int)iphdr->ip_p != IPPROTO_TCP) {
/*printf("IP proto %d\n", (int)iphdr->ip_p);*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
#endif
tcphdr = (const struct tcphdr *)&buffer[sizeof(struct ether_header) + sizeof(struct ip)];
#if 0
if((iphdr->saddr == htonl(INADDR_LOOPBACK)) || (iphdr->daddr == htonl(INADDR_LOOPBACK))) {
/*
* TODO: remove this code once the bind() code has been
* written
*/
puts("loop");
hashtable_iterate(hashtable, 1, 0);
continue;
}
#endif
#ifdef HAVE_LIBPCAP
#if 0
if(((iphdr->saddr&devicemask) != deviceaddr) && ((iphdr->daddr&devicemask) != deviceaddr)) {
/*struct in_addr addr;
memcpy(&addr, &iphdr->saddr, sizeof(struct in_addr));
printf("filter out saddr = %s ", inet_ntoa(addr));
memcpy(&addr, &iphdr->saddr, sizeof(struct in_addr));
printf("daddr = %s ", inet_ntoa(addr));
memcpy(&addr, &deviceaddr, sizeof(struct in_addr));
printf("deviceaddr = %s\n", inet_ntoa(addr));*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
#endif
#else
if((iphdr->saddr != etheraddr->sin_addr.s_addr) && (iphdr->daddr != etheraddr->sin_addr.s_addr)) {
/* The above bind fails, so let's filter here */
/*puts("filter out");*/
hashtable_iterate(hashtable, 1, 0);
continue;
}
#endif
#ifdef HAVE_STRUCT_IPHDR
if(iphdr->daddr == 0) {
/* FIXME: What are these? */
puts("Destination IP is 0");
continue;
}
source_addr.i = iphdr->saddr;
sport = ntohs(tcphdr->source);
dest_addr.i = iphdr->daddr;
dport = ntohs(tcphdr->dest);
#else
memcpy(&source_addr.i, &iphdr->ip_src, sizeof(source_addr.i));
sport = ntohs(tcphdr->th_sport);
memcpy(&dest_addr.i, &iphdr->ip_dst, sizeof(source_addr.i));
dport = ntohs(tcphdr->th_dport);
#endif
if(verbose >= 3) {
struct in_addr in_addr;
in_addr.s_addr = source_addr.i;
printf("%s:%d->", inet_ntoa(in_addr), sport);
in_addr.s_addr = dest_addr.i;
printf("%s:%d", inet_ntoa(in_addr), dport);
#ifdef HAVE_STRUCT_IPHDR
printf(" seq %u", ntohl(tcphdr->seq));
if(tcphdr->fin)
fputs(" FIN", stdout);
if(tcphdr->syn)
fputs(" SYN", stdout);
#else
printf(" seq %u", ntohl(tcphdr->th_seq));
if(tcphdr->th_flags&TH_FIN)
fputs(" FIN", stdout);
if(tcphdr->th_flags&TH_SYN)
fputs(" SYN", stdout);
#endif
}