-
Notifications
You must be signed in to change notification settings - Fork 8
/
dns-firewall.py
2401 lines (1896 loc) · 96.8 KB
/
dns-firewall.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================================
dns-firewall.py: v6.123-20180422 Copyright (C) 2018 Chris Buijs <[email protected]>
=========================================================================================
DNS filtering extension for the unbound DNS resolver.
Based on dns_filter.py by Oliver Hitz <[email protected]> and the python
examples providen by UNBOUND/NLNetLabs/Wijngaards/Wouters and others.
At start, it reads the following files:
- blacklist : contains a domain, IP/CIDR or regex (between forward slashes) per line to block.
- whitelist : contains a domain, IP/CIDR or regex (between forward slasges) per line to pass-thru.
Note: IP's will only be checked against responses (see 'checkresponse' below).
For every query sent to unbound, the extension checks if the name is in the
lists and matches. If it is in the whitelist, processing continues
as usual (i.e. unbound will resolve it). If it is in the blacklist, unbound
stops resolution and returns the IP address configured in intercept_address,
or REFUSED reply if left empty.
Note: The whitelist has precedence over blacklist (see 'disablewhitelist' below).
The whitelist and blacklist domain matching is done with every requested domain
and includes it subdomains.
The regex versions will match whatever is defined. It will match sequentially
and stops processing after the first hit.
Caching: this module will cache all black or whitelisted results after processinging to speed
things up, see caching parameters below.
Install and configure:
- Make sure all modules used are availble (check 'from" and 'import" statements above).
- Copy dns-firewall.py to unbound directory.
- If needed, change "intercept_address" below.
- Change unbound.conf as follows:
server:
module-config: "python validator iterator"
python:
python-script: "/unbound/directory/dns-firewall.py"
- Create the above lists as desired (filenames can be modified below).
- Restart unbound.
TODO:
- !!! Better Documentation / Remarks / Comments
=========================================================================================
'''
# Modules
# Make sure modules can be found
import sys
sys.path.append("/usr/local/lib/python2.7/dist-packages/")
# Standard/Included modules
import os, os.path, datetime, gc, subprocess
from thread import start_new_thread
from random import shuffle
from copy import deepcopy
# DNS Resolver (used for SafeDNS)
import dns.resolver
# Enable Garbage collection
gc.enable()
# Use requests module for downloading lists
import requests
# Use module regex instead of re, much faster less bugs
import regex
# Use module pytricia to find ip's in CIDR's dicts fast
import pytricia
# Use CacheTools TTLCache for cache
from cachetools import TTLCache
# Use cymruwhois for SafeDNS ASN lookups
from cymruwhois import Client
# Use IPSet from IPy to aggregate
from IPy import IP, IPSet
##########################################################################################
# Variables/Dictionaries/Etc ...
# logging tag
tag = 'DNS-FIREWALL INIT: '
tagcount = 0
# IP Address to redirect to, leave empty to generate REFUSED
#intercept_address = ''
intercept_address = '192.168.1.250'
intercept_host = 'sinkhole.'
# List files
# Per line you can specify:
# - An IP-Address, Like 10.1.2.3
# - A CIDR-Address/Network, Like: 192.168.1.0/24
# - A Regex (start and end with forward-slash), Like: /^ad[sz]\./
# - A Domain name, Like: bad.company.com
# Lists file to configure which lists to use, one list per line, syntax:
# <Identifier>,<black|white>,<filename|url>[,savefile[,maxlistage[,regex]]]
#lists = False
lists = '/etc/unbound/dns-firewall.lists'
# Lists
blacklist = dict() # Domains blacklist
whitelist = dict() # Domains whitelist
cblacklist4 = pytricia.PyTricia(32) # IPv4 blacklist
cwhitelist4 = pytricia.PyTricia(32) # IPv4 whitelist
cblacklist6 = pytricia.PyTricia(128) # IPv6 blacklist
cwhitelist6 = pytricia.PyTricia(128) # IPv6 whitelist
rblacklist = dict() # Regex blacklist (maybe replace with set()?)
rwhitelist = dict() # Regex whitelist (maybe replace with set()?)
excludelist = dict() # Domain excludelist
asnwhitelist = dict() # ASN Whitelist
asnblacklist = dict() # ASN Blacklist
safeblacklist = dict() # Safe listm anything is this list will not be touched
safewhitelist = dict() # Safe listm anything is this list will not be touched
safeunwhitelist = dict() # Keep unwhitelisted entries safe
# Cache
cachesize = 4096 # Entries
cachettl = 1800 # Seconds
blackcache = TTLCache(cachesize, cachettl)
whitecache = TTLCache(cachesize, cachettl)
asnscorecache = TTLCache(cachesize, cachettl * 8)
asncache4 = pytricia.PyTricia(32)
asncache6 = pytricia.PyTricia(128)
cachefile = '/etc/unbound/cache.file'
# Save
savelists = True
blacksave = '/etc/unbound/blacklist.save'
whitesave = '/etc/unbound/whitelist.save'
# regexlist
fileregex = dict()
fileregexlist = '/etc/unbound/listregexes'
# TLD file
#tldfile = False
tldfile = '/etc/unbound/tlds.list'
tldlist = dict()
# Forcing blacklist, use with caution
disablewhitelist = False
# Filtering on/off
filtering = True
# Unwhitelist domains, keep in mind this can remove whitelisted entries that are blocked by IP.
unwhitelist = False
# Keep state/lock on commands
command_in_progress = False
# Queries within bewlow TLD (commandtld) will be concidered commands to execute
# Only works from localhost (system running UNBOUND)
# Query will return NXDOMAIN or timeout, this is normal.
# Commands availble:
# dig @127.0.0.1 <number>.debug.commandtld - Set debug level to <Number>
# dig @127.0.0.1 save.cache.commandtld - Save cache to cachefile
# dig @127.0.0.1 reload.commandtld - Reload saved lists
# dig @127.0.0.1 update.commandtld - Update/Reload lists
# dig @127.0.0.1 force.update.commandtld - Force Update/Reload lists
# dig @127.0.0.1 force.reload.commandtld - Force fetching/processing of lists and reload
# dig @127.0.0.1 pause.commandtld - Pause filtering (everything passthru)
# dig @127.0.0.1 resume.commandtld - Resume filtering
# dig @127.0.0.1 maintenance.commandtld - Run maintenance
# dig @127.0.0.1 flush.cache.commandtld - Flush caches
# dig @127.0.0.1 <domain>.add.whitelist.commandtld - Add <Domain> to blacklist
# dig @127.0.0.1 <domain>.add.blacklist.commandtld - Add <Domain> to blacklist
# dig @127.0.0.1 <domain>.del.whitelist.commandtld - Remove <Domain> from whitelist
# dig @127.0.0.1 <domain>.del.blacklist.commandtld - Remove <Domain> from blacklist
commandtld = '.command'
# unbound-control, leave empty '' to disable
ucontrol = '/usr/local/sbin/unbound-control -c /etc/unbound/unbound.conf'
# Check answers/responses as well
checkresponse = True
# Maintenance after x queries
maintenance = 100000
# Automatic generated reverse entries for IP-Addresses that are listed
autoreverse = True
# Automatic add non-hits (both black or whitelists) to whitelist cache (only cache!)
autowhitelist = False # !!! Leave False
# Block IPv6 queries/responses
blockv6 = False
# CNAME Collapsing (note: whitelisted entries are not collapsed)
collapse = True
# Allow RFC 2606 TLD's
rfc2606 = False
# Allow common intranet TLD's
intranet = False
# Allow block internet domains
notinternet = False
# Aggregate IP lists, can be slow on large list (more then 5000 entries)
aggregate = True # if false, only child subnets will be removed
# Creaete automatic white-safelist entries that are unwhitelisted
autowhitesafelist = True
# Default maximum age of downloaded lists, can be overruled in lists file
maxlistage = 43200 # In seconds
# Debugging, Levels: 0=Minimal, 1=Default, show blocking, 2=Show all info/processing, 3=Flat out all
# The higher levels include the lower level informations
debug = 2
# Default file regex
defaultfregex = '^(?P<line>.*)$'
# Regex to match IPv4/IPv6 Addresses/Subnets (CIDR)
ip4regex = '((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}(/(3[0-2]|[12]?[0-9]))*)'
ip6regex = '(((:(:[0-9a-f]{1,4}){1,7}|::|[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){1,6}|::|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){1,5}|::|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){1,4}|::|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){1,3}|::|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){1,2}|::|:[0-9a-f]{1,4}(::[0-9a-f]{1,4}|::|:[0-9a-f]{1,4}(::|:[0-9a-f]{1,4}))))))))|(:(:[0-9a-f]{1,4}){0,5}|[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){0,4}|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){0,3}|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4}){0,2}|:[0-9a-f]{1,4}(:(:[0-9a-f]{1,4})?|:[0-9a-f]{1,4}(:|:[0-9a-f]{1,4})))))):(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})(/(12[0-8]|1[01][0-9]|[1-9]?[0-9]))*)'
ipregex = regex.compile('^(' + ip4regex + '|' + ip6regex +')$', regex.I)
#ipregex = regex.compile('^(([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})*|([0-9a-f]{1,4}|:)(:([0-9a-f]{0,4})){1,7}(/[0-9]{1,3})*)$', regex.I)
# Regex to match regex-entries in lists
isregex = regex.compile('^/.*/$')
# Regex for AS(N) number
asnregex = regex.compile('^AS[0-9]+$')
# Regex to match domains/hosts in lists
#isdomain = regex.compile('^[a-z0-9\.\-]+$', regex.I) # According RFC, Internet only
isdomain = regex.compile('^[a-z0-9_\.\-]+$', regex.I) # According RFC plus underscore, works everywhere
# Regex for excluded entries to fix issues
defaultexclude = '^(127\.0\.0\.1(/32)*|::1(/128)*|local(host|net[s]*))$'
exclude = regex.compile(defaultexclude, regex.I)
# Regex for www entries
wwwregex = regex.compile('^(https*|ftps*|www*)[0-9]*\..*$', regex.I)
# SafeDNS - HIGHLY EXPERIMENTAL AND WILL BREAK STUFF, USE AT OWN RISK !!!
# Based on idea/code of NavyTitanium: https://github.com/NavyTitanium/Dns-online-filter
safedns = False
safednsblock = True # When False, only monitoring/reporting
safescore = 50 # (percentage), start blocking when score is below this
nameservers = dict()
nameserverslist = '/etc/unbound/safenameservers'
#ipasnfile = False # When False, whois will be used solely to lookup ASN's
ipasnfile = '/etc/unbound/ipasn.dat'
##########################################################################################
# Check against lists
def in_list(name, bw, type, rrtype):
tag = 'DNS-FIREWALL ' + type + ' FILTER: '
if not filtering:
if (debug >= 2): log_info(tag + 'Filtering disabled, passthru \"' + name + '\" (RR:' + rrtype + ')')
return False
if (bw == 'white') and disablewhitelist:
return False
if blockv6 and ((rrtype == 'AAAA') or name.endswith('.ip6.arpa')):
if (bw == 'black'):
if (debug >= 2): log_info(tag + 'HIT on IPv6 for \"' + name + '\" (RR:' + rrtype + ')')
#add_to_cache(bw, name) # Do not cache, will block non-v6 queries if cached
return True
if not in_cache('white', name):
if not in_cache('black', name):
# Check for IP's
if (type == 'RESPONSE') and rrtype in ('A', 'AAAA'):
cidr = check_ip(name, bw)
if cidr:
if (debug >= 2): log_info(tag + 'HIT on IP \"' + name + '\" in ' + bw + '-listed network ' + cidr)
add_to_cache(bw, name)
return True
else:
return False
else:
# Check against tlds
if (bw == 'black') and tldlist:
tld = name.split('.')[-1:][0]
if not tld in tldlist:
if (debug >= 2): log_info(tag + 'HIT on non-existant TLD \"' + tld + '\" for \"' + name + '\"')
add_to_cache(bw, name)
return True
# Check against domains
testname = name
while True:
if (bw == 'black'):
found = (testname in blacklist)
if found:
id = blacklist[testname]
elif testname != name:
found = (testname in blackcache)
if found:
id = 'CACHE'
else:
found = (testname in whitelist)
if found:
id = whitelist[testname]
elif testname != name:
found = (testname in whitecache)
if found:
id = 'CACHE'
if found:
if (debug >= 2): log_info(tag + 'HIT on DOMAIN \"' + name + '\", matched against ' + bw + '-list-entry \"' + testname + '\" (' + str(id) + ')')
add_to_cache(bw, name)
return True
elif testname.find('.') == -1:
break
else:
testname = testname[testname.find('.') + 1:]
if (debug >= 3): log_info(tag + 'Checking for ' + bw + '-listed parent domain \"' + testname + '\"')
# Match against Regex-es
foundregex = check_regex(name, bw, True)
if foundregex:
if (debug >= 2): log_info(tag + 'HIT on \"' + name + '\", matched against ' + bw + '-regex ' + foundregex +'')
add_to_cache(bw, name)
return True
else:
if (bw == 'black'):
return True
else:
if (bw == 'white'):
return True
return False
# Check if entry is in cache
def in_cache(bw, name):
tag = 'DNS-FIREWALL CACHE FILTER: '
if (bw == 'black'):
if name in blackcache:
if (debug >= 2): log_info(tag + 'Found \"' + name + '\" in black-cache')
return True
else:
if name in whitecache:
if (debug >= 2): log_info(tag + 'Found \"' + name + '\" in white-cache')
return True
return False
# Add matched entry to cache
def add_to_cache(bw, name):
tag = 'DNS-FIREWALL CACHE FILTER: '
if autoreverse:
addarpa = rev_ip(name)
else:
addarpa = False
if (bw == 'black') and name not in blackcache:
if (debug >= 2): log_info(tag + 'Added \"' + name + '\" to black-cache')
blackcache[name] = True
whitecache.pop(name, False)
if addarpa:
if (debug >= 2): log_info(tag + 'Auto-Generated/Added \"' + addarpa + '\" (' + name + ') to black-cache')
blackcache[addarpa] = True
whitecache.pop(addarpa, False)
elif name not in whitecache:
if (debug >= 2): log_info(tag + 'Added \"' + name + '\" to white-cache')
whitecache[name] = True
blackcache.pop(name, False)
if addarpa:
if (debug >= 2): log_info(tag + 'Auto-Generated/Added \"' + addarpa + '\" (' + name + ') to white-cache')
whitecache[addarpa] = True
blackcache.pop(addarpa, False)
return True
# Check against IP lists (called from in_list)
def check_ip(ip, bw):
if (bw == 'black'):
if ip.find(':') == -1:
if ip in cblacklist4:
return cblacklist4[ip]
#return cblacklist4.get_key(ip)
else:
if ip in cblacklist6:
return cblacklist6[ip]
#return cblacklist6.get_key(ip)
else:
if ip.find(':') == -1:
if ip in cwhitelist4:
return cwhitelist4[ip]
#return cwhitelist4.get_key(ip)
else:
if ip in cwhitelist6:
return cwhitelist6[ip]
#return cwhitelist6.get_key(ip)
return False
# Checke against REGEX lists (called from in_list)
def check_regex(name, bw, tld):
tag = 'DNS-FIREWALL REGEX FILTER: '
if (bw == 'black'):
rlist = rblacklist
else:
rlist = rwhitelist
for i in range(0,len(rlist)/3):
checkregex = rlist[i,1]
if (debug >= 3): log_info(tag + 'Checking ' + name + ' against regex \"' + rlist[i,2] + '\"')
if checkregex.search(name):
return '\"' + rlist[i,2] + '\" (' + rlist[i,0] + ')'
return False
# Generate Reverse IP (arpa) domain
def rev_ip(ip):
if ipregex.match(ip):
if ip.find(':') == -1:
arpa = '.'.join(ip.split('.')[::-1]) + '.in-addr.arpa' # Add IPv4 in-addr.arpa
else:
a = ip.replace(':', '')
arpa = '.'.join(a[i:i+1] for i in range(0, len(a), 1))[::-1] + '.ip6.arpa' # Add IPv6 ip6.arpa
return arpa
else:
return False
# Clear lists
def clear_lists():
tag = 'DNS-FIREWALL LISTS: '
global blacklist
global whitelist
global rblacklist
global rwhitelist
global cblacklist4
global cwhitelist4
global cblacklist6
global cwhitelist6
global excludelist
log_info(tag + 'Clearing Lists')
rwhitelist.clear()
whitelist.clear()
excludelist.clear()
for i in cwhitelist4.keys():
cwhitelist4.delete(i)
for i in cwhitelist6.keys():
cwhitelist6.delete(i)
rblacklist.clear()
blacklist.clear()
for i in cblacklist4.keys():
cblacklist4.delete(i)
for i in cblacklist6.keys():
cblacklist6.delete(i)
clear_cache()
return True
# Clear cache
def clear_cache():
tag = 'DNS-FIREWALL CACHE: '
log_info(tag + 'Clearing Cache')
flush_dns_cache('.')
blackcache.clear()
whitecache.clear()
asnscorecache.clear()
for i in asncache4.keys():
asncache4.delete(i)
for i in asncache6.keys():
asncache6.delete(i)
return True
# Maintenance lists, check expiry, reload, etc...
def maintenance_lists(count):
tag = 'DNS-FIREWALL MAINTENACE: '
global command_in_progress
if command_in_progress:
log_info(tag + 'ALREADY PROCESSING')
return True
command_in_progress = True
log_info(tag + 'Maintenance Started')
age = file_exist(whitesave)
if age and age < maxlistage:
age = file_exist(blacksave)
if age and age < maxlistage:
log_info(tag + 'Nothing to do. Done')
command_in_progress = False
return False
log_info(tag + 'Updating Lists')
load_lists(False, True)
log_info(tag + 'Maintenance Done')
command_in_progress = False
return True
# Load lists
def load_lists(force, savelists):
tag = 'DNS-FIREWALL LISTS: '
global blacklist
global whitelist
global rblacklist
global rwhitelist
global cblacklist4
global cwhitelist4
global cblacklist6
global cwhitelist6
global asnwhitelist
global asnblacklist
global tldfile
global excludelist
global exclude
if lists == False:
return True
# Header/User-Agent to use when downloading lists, some sites block non-browser downloads
headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' }
# clear lists if already filled
if (len(blacklist) > 0) or (len(whitelist) > 0):
clear_lists()
# Get top-level-domains
if tldfile:
tldlist.clear()
age = file_exist(tldfile)
if not age or age > maxlistage:
log_info(tag + 'Downloading IANA TLD list to \"' + tldfile + '\"')
r = requests.get('https://data.iana.org/TLD/tlds-alpha-by-domain.txt', headers=headers, allow_redirects=True)
if r.status_code == 200:
try:
with open(tldfile, 'w') as f:
f.write(r.text.encode('ascii', 'ignore').replace('\r', '').lower())
except BaseException as err:
log_err(tag + 'Unable to write to file \"' + tldfile + '\": ' + str(err))
tldfile = False
if tldfile:
log_info(tag + 'Fetching TLD list from \"' + tldfile + '\"')
try:
with open(tldfile, 'r') as f:
for line in f:
entry = line.strip()
if not (entry.startswith("#")) and not (len(entry) == 0):
tldlist[entry] = True
except BaseException as err:
log_err(tag + 'Unable to read from file \"' + tldfile + '\": ' + str(err))
tldfile = False
if tldfile:
if rfc2606:
tldlist['example'] = True
tldlist['invalid'] = True
tldlist['localhost'] = True
tldlist['test'] = True
if notinternet:
tldlist['onion'] = True
if intranet:
tldlist['corp'] = True
tldlist['home'] = True
tldlist['host'] = True
tldlist['lan'] = True
tldlist['local'] = True
tldlist['localdomain'] = True
tldlist['router'] = True
tldlist['workgroup'] = True
log_info(tag + 'fetched ' + str(len(tldlist)) + ' TLDs')
# if intercept_host:
# tldlist[intercept_host.strip('.').split('.')[-1:][0]] = True
if fileregexlist:
log_info(tag + 'Fetching list-regexes from \"' + fileregexlist + '\"')
try:
with open(fileregexlist, 'r') as f:
for line in f:
entry = line.strip()
if not (entry.startswith("#")) and not (len(entry) == 0):
elements = entry.split('\t')
if len(elements) > 1:
name = elements[0].strip().upper()
if (debug >= 2): log_info(tag + 'Fetching file-regex \"@' + name + '\"')
fileregex[name] = elements[1]
else:
log_err(tag + 'Invalid list-regex entry: \"' + entry + '\"')
except BaseException as err:
log_err(tag + 'Unable to read from file \"' + fileregexlist + '\": ' + str(err))
tldfile = False
# Read Lists
readblack = True
readwhite = True
if savelists and not force:
age = file_exist(whitesave)
if age and age < maxlistage and not disablewhitelist:
log_info(tag + 'Using White-Savelist, not expired yet (' + str(age) + '/' + str(maxlistage) + ')')
read_lists('saved-whitelist', whitesave, rwhitelist, cwhitelist4, cwhitelist6, whitelist, asnwhitelist, safewhitelist, safeunwhitelist, True, 'white')
readwhite = False
age = file_exist(blacksave)
if age and age < maxlistage:
log_info(tag + 'Using Black-Savelist, not expired yet (' + str(age) + '/' + str(maxlistage) + ')')
read_lists('saved-blacklist', blacksave, rblacklist, cblacklist4, cblacklist6, blacklist, asnblacklist, safeblacklist, False, True, 'black')
readblack = False
addtoblack = dict()
addtowhite = dict()
try:
with open(lists, 'r') as f:
for line in f:
entry = line.strip().replace('\r', '')
if not (entry.startswith("#")) and not (len(entry) == 0):
element = entry.split('\t')
if len(element) > 2:
id = element[0]
bw = element[1].lower()
if (bw == 'black' and readblack) or (bw == 'white' and readwhite) or (bw == 'exclude' and (readwhite or readblack)):
source = element[2]
downloadfile = False
listfile = False
force = False
url = False
if source.startswith('http://') or source.startswith('https://'):
url = source
if (debug >= 2): log_info(tag + 'Source for \"' + id + '\" is an URL: \"' + url + '\"')
else:
if (debug >= 2): log_info(tag + 'Source for \"' + id + '\" is a FILE: \"' + source + '\"')
if source:
if len(element) > 3:
listfile = element[3]
else:
listfile = '/etc/unbound/' + id.strip('.').lower() + ".list"
if len(element) > 4:
filettl = int(element[4])
else:
filettl = maxlistage
fregex = defaultfregex
if len(element) > 5:
r = element[5]
if r.startswith('@'):
r = r.split('@')[1].upper().strip()
if r in fileregex:
fregex = fileregex[r]
if (debug >= 3): log_info(tag + 'Using \"@' + r + '\" regex/filter for \"' + id + '\" (' + fregex + ')')
else:
log_err(tag + 'Regex \"@' + r + '\" does not exist in \"' + fileregexlist + '\" using default \"' + defaultfregex +'\"')
elif r.find('(?P<') == -1:
log_err(tag + 'Regex \"' + r + '\" does not contain placeholder (e.g: \"(?P< ... )\")')
else:
fregex = r
exclude = regex.compile(defaultexclude, regex.I)
if len(element) > 6:
r = element[6]
if r.startswith('@'):
r = r.split('@')[1].upper().strip()
if r in fileregex:
exclude = regex.compile(fileregex[r], regex.I)
if (debug >= 3): log_info(tag + 'Using \"@' + r + '\" exclude regex/filter for \"' + id + '\" (' + r + ')')
else:
log_err(tag + 'Regex \"@' + r + '\" does not exist in \"' + fileregexlist + '\" using default \"' + defaultexclude +'\"')
else:
exclude = regex.compile(r, regex.I)
#if len(element) > 6:
# exclude = regex.compile('(' + element[6] + '|' + defaultexclude + ')', regex.I)
# if (debug >= 3): log_info(tag + id + ': Using \"' + element[6] + '\" exclude-regex/filter')
if url:
age = file_exist(listfile)
if not age or age > filettl or force:
downloadfile = listfile + '.download'
log_info(tag + 'Downloading \"' + id + '\" from \"' + url + '\" to \"' + downloadfile + '\"')
try:
r = requests.get(url, headers=headers, allow_redirects=True)
if r.status_code == 200:
try:
with open(downloadfile, 'w') as f:
f.write(r.text.encode('ascii', 'ignore').replace('\r', '').strip().lower())
except BaseException as err:
log_err(tag + 'Unable to write to file \"' + downloadfile + '\": ' + str(err))
else:
log_err(tag + 'Error during downloading from \"' + url + '\"')
except BaseException as err:
log_err(tag + 'Error downloading from \"' + url + '\": ' + str(err))
else:
log_info(tag + 'Skipped download \"' + id + '\" previous list \"' + listfile + '\" is only ' + str(age) + ' seconds old')
source = listfile
if url and downloadfile:
sourcefile = downloadfile
else:
sourcefile = source
if file_exist(sourcefile) >= 0:
if sourcefile != listfile:
try:
log_info(tag + 'Creating \"' + id + '\" file \"' + listfile + '\" from \"' + sourcefile + '\"')
with open(sourcefile, 'r') as f:
try:
with open(listfile, 'w') as g:
for line in f:
line = line.replace('\r', '').lower().strip()
if line and len(line) >0:
if not exclude.match(line):
matchentry = regex.match(fregex, line, regex.I)
if matchentry:
for placeholder in ['asn', 'domain', 'entry', 'ip', 'line', 'regex']:
try:
entry = matchentry.group(placeholder)
except:
entry = False
if entry and len(entry) > 0:
if not exclude.match(entry):
# !!! To do: use placholder to pre-process/validate/error-check type of entry via regex
#print placeholder, entry
g.write(entry)
g.write('\n')
else:
if (debug >= 3): log_info(tag + id +': Skipping excluded entry \"' + line + '\" (' + entry + ')')
else:
if (debug >= 3): log_info(tag + id +': Skipping non-matched line \"' + line + '\"')
else:
if (debug >= 3): log_info(tag + id +': Skipping excluded line \"' + line + '\"')
except BaseException as err:
log_err(tag + 'Unable to write to file \"' + listfile + '\" (' + str(err) + ')')
except BaseException as err:
log_err(tag + 'Unable to read source-file \"' + sourcefile + '\" (' + str(err) + ')')
else:
log_info(tag + 'Skipped processing of \"' + id + '\", source-file \"' + sourcefile + '\" same as list-file')
else:
log_info(tag + 'Skipped \"' + id + '\", source-file \"' + sourcefile + '\" does not exist')
if file_exist(listfile) >= 0:
if bw == 'black':
read_lists(id, listfile, rblacklist, cblacklist4, cblacklist6, blacklist, asnblacklist, safeblacklist, False, force, bw)
elif bw == 'white':
if not disablewhitelist:
read_lists(id, listfile, rwhitelist, cwhitelist4, cblacklist6, whitelist, asnwhitelist, safewhitelist, safeunwhitelist, force, bw)
elif bw == 'exclude':
excount = 0
try:
with open(listfile, 'r') as f:
for line in f:
elements = line.strip().replace('\r', '').split('\t')
entry = elements[0]
if (len(entry) > 0) and isdomain.match(entry):
if len(elements)>1:
action = elements[1]
else:
action = 'exclude'
if action == 'black':
addtoblack[entry] = id
elif action == 'white':
addtowhite[entry] = id
excludelist[entry] = id
excount += 1
log_info(tag + 'Fetched ' + str(excount) + ' exclude entries from \"' + listfile + '\" (' + id + ')')
except BaseException as err:
log_err(tag + 'Unable to read list-file \"' + listfile + '\" (' + str(err) + ')')
else:
log_err(tag + 'Unknow type \"' + bw + '\" for file \"' + listfile + '\"')
else:
log_err(tag + 'Cannot open \"' + listfile + '\"')
else:
log_info(tag + 'Skipping ' + bw + 'list \"' + id + '\", using savelist')
else:
log_err(tag + 'Not enough arguments: \"' + entry + '\"')
except BaseException as err:
log_err(tag + 'Unable to open file \"' + lists + '\": ' + str(err))
# Redirect entry, we don't want to expose it
blacklist[intercept_host.strip('.')] = 'Intercept_Host'
# Excluding domains, first thing to do on "dirty" lists
if excludelist and (readblack or readwhite):
# Optimize excludelist
excludelist = optimize_domlists(excludelist, 'ExcludeDoms')
# Remove exclude entries from lists
whitelist = exclude_domlist(whitelist, excludelist, 'WhiteDoms')
blacklist = exclude_domlist(blacklist, excludelist, 'BlackDoms')
# Add exclusion entries when requested
whitelist = add_exclusion(whitelist, addtowhite, safewhitelist, 'WhiteDoms')
blacklist = add_exclusion(blacklist, addtoblack, safeblacklist, 'BlackDoms')
# Optimize/Aggregate white domain lists (remove sub-domains is parent exists and entries matchin regex)
if readwhite:
whitelist = optimize_domlists(whitelist, 'WhiteDoms')
cwhitelist4 = aggregate_ip(cwhitelist4, 'WhiteIP4s')
cwhitelist6 = aggregate_ip(cwhitelist6, 'WhiteIP6s')
write_out('/etc/unbound/whitelist.full', False)
whitelist = unreg_lists(whitelist, rwhitelist, safewhitelist, 'WhiteDoms')
# Optimize/Aggregate black domain lists (remove sub-domains is parent exists and entries matchin regex)
if readblack:
blacklist = optimize_domlists(blacklist, 'BlackDoms')
cblacklist4 = aggregate_ip(cblacklist4, 'BlackIP4s')
cblacklist6 = aggregate_ip(cblacklist6, 'BlackIP6s')
write_out(False, '/etc/unbound/blacklist.full')
blacklist = unreg_lists(blacklist, rblacklist, safeblacklist, 'BlackDoms')
# Remove whitelisted entries from blacklist
if readblack or readwhite:
blacklist = uncomplicate_lists(whitelist, rwhitelist, blacklist, safeblacklist)
cblacklist4 = uncomplicate_ip_lists(cwhitelist4, cblacklist4, 'IPv4')
cblacklist6 = uncomplicate_ip_lists(cwhitelist6, cblacklist6, 'IPv6')
whitelist = unwhite_domain(whitelist, blacklist)
cwhitelist4 = unwhite_ip(cwhitelist4, cblacklist4, 'IPv4 List')
cwhitelist6 = unwhite_ip(cwhitelist6, cblacklist6, 'IPv6 List')
# Reporting
regexcount = str(len(rwhitelist)/3)
ipcount = str(len(cwhitelist4) + len(cwhitelist6))
domaincount = str(len(whitelist))
asncount = str(len(asnwhitelist))
log_info(tag + 'WhiteList Totals: ' + regexcount + ' REGEXES, ' + ipcount + ' IPs/CIDRs, ' + domaincount + ' DOMAINS and ' + asncount + ' ASNs')
regexcount = str(len(rblacklist)/3)
ipcount = str(len(cblacklist4) + len(cblacklist6))
domaincount = str(len(blacklist))
asncount = str(len(asnblacklist))
log_info(tag + 'BlackList Totals: ' + regexcount + ' REGEXES, ' + ipcount + ' IPs/CIDRs, ' + domaincount + ' DOMAINS and ' + asncount + ' ASNs')
# Save processed list for distribution
write_out(whitesave, blacksave)
# Clean-up after ourselfs
gc.collect()
return True
# Add exclusions to lists
def add_exclusion(dlist, elist, slist, listname):
tag = 'DNS-FIREWALL LISTS: '
before = len(dlist)
for domain in dom_sort(elist.keys()):
id = elist[domain]
if (debug >= 2): log_info(tag + 'Adding excluded entry \"' + domain + '\" to ' + listname + ' (from ' + id + ')')
if domain in dlist:
if dlist[domain].find(id) == -1:
dlist[domain] = dlist[domain] + ', ' + id
else:
dlist[domain] = id
slist[domain] = dlist[domain]
after = len(dlist)
count = after - before
if (debug >= 2): log_info(tag + 'Added ' + str(count) + ' new exclusion entries to \"' + listname + '\", went from ' + str(before) + ' to ' + str(after))
return dlist
# Read file/list
def read_lists(id, name, regexlist, iplist4, iplist6, domainlist, asnlist, safelist, safewlist, force, bw):
tag = 'DNS-FIREWALL LISTS: '
orgid = id
if (len(name) > 0):
try:
with open(name, 'r') as f:
log_info(tag + 'Reading ' + bw + '-file/list \"' + name + '\" (' + id + ')')
orgregexcount = (len(regexlist)/3-1)+1
regexcount = orgregexcount
ipcount = 0
domaincount = 0
asncount = 0
skipped = 0
total = 0
for line in f:
entry = line.split('#')[0].strip().replace('\r', '')
if len(entry) > 0 and (not entry.startswith('#')):
id = orgid
elements = entry.split('\t')
if len(elements) > 1:
entry = elements[0]
if elements[1]:
id = elements[1]
safed = False
if (safelist != False) and entry.endswith('!'):
entry = entry[:-1]
#print "SAFE:", bw, entry
safed = True
unwhite = False
if (not safed) and (unwhitelist != False) and entry.endswith('&'):
entry = entry[:-1]
#print "UNWHITE:", bw, entry
unwhite = True
total += 1
if (isregex.match(entry)):
# It is an Regex
cleanregex = entry.strip('/')
try:
regexlist[regexcount,1] = regex.compile(cleanregex, regex.I)
regexlist[regexcount,0] = str(id)
regexlist[regexcount,2] = cleanregex
regexcount += 1
except:
log_err(tag + name + ': Skipped invalid line/regex \"' + entry + '\"')
pass
elif (asnregex.match(entry.upper())):
if checkresponse and safedns: