-
Notifications
You must be signed in to change notification settings - Fork 1
/
breachblocker.py
1512 lines (1282 loc) · 50.6 KB
/
breachblocker.py
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
# coding: utf-8
import os
import sys
import re
import socket
import syslog
import sqlite3
import datetime
import time
import subprocess
import traceback
import argparse
import getpass
import configparser
import threading
from collections import defaultdict
"""
==================================================
**BREACHBLOCKER**
Breachblocker is a script designed to crawl log files
and get the ip addresses of hosts which tried to
break in
Copyright (C) Andy Kayl - All Rights Reserved
* Unauthorized copying of this file, via any medium is prohibited, except for your own needs
* Modification to the script logic is also prohibited, except for your own needs
* Licencing to a third-party is strictly prohibited
* Selling this script is strictly prohibited, this script is always free of charge
* Using in closed source software without prior confirmation of the author is strictly prohibited
* The author declines any responsability for any damage of any nature this script could cause
Written by Andy Kayl <[email protected]>, August 2013
==================================================
"""
__author__ = "Andy Kayl"
__version__ = "2.7.0"
__modified__ = "2019-10-23"
"""---------------------------
check python version before running
---------------------------"""
major = sys.version_info[0]
minor = sys.version_info[1]
if (major < 3 and minor < 5):
print("You need Python 3.5+ to run this script")
sys.exit(1)
IS_PY3 = False
if major == 3:
IS_PY3 = True
"""---------------------------
load mailer for simplified email sending
---------------------------"""
try:
import mailer
except ImportError:
print("Python mailer module is needed. Please install it with: pip install mailer")
sys.exit(1)
"""---------------------------
define default config variables
---------------------------"""
dry_run = 1
daemon = 0
pid_file = "/var/run/breachblocker.pid"
scan_interval = 10
write_syslog = 1
attempts = 10
block_timeout = 60
history_timeout = 43200
whitelist = "127.0.0.1"
blacklist = ""
dbfile = "/tmp/breachblocker.db"
scan_http = 0
scan_ssh = 0
scan_ftp = 0
scan_mail = 0
scan_smtp = 0
scan_synrecv = 0
send_email = 0
mailhost = "127.0.0.1"
"""---------------------------
load config
---------------------------"""
config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), "breachblocker.conf"))
if config.has_option("global", "dry_run"):
dry_run = config.getint("global", "dry_run")
if config.has_option("global", "daemon"):
daemon = config.getint("global", "daemon")
if config.has_option("global", "scan_interval"):
scan_interval = config.getint("global", "scan_interval")
if config.has_option("global", "pid_file"):
pid_file = config.get("global", "pid_file")
if config.has_option("global", "write_syslog"):
write_syslog = config.getint("global", "write_syslog")
if config.has_option("global", "attempts"):
attempts = config.getint("global", "attempts")
if config.has_option("global", "block_timeout"):
block_timeout = config.getint("global", "block_timeout")
if config.has_option("global", "history_timeout"):
history_timeout = config.getint("global", "history_timeout")
if config.has_option("global", "whitelist"):
whitelist = config.get("global", "whitelist")
if config.has_option("global", "blacklist"):
blacklist = config.get("global", "blacklist")
if config.has_option("global", "db_file"):
dbfile = config.get("global", "db_file")
if config.has_option("scan", "http"):
scan_http = config.getint("scan", "http")
if config.has_option("scan", "ssh"):
scan_ssh = config.getint("scan", "ssh")
if config.has_option("scan", "ftp"):
scan_ftp = config.getint("scan", "ftp")
if config.has_option("scan", "mail"):
scan_mail = config.getint("scan", "mail")
if config.has_option("scan", "smtp"):
scan_smtp = config.getint("scan", "smtp")
if config.has_option("scan", "synrecv"):
scan_synrecv = config.getint("scan", "synrecv")
http_svr = config.get("servers", "http")
ftp_svr = config.get("servers", "ftp")
mail_svr = config.get("servers", "mail")
ssh_svr = config.get("servers", "ssh")
smtp_svr = config.get("servers", "smtp")
if config.has_option("email", "send"):
send_email = config.getint("email", "send")
if config.has_option("email", "mailhost"):
mailhost = config.get("email", "mailhost")
email_from = config.get("email", "from")
email_to = config.get("email", "recipient")
"""---------------------------
supported server list
---------------------------"""
supp_servers = {
"rhel": [
"apache", "dovecot", "uw-imapd", "openssh",
"postfix", "proftpd", "pure-ftpd", "vsftpd"
],
"freebsd": [
"apache", "dovecot", "openssh", "postfix", "proftpd"
]
}
"""---------------------------
add cli arguments
---------------------------"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--kill",
help="Kill runniing process (only in daemon mode)",
action="store_true"
)
parser.add_argument(
"--single",
help="Run this script once if daemon mode is set to yes",
action="store_true"
)
parser.add_argument(
"--daemon",
help="Launch as background daemon",
action="store_true"
)
parser.add_argument(
"--remove",
help="Specify an ip address to remove from firewall",
metavar="IPv4-ADDR"
)
parser.add_argument(
"--check",
help="Specify an ip address to check in white-/blacklist/firewall",
metavar="IPv4-ADDR"
)
parser.add_argument(
"--whitelist",
help="Specify an ip address to whitelist temporary (minutes)",
nargs=2,
metavar=("MIN", "IPv4-ADDR")
)
parser.add_argument(
"--bl",
help="List all blocked ip addresses during scans",
action="store_true"
)
parser.add_argument(
"--wl",
help="List all temporary whitelisted addresses",
action="store_true"
)
parser.add_argument(
"--flush",
help="Clear all database/firewall adresses",
action="store_true"
)
parser.add_argument(
"--no-dryrun",
help="Overwrite config setting for DRY-RUN",
action="store_true"
)
parser.add_argument(
"--history",
help="Show history entries",
action="store_true"
)
class Firewall(object):
""" Firewall class: used for firewall interactions """
def __init__(self):
""" init firewall stuff """
self._ipfw_rulestable = 100
self.iptables_version = None
self.firewall_type = config.get("global", "firewall")
self.firewall = None
self._detect()
def _detect(self):
""" detect firewall type and return it / store it inside class """
if self.firewall_type == "iptables":
self.firewall = "iptables"
elif self.firewall_type == "firwalld":
self.firewall = "firewalld"
elif self.firewall_type == "ipfw":
self.firewall = "ipfw"
else:
if os.path.isfile("/sbin/ipfw"):
self.firewall = "ipfw"
elif os.path.isfile("/usr/bin/firewall-cmd"):
self.firewall = "firewalld"
elif os.path.isfile("/sbin/iptables"):
self.firewall = "iptables"
else:
print("Could not determine firewall type. Please set it manually.")
sys.exit(1)
if self.firewall == "iptables":
proc = subprocess.Popen("/sbin/iptables --version", shell=True, stdout=subprocess.PIPE)
proc.wait()
proc_out = proc.communicate()[0]
if IS_PY3:
proc_out = proc_out.decode()
(major, minor, bugfix) = proc_out.replace("v", "").strip().split(" ")[1].split(".")
self.iptables_version = "%d.%02d.%02d" % (int(major), int(minor), int(bugfix))
def add(self, ip):
""" add the given ip to the system firewall rules """
if self.firewall == "firewalld":
proc = subprocess.Popen(
"/usr/bin/firewall-cmd --quiet --zone drop --add-source %s" % ip,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
elif self.firewall == "ipfw":
proc = subprocess.Popen(
"/sbin/ipfw list | grep '00001 deny ip from table(%d)'" % self._ipfw_rulestable,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
stdout = proc.communicate()[0]
if stdout == "":
proc = subprocess.Popen(
"/sbin/ipfw -q add 1 deny ip from 'table(%d)' to any" % self._ipfw_rulestable,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
proc = subprocess.Popen(
"/sbin/ipfw -q table %d add %s" % (self._ipfw_rulestable, ip),
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
else:
cmd = "/sbin/iptables -w -I INPUT -s %s -j DROP"
if self.iptables_version and self.iptables_version < "1.04.20":
cmd = "/sbin/iptables -I INPUT -s %s -j DROP"
proc = subprocess.Popen(cmd % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.wait()
return proc.returncode
def getBlocked(self):
""" get all addresses blocked by the firewall """
fw_source_blocked = []
if self.firewall == "firewalld":
proc = subprocess.Popen(
"/usr/bin/firewall-cmd --zone drop --list-sources",
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
blocked = proc.communicate()[0]
if IS_PY3:
blocked = blocked.decode()
blocked = re.split("\s{1,}", blocked)
for entry in blocked:
if entry == "":
continue
fw_source_blocked.append(entry)
elif self.firewall == "ipfw":
proc = subprocess.Popen(
"/sbin/ipfw table %d list" % self._ipfw_rulestable,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
blocked = proc.communicate()[0]
if IS_PY3:
blocked = blocked.decode()
blocked = blocked.split("\n")
for entry in blocked:
if entry == "":
continue
line = re.split("\s{1,}", entry)
host = line[0].replace("/32", "")
fw_source_blocked.append(host)
else:
cmd = "/sbin/iptables -w -L INPUT -n | grep DROP"
if self.iptables_version and self.iptables_version < "1.04.20":
cmd = "/sbin/iptables -L INPUT -n | grep DROP"
blocked = os.popen(cmd).readlines()
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.wait()
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
blocked = stdout.rstrip().split("\n")
for entry in blocked:
if entry == "":
continue
line = re.split("\s{1,}", entry)
if len(line) < 5:
continue
fw_source_blocked.append(line[3])
return fw_source_blocked
def remove(self, ip):
""" remove given ip address from the firewall rules """
if self.firewall == "firewalld":
proc = subprocess.Popen(
"/usr/bin/firewall-cmd --quiet --zone drop --remove-source %s" % ip,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
elif self.firewall == "ipfw":
proc = subprocess.Popen(
"/sbin/ipfw table %d list | grep %s" % (self._ipfw_rulestable, ip),
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
stdout, stderr = proc.communicate()
if stdout == "":
return
stdout = stdout.decode()
ip = re.split("\s+", stdout)[0]
proc = subprocess.Popen(
"/sbin/ipfw -q table %d delete %s" % (self._ipfw_rulestable, ip),
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
else:
cmd = "/sbin/iptables -w -D INPUT -s %s -j DROP"
if self.iptables_version and self.iptables_version < "1.04.20":
cmd = "/sbin/iptables -D INPUT -s %s -j DROP"
proc = subprocess.Popen(
cmd % ip,
shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
proc.wait()
return proc.returncode
def check(self, ip):
fw_blocked = self.getBlocked()
if ip in fw_blocked:
return True
return False
class ScanThreadBase(threading.Thread):
""" base class for scanning threads """
def __init__(self):
threading.Thread.__init__(self)
self.log = None
self.log_pattern = None
self.ip_pattern = None
self.ip_list = None
self.blk_reason = None
self.line_numbers = 1000
def checkLogTimeout(self, line):
""" check log entry line timeout """
if line == "":
return False
now_in_secs = int(time.time())
ignore_timeout = 3600
block_timeout_scope = block_timeout * 60
if block_timeout_scope < ignore_timeout:
ignore_timeout = block_timeout_scope
line_arr = re.split("\s{1,}", line)
(month_name, day, time_) = line_arr[0:3]
year = datetime.datetime.now().strftime("%Y")
timeout_date = datetime.datetime.strptime("%s %s %s %s" % (year, month_name, day, time_), "%Y %b %d %H:%M:%S")
timeout_date_tuple = timeout_date.timetuple()
timeout_in_sec = int(time.mktime(timeout_date_tuple))
if now_in_secs - timeout_in_sec <= ignore_timeout:
return True
return False
class ScanThreadSSH(ScanThreadBase):
""" scan thread for SSH """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
ssh_comm = "cat {logfile} | grep -i sshd | grep -i -E \"{pattern}\" | tail -n {lines}".format(
logfile=self.log,
pattern=self.log_pattern,
lines=self.line_numbers
)
proc = subprocess.Popen(
ssh_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
if not self.checkLogTimeout(line):
continue
match = re.search(self.ip_pattern, line, re.IGNORECASE)
if match:
match = match.group()
if "=" in match:
ip = match.rstrip().split("=")[1]
elif "from " in match:
ip = match.replace("from ", "")
self.ip_list.append(ip)
self.blk_reason['ssh'].append(ip)
class ScanThreadMail(ScanThreadBase):
""" scan thread for mail """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
mail_comm = "cat {log} | "
mail_comm += "grep -i -E \"(imap|pop3)\" | "
mail_comm += "grep -E -v \"user=<>\" | "
mail_comm += "grep -i -E \"{pattern}\" | "
mail_comm += "tail -n {lines}"
mail_comm = mail_comm.format(
log=self.log,
pattern=self.log_pattern,
lines=self.line_numbers
)
proc = subprocess.Popen(
mail_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
if not self.checkLogTimeout(line):
continue
match = re.search(self.ip_pattern, line, re.IGNORECASE)
if match:
match = match.group()
ip = match.rstrip().split("=")
self.ip_list.append(ip[1])
self.blk_reason['mail'].append(ip[1])
class ScanThreadSMTP(ScanThreadBase):
""" scan thread for smtp """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
smtp_comm = "cat {log} | "
smtp_comm += "grep -i -E \"(smtp|sasl)\" | "
smtp_comm += "grep -i -E -v \"Connection lost\" | "
smtp_comm += "grep -i -E \"{pattern}\" | "
smtp_comm += "tail -n {lines}"
smtp_comm = smtp_comm.format(
log=self.log,
pattern=self.log_pattern,
lines=self.line_numbers
)
proc = subprocess.Popen(
smtp_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
if not self.checkLogTimeout(line):
continue
match = re.search(self.ip_pattern, line, re.IGNORECASE)
if match:
match = match.group()
if smtp_svr == "postfix":
ip = re.sub("(\[|\])", "", match)
else:
ip = match.rstrip().split("=")[1]
self.ip_list.append(ip)
self.blk_reason['smtp'].append(ip)
class ScanThreadFTP(ScanThreadBase):
""" scan thread for ftp """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
ftp_comm = "cat {log} | grep -i ftpd | grep -i -E \"{pattern}\" | tail -n {lines}"
ftp_comm = ftp_comm.format(
log=self.log,
pattern=self.log_pattern,
lines=self.line_numbers
)
proc = subprocess.Popen(
ftp_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
if not self.checkLogTimeout(line):
continue
match = re.search(self.ip_pattern, line, re.IGNORECASE)
if match:
match = match.group()
if ftp_svr == "proftpd":
ip = re.sub("(::ffff:|\[|\])", "", match)
elif ftp_svr == "vsftpd":
ip = match.rstrip().split("=")
ip = ip[1]
elif ftp_svr == "pure-ftpd":
ip = re.sub("\?@", "", match)
self.ip_list.append(ip)
self.blk_reason['ftp'].append(ip)
class ScanThreadHTTP(ScanThreadBase):
""" scan thread for http """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
http_comm = "cat {log} | grep -i -E \"{pattern}\" | tail -n {lines}"
http_comm = http_comm.format(
log=self.log,
pattern=self.log_pattern,
lines=self.line_numbers
)
proc = subprocess.Popen(
http_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
if not self.checkLogTimeout(line):
continue
if "favicon" not in shell_ret:
match = re.search(self.ip_pattern, line, re.IGNORECASE)
if match:
match = match.group()
ip = match.lstrip("client ")
self.ip_list.append(ip)
self.blk_reason['http'].append(ip)
class ScanThreadDoS(ScanThreadBase):
""" scan thread for syn_recv connections """
def __init__(self):
ScanThreadBase.__init__(self)
def run(self):
netstat_comm = "netstat -n | grep tcp | grep SYN_RECV | tail -n {lines}"
netstat_comm = netstat_comm.format(lines=self.line_numbers)
proc = subprocess.Popen(
netstat_comm,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout = proc.communicate()[0]
if IS_PY3:
stdout = stdout.decode()
shell_ret = stdout.rstrip().split("\n")
for line in shell_ret:
line_list = re.split("\s+", line)
if len(line_list) <= 1:
return
match = re.search("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line_list[4], re.IGNORECASE)
if match:
ip = match.group()
self.ip_list.append(ip)
self.blk_reason['synflood'].append(ip)
class BreachBlocker(object):
""" Breachblocker main class """
@staticmethod
def initDB():
""" init SQLite database and fetch data """
dbconn = sqlite3.connect(config.get("global", "db_file"))
dbcursor = dbconn.cursor()
dbcursor.execute("CREATE TABLE IF NOT EXISTS addresses (ip, date, reason)")
dbcursor.execute("CREATE TABLE IF NOT EXISTS whitelist (ip, date)")
dbcursor.execute("CREATE TABLE IF NOT EXISTS history (ip, date)")
try:
dbcursor.execute("ALTER TABLE addresses ADD COLUMN reason")
except sqlite3.OperationalError as e:
pass
dbconn.commit()
dbconn.close()
def __init__(self):
""" Init breachblocker class, set config params, detect firewall and more """
self.write_syslog = write_syslog
self.firewall = Firewall().firewall
self.mode = None
self.rules = None
self._ips_to_block = None
self._blk_cause = None
self._blk_reason = {
"ssh": [],
"ftp": [],
"mail": [],
"smtp": [],
"http": [],
"blacklist": [],
"synflood": []
}
self._fw_updated = False
def printError(self, string):
""" Prints and logs error message """
print("ERROR: %s" % string)
if self.write_syslog:
syslog.syslog(syslog.LOG_ERR, string)
sys.exit(1)
def checkOS(self):
""" check for correct os version """
rel_file = "/etc/redhat-release"
found_centos = False
if os.path.isfile(rel_file):
file_content = open(rel_file).readline()
found_centos = re.search("centos( linux)? release (6|7)", file_content, re.IGNORECASE)
found_freebsd = re.search("freebsd(10|11|12)", sys.platform, re.IGNORECASE)
if not found_centos and not found_freebsd:
self.printError(
"Operating System is invalid. " +
"This script runs only on RHEL/CentOS Linux version 6/7 or FreeBSD 10/11/12"
)
if found_centos:
self.mode = "rhel"
elif found_freebsd:
self.mode = "freebsd"
def loadRules(self):
""" load rules from directory """
nosupp = "The specified server/rules (%s) is/are not supported on this OS."
if http_svr not in supp_servers[self.mode]:
self.printError(nosupp % http_svr)
if mail_svr not in supp_servers[self.mode]:
self.printError(nosupp % mail_svr)
if smtp_svr not in supp_servers[self.mode]:
self.printError(nosupp % smtp_svr)
if ftp_svr not in supp_servers[self.mode]:
self.printError(nosupp % ftp_svr)
if ssh_svr not in supp_servers[self.mode]:
self.printError(nosupp % ssh_svr)
self.rules = {
"http": self._parseRule(self.mode, http_svr),
"mail": self._parseRule(self.mode, mail_svr),
"smtp": self._parseRule(self.mode, smtp_svr),
"ftp": self._parseRule(self.mode, ftp_svr),
"ssh": self._parseRule(self.mode, ssh_svr)
}
def _parseRule(self, osname, svrname):
""" parse the given rule and return dict """
rulesdir = os.path.abspath(os.path.dirname(__file__))
ruleconf = configparser.ConfigParser()
ruleconf.read(os.path.join(rulesdir, "rules", "%s_%s.conf" % (osname, svrname)))
return {
"rc": re.split("\s{1,}|\n", ruleconf.get("rule", "rc")),
"log": ruleconf.get("rule", "log"),
"regex_fail": ruleconf.get("rule", "regex_fail"),
"regex_host": ruleconf.get("rule", "regex_host"),
}
def testRC(self, ruletype):
""" test for existing server binary used in ruleset """
conf = self.rules[ruletype]
if conf["rc"] is None or conf['rc'] == "":
return True
for entry in conf['rc']:
if os.path.isfile(entry):
return True
return False
def checkSoftware(self):
""" check for invalid defined servers """
errormsg = ""
websvr_found = False
mailsvr_found = False
smtpsvr_found = False
ftpsvr_found = False
sshsvr_found = False
if scan_http:
websvr_found = self.testRC("http")
if not websvr_found:
errormsg += "Web server not found: " + http_svr + "\n"
if scan_mail:
mailsvr_found = self.testRC("mail")
if not mailsvr_found:
errormsg += "POP/IMAP server not found: " + mail_svr + "\n"
if scan_smtp:
smtpsvr_found = self.testRC("smtp")
if not smtpsvr_found:
errormsg += "SMTP server not found: " + smtp_svr + "\n"
if scan_ftp:
ftpsvr_found = self.testRC("ftp")
if not ftpsvr_found:
errormsg += "FTP server not found: " + ftp_svr + "\n"
if scan_ssh:
sshsvr_found = self.testRC("ssh")
if not sshsvr_found:
errormsg += "SSH server not found: " + ssh_svr + "\n"
if errormsg != "":
errormsg += "\n"
errormsg += "Supported servers on this platform:\n"
for entry in supp_servers[self.mode]:
errormsg += "\t- %s\n" % entry
self.printError(errormsg)
else:
self.http_svr_data = {
"log": self.rules['http']['log'],
"log_pattern": self.rules['http']['regex_fail'],
"ip_pattern": self.rules['http']['regex_host']
}
self.mail_svr_data = {
"log": self.rules['mail']['log'],
"log_pattern": self.rules['mail']['regex_fail'],
"ip_pattern": self.rules['mail']['regex_host']
}
self.smtp_svr_data = {
"log": self.rules['smtp']['log'],
"log_pattern": self.rules['smtp']['regex_fail'],
"ip_pattern": self.rules['smtp']['regex_host']
}
self.ftp_svr_data = {
"log": self.rules['ftp']['log'],
"log_pattern": self.rules['ftp']['regex_fail'],
"ip_pattern": self.rules['ftp']['regex_host']
}
self.ssh_svr_data = {
"log": self.rules['ssh']['log'],
"log_pattern": self.rules['ssh']['regex_fail'],
"ip_pattern": self.rules['ssh']['regex_host']
}
def checkLogfiles(self):
""" check if the specified log files do exist """
if self.http_svr_data and scan_http:
if not os.path.isfile(self.http_svr_data['log']):
self.printError("HTTP log file " + self.http_svr_data['log'] + " not found")
if self.ftp_svr_data and scan_ftp:
if not os.path.isfile(self.ftp_svr_data['log']):
self.printError("FTP log file " + self.ftp_svr_data['log'] + " not found")
if self.ssh_svr_data and scan_ssh:
if not os.path.isfile(self.ssh_svr_data['log']):
self.printError("SSH log file " + self.ssh_svr_data['log'] + " not found")
if self.mail_svr_data and scan_mail:
if not os.path.isfile(self.mail_svr_data['log']):
self.printError("MAIL log file " + self.mail_svr_data['log'] + " not found")
if self.smtp_svr_data and scan_smtp:
if not os.path.isfile(self.smtp_svr_data['log']):
self.printError("SMTP log file " + self.smtp_svr_data['log'] + " not found")
def scan(self):
""" do the hard work, scan files for intruders """
print("Scanning for IPs to block... ", end="", flush=True)
ip_list = []
self._ips_to_block = []
self._blk_cause = self._blk_reason
ssh_thread = ScanThreadSSH()
mail_thread = ScanThreadMail()
smtp_thread = ScanThreadSMTP()
ftp_thread = ScanThreadFTP()
http_thread = ScanThreadHTTP()
synrecv_thread = ScanThreadDoS()
if self.ssh_svr_data and scan_ssh:
ssh_thread.log = self.ssh_svr_data['log']
ssh_thread.log_pattern = self.ssh_svr_data['log_pattern']
ssh_thread.ip_pattern = self.ssh_svr_data['ip_pattern']
ssh_thread.blk_reason = self._blk_reason
ssh_thread.ip_list = ip_list
ssh_thread.start()
if self.mail_svr_data and scan_mail:
mail_thread.log = self.mail_svr_data['log']
mail_thread.log_pattern = self.mail_svr_data['log_pattern']
mail_thread.ip_pattern = self.mail_svr_data['ip_pattern']
mail_thread.blk_reason = self._blk_reason
mail_thread.ip_list = ip_list
mail_thread.start()
if self.smtp_svr_data and scan_smtp:
smtp_thread.log = self.smtp_svr_data['log']
smtp_thread.log_pattern = self.smtp_svr_data['log_pattern']
smtp_thread.ip_pattern = self.smtp_svr_data['ip_pattern']
smtp_thread.blk_reason = self._blk_reason
smtp_thread.ip_list = ip_list
smtp_thread.start()
if self.ftp_svr_data and scan_ftp:
ftp_thread.log = self.ftp_svr_data['log']
ftp_thread.log_pattern = self.ftp_svr_data['log_pattern']
ftp_thread.ip_pattern = self.ftp_svr_data['ip_pattern']
ftp_thread.blk_reason = self._blk_reason
ftp_thread.ip_list = ip_list
ftp_thread.start()
if self.http_svr_data and scan_http:
http_thread.log = self.http_svr_data['log']
http_thread.log_pattern = self.http_svr_data['log_pattern']
http_thread.ip_pattern = self.http_svr_data['ip_pattern']
http_thread.blk_reason = self._blk_reason
http_thread.ip_list = ip_list
http_thread.start()
if scan_synrecv:
synrecv_thread.blk_reason = self._blk_reason
synrecv_thread.ip_list = ip_list
synrecv_thread.start()
while (ssh_thread.is_alive() or
mail_thread.is_alive() or
smtp_thread.is_alive() or
ftp_thread.is_alive() or
http_thread.is_alive() or
synrecv_thread.is_alive()):
time.sleep(0.1)
unique_ip_counts = defaultdict(int)
for x in ip_list:
unique_ip_counts[x] += 1
for ip, num in unique_ip_counts.items():
if num > attempts:
self._ips_to_block.append(ip)
for ip in self._getBlacklistAddresses():
self._ips_to_block.append(ip)
self._blk_cause['blacklist'].append(ip)
for key, value in self._blk_reason.items():
unique_ip_counts = defaultdict(int)
for x in value:
unique_ip_counts[x] += 1
for ip in unique_ip_counts:
try:
ip = socket.gethostbyname(ip)
self._blk_cause[key].append(ip)
except Exception as e:
pass
print("\033[32mdone.\033[0m")
def _getBlacklistAddresses(self):
""" get blacklisted ip addresses from config """
if blacklist == "":
return []
blist = blacklist
if blacklist.startswith("file:"):
filename = blacklist.replace("file:", "")
if not os.path.isfile(filename):
raise FileNotFoundError("Could not find blacklist: {file}".format(file=filename))
blist = open(filename, "r").read()
blist = re.split("\s{1,}|\n", blist.strip())
return blist
def _checkWhitelist(self, host):
""" check if host is in config whitelist """
if whitelist == "":