-
Notifications
You must be signed in to change notification settings - Fork 2
/
instigator.py
executable file
·3497 lines (2783 loc) · 135 KB
/
instigator.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 python3
# Needs Python 3.5 or newer!
'''
=========================================================================================
instigator.py: v7.30-20190111 Copyright (C) 2018-19 Chris Buijs <[email protected]>
=========================================================================================
Python DNS Forwarder/Proxy with security and filtering features
GitHub: https://github.com/cbuijs/instigator
This is a little study to build a DNS server in Python including some features:
- Blacklist/Whitelist DNS queries and responses based on domain, ip or regex
- Blacklisted DNS queries never leave the building
... to be elaborated. Maybe never ...
ToDo/Ideas:
- Loads ...
- Use configuration file in easy format to configure Instigator. Status: Partly Done.
- Logging only option (no blocking). Status: Partly Done.
- Better Documentation / Remarks / Comments. Status: Ongoing.
- Optimize code for better cache/resolution performance. Status: Ongoing.
- Cleanup code and optimize. Some of it is hacky-quick-code. Status: Ongoing.
- Switch to dnspython or more modern lib as DNS 'engine'. Status: Backburner.
- DNSSEC support (validation only), like DNSMasq (Needs DNSPython). Status: Backburner.
- Itterative resolution besides only forwarding (as is today). Status: Backburner.
- Add more security-features against hammering, dns-drip, ddos, etc. Status: Backburner.
- Fix SYSLOG on MacOS. Status: To-be-done.
- Redo randomness blocking, Status: Backburner/Disabled.
- Options per entry to have more precise blocking, Status: Backburner.
- TTL with value -1 will be statically cached. Status: Done/Finetuning.
- Load BIND style DB zones into static cache. Status: Partially-Done/Finetuning.
- Unduplicate some calls (like Cache-Maintence). Status: Maybe-Fixed/Done.
- Use regex for defaults and other domain-based aliases. Status: To-be-done.
=========================================================================================
'''
# Standard modules
import os, time, shelve, dbm, gc # DBM used for Shelve
gc.enable() # Enable garbage collection
# sys module and path, adapt for your system. Below if for Debian 9.5 Stable
import sys
sys.path.append('/usr/local/lib/python3.5/dist-packages/')
# Random
import random
random.seed(os.urandom(256))
# Syslogging / Logging
import syslog
syslog.openlog(ident='INSTIGATOR', logoption=syslog.LOG_NOWAIT)
logfile = '/opt/instigator/instigator.log'
flogfile = False
if logfile:
flogfile = open(logfile, 'a', 1)
# DNSLib module
from dnslib import *
from dnslib.server import *
# Regex module
import regex
# Use cymruwhois for SafeDNS ASN lookups
from cymruwhois import Client
# Use zxcvbn to determine guessability. The harder, it probably is more random. To catch DGA.
#from zxcvbn import zxcvbn
#from zxcvbn.matching import add_frequency_lists
# Use requests to fetch lists online
import requests
# Ordered Dictionaries
from collections import OrderedDict
# Simple caches
from cachetools import TTLCache
# Use module PyTricia for CIDR/Subnet stuff
import pytricia
###################
# Debugging
debug = False
if sys.argv[1:]: # Any argument on command-line will put debug-mode on, printing all messages to TTY.
debug = True
# Logging Message-length
msglength = 1024
# Base/Work dirs
basedir = '/'.join(os.path.realpath(__file__).split('/')[0:-1]) + '/'
# Config
configfile = basedir + 'instigator.conf'
# Resolv.conf file
resolvfile = False
#resolvfile = '/etc/resolv.conf'
# Listen for queries
#listen_on = list(['192.168.1.251@53', '127.0.0.1@53']) # IPv4 only for now.
#listen_on = list(['172.16.1.251@53', '127.0.0.1@53']) # IPv4 only for now.
listen_on = list(['@53']) # Listen on all interfaces/ip's
#listen_on = list(['127.0.0.1@53']) # IPv4 only for now.
# Forwarding queries to
# See list of servers here: https://www.lifewire.com/free-and-public-dns-servers-2626062
forward_timeout = 3 # Seconds, keep on 5 seconds or higher
forward_servers = dict()
#forward_servers['.'] = list(['1.1.1.1@53','1.0.0.1@53']) # DEFAULT Cloudflare !!! TTLs inconsistent !!!
#forward_servers['.'] = list(['9.9.9.9@53','149.112.112.112@53']) # DEFAULT Quad9 !!! TTLs inconsistent !!!
#forward_servers['.'] = list(['128.52.130.209@53']) # DEFAULT OpenNIC MIT
# Alternatives:
#forward_servers['.'] = list(['9.9.9.10@53', '149.112.112.10@53', '1.1.1.1@53', '1.0.0.1@53', '8.8.8.8@53', '8.8.4.4@53']) # Default Quad9/CloudFlare/Google (Unfiltered versions)
#forward_servers['.'] = list(['172.16.1.1@53']) # DEFAULT Eero/Gateway
#forward_servers['.'] = list(['172.16.1.1@53','9.9.9.9@53', '149.112.112.112@53']) # DEFAULT Eero/Gateway fallback Quad9
#forward_servers['.'] = list(['172.16.1.1@53','209.244.0.3@53','209.244.0.4@53']) # DEFAULT Eero/Gateway plus fallback level-3
#forward_servers['.'] = list(['209.244.0.3@53','209.244.0.4@53']) # DEFAULT Level-3
#forward_servers['.'] = list(['8.8.8.8@53','8.8.4.4@53']) # DEFAULT Google !!! TTLs inconsistent !!!
#forward_servers['.'] = list(['208.67.222.222@443','208.67.220.220@443', '208.67.222.220@443', '208.67.220.222@443']) # DEFAULT OpenDNS
forward_servers['.'] = list(['208.67.222.123@443','208.67.220.123@443']) # DEFAULT OpenDNS FamilyShield
#forward_servers['.'] = list(['8.26.56.26@53','8.20.247.20@53']) # DEFAULT Comodo
#forward_servers['.'] = list(['199.85.126.10@53','199.85.127.10@53']) # DEFAULT Norton
#forward_servers['.'] = list(['64.6.64.6@53','64.6.65.6@53']) # DEFAULT Verisign
#forward_servers['.'] = list(['156.154.70.2@53','156.154.71.2@53']) # DEFAULT Neustar
#forward_servers['.'] = list(['8.34.34.34@53', '8.35.35.35.35@53']) # DEFAULT ZScaler Shift
#forward_servers['.'] = list(['71.243.0.14@53', '68.237.161.14@53']) # DEFAULT Verizon New England area (Boston and NY opt-out)
#forward_servers['.'] = list(['127.0.0.1@53001', '127.0.0.1@53002', '127.0.0.1@53003', '127.0.0.1@53004']) # DEFAULT Stubby
#forward_servers['.'] = list(['172.16.1.1@53053']) # Stubby on router
# Redirect Address, leave empty to generete REFUSED
#redirect_addrs = list()
redirect_addrs = list(['NODATA'])
#redirect_addrs = list(['0.0.0.0', '0000:0000:0000:0000:0000:0000:0000:0000'])
#redirect_addrs = list(['172.16.1.1', '0000:0000:0000:0000:0000:0000:0000:0000'])
#redirect_addrs = list(['172.16.1.251'])
#redirect_addrs = list(['block.frutch'])
#redirect_addrs = list(['172.16.1.1'])
#redirect_addrs = list(['blocked.eero.com']) # test with eero-plus stuff
# ACL's
aclrcode = 'REFUSED'
allow_query4 = pytricia.PyTricia(32)
allow_query4['10.0.0.0/8'] = 'RFC1918 10.0.0.0/8'
allow_query4['127.0.0.1/32'] = 'RFC990 Localhost'
allow_query4['172.16.0.0/12'] = 'RFC1918 172.16.0.0/12'
allow_query4['192.168.0.0/16'] = 'RFC1918 192.168.0.0/16'
allow_query6 = pytricia.PyTricia(128)
allow_query6['::1/128'] = 'RFC4291 Localhost'
# Return-code when query hits a list and cannot be redirected, only use NODATA, NXDOMAIN or REFUSED
hitrcode = 'NODATA'
#hitrcode = 'NXDOMAIN'
#hitrcode = 'REFUSED'
# Only load cached/fast files when not older then maxfileage
maxfileage = 43200 # Seconds
# Files / Lists
savefile = basedir + 'save.shelve'
defaultlist = list([None, 0, '', 0, 0, '']) # reply - expire - qname/class/type - hits - orgttl - comment
lists = OrderedDict()
#lists['blacklist'] = basedir + 'black.list' # Blacklist
lists['blacklist'] = 'https://raw.githubusercontent.com/cbuijs/accomplist/master/standard/black.list' # Blacklist
#lists['whitelist'] = basedir + 'white.list' # Whitelist
lists['whitelist'] = 'https://raw.githubusercontent.com/cbuijs/accomplist/master/standard/white.list' # Whitelist
#lists['ck-blacklist'] = basedir + 'ck-black.list' # Blacklist
#lists['ck-whitelist'] = basedir + 'ck-white.list' # Whitelist
lists['aliases'] = basedir + 'aliases.list' # Aliases/Forwards/TTLS/etc
#lists['malicious-ip'] = basedir + 'malicious-ip.list' # Bad IP's
lists['malicious-ip'] = 'https://raw.githubusercontent.com/cbuijs/accomplist/master/malicious-ip/black.list' # Bad IP's
#lists['tlds'] = basedir + 'tlds.list' # Allowed TLD's, negated regex-list, generates NXDOMAIN for none IANA TLD's
lists['tlds'] = 'https://raw.githubusercontent.com/cbuijs/accomplist/master/chris/tld-black.regex' # Allowed TLD's, negated regex-list, generates NXDOMAIN for none IANA TLD's
lists['nat'] = basedir + 'nat-reflect.list' # Handout local IP's for public names hosted locally
#lists['shalla-ads'] = '/opt/instigator/shallalist/adv/domains'
#lists['shalla-banking'] = '/opt/instigator/shallalist/finance/banking/domains'
#lists['shalla-costtraps'] = '/opt/instigator/shallalist/costtraps/domains'
#lists['shalla-porn'] = '/opt/instigator/shallalist/porn/domains'
#lists['shalla-gamble'] = '/opt/instigator/shallalist/gamble/domains'
#lists['shalla-spyware'] = '/opt/instigator/shallalist/spyware/domains'
#lists['shalla-trackers'] = '/opt/instigator/shallalist/tracker/domains'
#lists['shalla-updatesites'] = '/opt/instigator/shallalist/updatesites/domains'
#lists['shalla-warez'] = '/opt/instigator/shallalist/warez/domains'
#blacklist = list(['blacklist', 'ck-blacklist', 'shalla-ads', 'shalla-costtraps', 'shalla-porn', 'shalla-gamble', 'shalla-spyware', 'shalla-warez', 'malicious-ip'])
#whitelist = list(['whitelist', 'ck-whitelist', 'aliases', 'shalla-banking', 'shalla-updatesites', 'tlds', 'nat'])
blacklist = list(['blacklist', 'shalla-ads', 'shalla-costtraps', 'shalla-porn', 'shalla-gamble', 'shalla-spyware', 'shalla-warez', 'malicious-ip'])
whitelist = list(['whitelist', 'aliases', 'shalla-banking', 'shalla-updatesites', 'tlds', 'nat'])
# Search domains
searchdom = dict()
# Root servers # !!! WIP
#root_servers = list(['198.41.0.4', '2001:503:ba3e::2:30', '199.9.14.201', '2001:500:200::b', '192.33.4.12', '2001:500:2::c', '199.7.91.13', '2001:500:2d::d', '192.203.230.10', '2001:500:a8::e', '192.5.5.241', '2001:500:2f::f', '192.112.36.4', '2001:500:12::d0d', '198.97.190.53', '2001:500:1::53', '192.36.148.17', '2001:7fe::53', '192.58.128.30', '2001:503:c27::2:30', '193.0.14.129', '2001:7fd::1', '199.7.83.42', '2001:500:9f::42', '202.12.27.33', '2001:dc3::35'])
# Cache Settings
nocache = False # Don't change this
cachefile = basedir + 'cache.shelve'
cachesize = 2048 # Entries
cache_maintenance_now = False
cache_maintenance_busy = False
persistentcache = True
# Always load/process lists fully
alwaysfresh = False
# TTL Settings
ttlstrategy = 'last' # average/lowest/highest/random/first/last - Egalize TTL on all RRs in RRSET
filterttl = 900 # Seconds - For filtered/blacklisted/alias entry caching
minttl = 60 # Seconds
maxttl = 86400 # Seconds - 3600 = 1 Hour, 86400 = 1 Day, 604800 = 1 Week
rcodettl = 30 # Seconds - For return-codes caching
failttl = 10 # Seconds - When failure/error happens
retryttl = 10 # Seconds - Retry time
nottl = 0 # Seconds - when no TTL or zero ttl
# Filtering on or off
filtering = True
# Check requests/queries
checkrequest = True # When False, only responses are checked and queries are ignored (passthru)
# Check responses/answers
checkresponse = True # When False, only queries are checked and responses are ignored (passthru)
# Check ASN against black/white lists
checkasn = False
# Logging
logreplies = True # Improves response times a little bit when False
# Minimal Responses
minresp = True
# Minimum/Maximum number of dots in a domain-name
mindots = 1
maxdots = 32
# Roundrobin of address/forward-records
roundrobin = True
forwardroundrobin = True
# Collapse/Flatten CNAME Chains
collapse = True
# Block IPV4 or IPv6 based queries, True = Block, False = NotBlock and None = Based on transport/client-ip
blockv4 = False
blockv6 = None
blockrcode = 'NODATA'
# Block illegal names
blockillegal = True
# Block weird
blockweird = True
# Block subdomains for NODATA, NXDOMAIN, REFUSED and SERVFAIL rcodes received for parent
blocksub = True
# Block queries in search-domains (from /etc/resolv.conf) if entry already exist in cache without searchdomain
blocksearchdom = True
# Block randomized domains
#blockrandom = True
#blockrandommononly = True
#random_threshhold = 42
# Allow "Forced" entries (entries ending in exclaimation mark)
allowforced = True
# Optimize lists, makes startup longer but memory usage and DNS resolution smaller and more efficient
optimizelists = True
# SafeDNS
safedns = False
safednsmononly = True
safednsratio = 50 # Percent
#ipasnfile = basedir + 'ipasn.list'
ipasnfile = 'https://raw.githubusercontent.com/cbuijs/ipasn/master/ipasn-all-cidr-aggregated-complete.dat'
#ipasnfile = False # To disable loading of IPASN and rely on whois
ipasn4 = pytricia.PyTricia(32)
ipasn6 = pytricia.PyTricia(128)
# Block rebinding, meaning that IP-Addresses in responses that match against below ranges,
# must come from a DNS server with an IP-Address also in below ranges
blockrebind = True
rebind4 = pytricia.PyTricia(32)
rebind4['0.0.0.0/8'] = 'Only valid as source'
rebind4['10.0.0.0/8'] = 'Private'
rebind4['127.0.0.0/8'] = 'Loopback'
rebind4['168.254.0.0/16'] = 'Link-Local/APIPA'
rebind4['172.16.0.0/12'] = 'Private'
rebind4['192.0.0.0/24'] = 'Private, Protocol Assignements'
rebind4['192.0.2.0/24'] = 'Documentation/Examples TEST-NET-1'
rebind4['192.168.0.0/16'] = 'Private'
rebind4['198.18.0.0/15'] = 'Private, Benchmarking'
rebind4['198.51.100.0/24'] = 'Documentation/Examples TEST-NET-2'
rebind4['203.0.113.0/24'] = 'Documentation/Examples TEST-NET-3'
rebind4['224.0.0.0/4'] = 'Multicast'
rebind4['240.0.0.0/4'] = 'Reserved (Class-E)'
rebind6 = pytricia.PyTricia(128)
rebind6['::/128'] = 'Reserved/Unspecified'
rebind6['::1/128'] = 'Loopback'
rebind6['2001:db8::/32'] = 'Documentation/Examples'
rebind6['fc00::/7'] = 'Private'
rebind6['fe80::/10'] = 'Link-Local'
rebind6['ff00::/8'] = 'Multicast'
rebind6['ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128'] = True
# Prefetch
prefetch = True
prefetching_busy = False # Gobal Flag, don't change!
prefetchgettime = 10 # Fetch at 1/x-th of TTL time
prefetchhitrate = 120 # 1 cache-hit per xx seconds needed to get prefetched
# Command TLD to interpert as instructions, only allowed from localhost
command = 'command'
# Lists
wl_dom = dict() # Domain whitelist
bl_dom = dict() # Domain blacklist
wl_ip4 = pytricia.PyTricia(32) # IPv4 Whitelist
bl_ip4 = pytricia.PyTricia(32) # IPv4 Blacklist
wl_ip6 = pytricia.PyTricia(128) # IPv6 Whitelist
bl_ip6 = pytricia.PyTricia(128) # IPv6 Blacklist
wl_rx = OrderedDict() # Regex Whitelist
bl_rx = OrderedDict() # Regex Blacklist
wl_asn = dict() # ASN Whitelist
bl_asn = dict() # ASN Blacklist
aliases = OrderedDict() # Aliases
aliases_rx = OrderedDict() # Alias generators/regexes
ttls = OrderedDict() # TTL aliases
defaults = OrderedDict() # NXDomain response replacements
# Work caches
#indom_cache = dict() # Cache results of domain hits
#inrx_cache = dict() # Cache result of regex hits
#match_cache = dict() # Cache results of match_blacklist
#random_cache = dict() # cache results of randomness-calculations
indom_cache = TTLCache(cachesize * 4, filterttl)
inrx_cache = TTLCache(cachesize * 4, filterttl)
match_cache = TTLCache(cachesize * 4, filterttl)
notlisted = TTLCache(cachesize * 4, filterttl)
#random_cache = TTLCache(cachesize * 4, filterttl)
broken_servers = TTLCache(16, retryttl) # Broken DNS Servers
# Clear caches
indom_cache.clear()
inrx_cache.clear()
match_cache.clear()
#random_cache.clear()
# List status match_cache
list_status = dict()
list_status[True] = 'BLACKLISTED'
list_status[False] = 'WHITELISTED'
list_status[None] = 'NOTLISTED'
list_status['NOTCACHED'] = 'NOTCACHED'
# Caches
cache = dict() # DNS cache
result_cache = TTLCache(cachesize * 8, filterttl)
# Pending IDs
pending = dict() # Pending queries
## Regexes
# Use fast (less precisie, sometimes faster) versions of regexes
fastregex = False # Leave False unless really slow system or (very) large datasets
# Regex to filter IP CIDR's out
if fastregex:
ip4regex_text = '([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})*'
ip6regex_text = '([0-9a-f]{1,4}|:)(:([0-9a-f]{0,4})){1,7}(/[0-9]{1,3})*'
else:
ip4regex_text = '((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_text = '(((:(:[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]))*)'
ipregex4 = regex.compile('^' + ip4regex_text + '$', regex.I)
ipregex6 = regex.compile('^' + ip6regex_text + '$', regex.I)
ipregex = regex.compile('^(' + ip4regex_text + '|' + ip6regex_text + ')$', regex.I)
# Regex to filter IP:PORT's out
if fastregex:
ip4portregex_text = '([0-9]{1,3}\.){3}[0-9]{1,3}(@[0-9]{1,5})*'
ip6portregex_text = '([0-9a-f]{1,4}|:)(:([0-9a-f]{0,4})){1,7}(@[0-9]{1,5})*'
else:
ip4portregex_text = '((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}(@(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}|0))*)'
ip6portregex_text = '(((:(:[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})(@(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}|0))*)'
ipportregex4 = regex.compile('^' + ip4portregex_text + '$', regex.I)
ipportregex6 = regex.compile('^' + ip6portregex_text + '$', regex.I)
ipportregex = regex.compile('^(' + ip4portregex_text + '|' + ip6portregex_text + ')$', regex.I)
# Regex for arpa's
ip4arpa_text = '([0-9]{1,3}\.){4}in-addr'
ip6arpa_text = '([0-9a-f]\.){32}ip6'
ip4arpa = regex.compile('^' + ip4arpa_text + '\.arpa$', regex.I)
ip6arpa = regex.compile('^' + ip6arpa_text + '\.arpa$', regex.I)
iparpa = regex.compile('^(' + ip4arpa_text + '|' + ip6arpa_text + ')\.arpa$', regex.I)
# Regex to match domains/hosts in lists
isdomain = regex.compile('(?=^.{1,252}[a-z]$)(^((?!-)[a-z0-9_-]{0,62}[a-z0-9]\.)*(xn--[a-z0-9-]{1,59}|[a-z]{2,63})$)', regex.I)
# Regex to filter regexes out
isregex = regex.compile('^/.*/$')
# Regex for AS(N) Numbers
isasn = regex.compile('^AS[0-9]+$', regex.I)
# Regex for numbers
isnum = regex.compile('^[0-9]+$')
# Has an option
#hasoption = regex.compile('^[a-z0-9,\+\-]+\s*~.*$', regex.I)
##############################################################
def log_info(message):
'''Log INFO messages to syslog'''
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
msg = '{0} {1}'.format(timestamp, message)[:msglength]
if debug:
print(msg)
sys.stdout.flush()
syslog.syslog(syslog.LOG_INFO, message[:msglength]) # !!! Fix SYSLOG on MacOS
if flogfile:
flogfile.write('{0}\n'.format(msg))
return True
def log_err(message):
'''Log ERR messages to syslog'''
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
msg = '{0} !!! PANIC: {1}'.format(timestamp, message)[:msglength]
if debug:
print(msg)
sys.stdout.flush()
syslog.syslog(syslog.LOG_ERR, message[:msglength]) # !!! Fix SYSLOG on MacOS
if flogfile:
flogfile.write('{0}\n'.format(msg))
return True
def file_exist(file, isdb):
'''Check if file exists and return age (in seconds) if so'''
if file:
if isdb and sys.platform.startswith('linux'): # Shelve-DB File
file = file + '.db'
try:
if os.path.isfile(file):
fstat = os.stat(file)
fsize = fstat.st_size
if fsize > 0: # File-size must be greater then zero
mtime = int(fstat.st_mtime)
currenttime = int(time.time())
age = int(currenttime - mtime)
if debug: log_info('FILE-EXIST: {0} = {1} seconds old'.format(file, age))
return age
else:
if debug: log_info('FILE-EXIST: {0} is zero size'.format(file))
except BaseException as err:
log_err('FILE-EXIST-ERROR: {0}'.format(err))
return False
return False
def make_dirs(subdir):
'''Make directory-structures'''
try:
os.makedirs(subdir)
except BaseException:
pass
return True
def match_blacklist(rid, rtype, rrtype, value):
'''Check lists/cache'''
# When reply, only check Requests or RRTypes that have a data-field ending in an IP or Domain-name
if value != '.' and (rtype == 'REQUEST' or (rtype == 'REPLY' and rrtype in ('A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SRV'))):
tag = 'MATCH-FROM-CACHE'
cachekey = query_hash(value, 'IN', rrtype)
result = match_cache.get(cachekey, 'NOTCACHED')
if result == 'NOTCACHED':
result = check_blacklist(rid, rtype, rrtype, value)
if nocache is False:
tag = 'MATCH-TO-CACHE'
match_cache[cachekey] = result
else:
tag = 'MATCH-NO-CACHE'
else:
tag = 'MATCH-NO-CACHE'
result = None
if debug:
log_info('{0} [{1}]: {2} {3}/{4} = {5}'.format(tag, id_str(rid), rtype, value, rrtype, list_status.get(result, 'NOTLISTED')))
return result
def check_blacklist(rid, rtype, rrtype, value):
'''
Check if entry matches a list
Returns:
True = Black-listed
False = White-listed
None = None-listed
'''
if filtering is False:
return None
tid = id_str(rid)
testvalue = value
itisanip = False
# Check if an REVDOM/IP
if rtype == 'REQUEST' and rrtype == 'PTR' and iparpa.search(testvalue):
if not in_domain(testvalue, wl_dom, 'Whitelist', False):
if not in_domain(testvalue, bl_dom, 'Blacklist', False):
ip = False
if ip4arpa.search(testvalue):
ip = '.'.join(testvalue.split('.')[0:4][::-1]) # IPv4
elif ip6arpa.search(testvalue):
ip = ':'.join(filter(None, regex.split('(.{4,4})', ''.join(testvalue.split('.')[0:32][::-1])))) # IPv6
if ip:
# Test IP further on as revdom is not listed
log_info('MATCHING [{0}]: Matching against IP \"{1}\" instead of domain \"{2}\"'.format(tid, ip, testvalue))
itisanip = True
testvalue = ip
else:
return True # Blacklisted
else:
return False # Whitelisted
elif rtype == 'REPLY':
if rrtype in ('A', 'AAAA'):
itisanip = True
elif testvalue.count(' ') > 0:
testvalue = regex.split('\s+', testvalue)[-1] # Take last field as domain-name
log_info('MATCHING [{0}]: Matching against \"{1}\" of \"{2}\" ({3})'.format(tid, testvalue, value, rrtype))
# Check domain-name validity
if not itisanip:
testvalue = normalize_dom(regex.split('\s+', testvalue)[-1]) # If RRType has multiple values in data, take last one
if testvalue.count('.') < mindots:
log_info('BLOCK-MINDOTS-HIT [{0}]: {1} ({2}<{3})'.format(tid, value, testvalue.count('.'), mindots))
return True
elif testvalue.count('.') > maxdots:
log_info('BLOCK-MAXDOTS-HIT [{0}]: {1} ({2}>{3})'.format(tid, value, testvalue.count('.'), maxdots))
return True
elif is_illegal(rtype, testvalue, rrtype):
log_err('BLOCK-ILLEGAL-HIT [{0}]: {1}'.format(tid, value))
return True
elif is_weird(rtype, testvalue, rrtype):
log_info('BLOCK-WEIRD-HIT [{0}]: {1}/{2}'.format(tid, value, rrtype))
return True
#elif blockrandom and (not in_domain(testvalue, wl_dom, 'Whitelist', False)):
# score = randomness(testvalue)
# if blockrandommononly is False and score > random_threshhold: # !!! TEST VALUE BASED ON AVERAGE USE, CHECK THIS !!!
# log_info('BLOCK-RANDOMNESS-HIT [{0}]: {1} ({2}>{3})'.format(tid, value, score, random_threshold))
# return True
# Check against IP-Lists
if itisanip:
if checkasn:
asn, prefix, owner = who_is(testvalue, '[' + tid + '] ' + rtype)
if asn != '0':
if asn in wl_asn: # Whitelist
log_info('WHITELIST-ASN-HIT [{0}]: {1} {2}/{3} matched against \"AS{4}\" ({5}/{6}) - {7}'.format(tid, rtype, value, testvalue, asn, wl_asn[asn], prefix, owner))
return False
elif asn in bl_asn: # Blacklist
log_info('BLACKLIST-ASN-HIT [{0}]: {1} {2}/{3} matched against \"AS{4}\" ({5}/{6}) - {7}'.format(tid, rtype, value, testvalue, asn, wl_asn[asn], prefix, owner))
return True
if is_v6(testvalue):
wip = wl_ip6
bip = bl_ip6
else:
wip = wl_ip4
bip = bl_ip4
found = False
prefix = False
if not testvalue in wip: # Whitelist
if testvalue in bip: # Blacklist
prefix = bip.get_key(testvalue)
found = True
else:
prefix = wip.get_key(testvalue)
if testvalue != value:
testvalue = value + '/' + testvalue
if found:
log_info('BLACKLIST-IP-HIT [{0}]: {1} {2} matched against {3} ({4})'.format(tid, rtype, testvalue, prefix, bip[prefix]))
return True
elif prefix:
log_info('WHITELIST-IP-HIT [{0}]: {1} {2} matched against {3} ({4})'.format(tid, rtype, testvalue, prefix, wip[prefix]))
return False
# Check against Sub-Domain-Lists
elif itisanip is False and testvalue.find('.') > 0 and isdomain.search(testvalue):
fd_found = in_domain(testvalue, forward_servers, 'Forward', False)
if fd_found is not False:
log_info('WHITELIST-{0} [{1}]: {2} \"{3}\" matched against forward-domain \"{4}\"'.format('FORWARD-HIT', tid, rtype, value, fd_found))
return False
sd_found = in_domain(testvalue, searchdom, 'Search', False)
if sd_found is not False:
log_info('WHITELIST-{0} [{1}]: {2} \"{3}\" matched against search-domain \"{4}\"'.format('SEARCH-HIT', tid, rtype, value, sd_found))
return False
for testvalue in (value + '!', value):
if testvalue.endswith('!'):
tag = 'FORCED-HIT'
listname = 'list!'
else:
tag = 'HIT'
listname = 'list'
wl_found = in_domain(testvalue, wl_dom, 'White' + listname, False) # Whitelist
if wl_found is not False:
log_info('WHITELIST-{0} [{1}]: {2} \"{3}\" matched against \"{4}\" ({5})'.format(tag, tid, rtype, value, wl_found, wl_dom[wl_found]))
return False
else:
bl_found = in_domain(testvalue, bl_dom, 'Black' + listname, False) # Blacklist
if bl_found is not False:
log_info('BLACKLIST-{0} [{1}]: {2} \"{3}\" matched against \"{4}\" ({5})'.format(tag, tid, rtype, value, bl_found, bl_dom[bl_found]))
return True
# If it is not an IP, check validity and against regex
if itisanip is False:
# Catchall: Check agains Regex-Lists
rxfound = in_regex(value, wl_rx, False, 'Whitelist') # Whitelist
if rxfound:
log_info('WHITELIST-REGEX-HIT [{0}]: {1} \"{2}\" matched against {3}'.format(tid, rtype, value, rxfound))
return False
rxfound = in_regex(value, bl_rx, False, 'Blacklist') # Blacklist
if rxfound:
log_info('BLACKLIST-REGEX-HIT [{0}]: {1} \"{2}\" matched against {3}'.format(tid, rtype, value, rxfound))
return True
# No hits
if debug: log_info('NONE-HIT [{0}]: {1} \"{2}\" does not match against any lists'.format(tid, rtype, value))
return None
#def randomness(testvalue):
# '''Calculates the Shannon entropy of a string'''
# if testvalue and (not ipregex.search(testvalue)) and (not iparpa.search(testvalue)):
# score = random_cache.get(testvalue, False)
# if score is False:
# prob = [ float(testvalue.count(c)) / len(testvalue) for c in dict.fromkeys(list(testvalue)) ]
# score = - sum([ p * math.log(p) / math.log(2.0) for p in prob ])
#
# random_cache[testvalue] = score
#
# if debug: log_info('RANDOMNESS-TO-CACHE: {0} = {1}'.format(testvalue, score))
# else:
# if debug: log_info('RANDOMNESS-FROM-CACHE: {0} = {1}'.format(testvalue, score))
#
# else:
# score = 0
#
# return score
#def randomness(testvalue):
# '''Calculate randomness'''
# if testvalue and (not ipregex.search(testvalue)) and (not iparpa.search(testvalue)):
# score = random_cache.get(testvalue, False)
# if score is False:
# words = regex.split('[\._-]', testvalue)
# totscore = 0
# for word in words:
# if word[2:] and (not isnum.search(word)):
# randomnessscore = zxcvbn(testvalue)
# totscore += int(round(randomnessscore['guesses_log10'])) # The higher, the more random
# score = int(round(totscore / len(words)))
# random_cache[testvalue] = score
# if debug: log_info('RANDOMNESS-TO-CACHE: {0} = {1}'.format(testvalue, score))
# else:
# if debug: log_info('RANDOMNESS-FROM-CACHE: {0} = {1}'.format(testvalue, score))
# else:
# score = 0
#
# return score
def in_domain(name, domlist, domid, checksub):
'''Check if name is domain or sub-domain'''
domidname = domid + ':' + name
if nocache is False:
indom = indom_cache.get(domidname, None)
if indom is not None:
if indom is True:
if debug: log_info('INDOM-CACHE [{0}]: \"{1}\" in \"{2}\"'.format(domid, name, indom))
else:
if debug: log_info('INDOM-CACHE [{0}]: \"{1}\" is NOMATCH'.format(domid, name))
return indom
if checksub:
testname = name[name.find('.') + 1:]
else:
testname = name
# while testname:
# if testname in domlist:
# indom_cache[domidname] = testname
# return testname
# elif testname.find('.') == -1:
# break
# else:
# testname = testname[testname.find('.') + 1:]
fqdn = False
for label in testname.split('.')[::-1]:
if fqdn:
fqdn = label + '.' + fqdn
else:
fqdn = label
if fqdn in domlist:
indom_cache[domidname] = fqdn
return fqdn
indom_cache[domidname] = False
return False
def in_regex(name, rxlist, isalias, rxid):
'''Check if name is matching regex'''
rxidname = rxid + ':' + name
if nocache is False:
inrx = inrx_cache.get(rxidname, None)
if inrx is not None:
if inrx:
if isalias:
if debug: log_info('INRX-CACHE [{0}]: \"{1}\" -> \"{2}\"'.format(rxid, name, inrx))
else:
if debug: log_info('INRX-CACHE [{0}]: \"{1}\" matched with \"{2}\"'.format(rxid, name, inrx))
return inrx
#if any(rx.search(name) for rx in rxlist.values()):
# return '!!!TEST!!! FOUND IT !!!TEST!!!'
#else:
# return False
if name and name != '.':
#for i in rxlist.keys():
for i in rxlist:
rx = rxlist.get(i, False)
if rx and rx.search(name): # and (not in_domain(name, forward_servers, 'Forward', False)):
elements = regex.split(':\s+', i)
lst = elements[0]
rx2 = ' '.join(elements[1:])
result = False
if isalias:
rx3 = regex.split('\s+', rx2)[0]
result = regex.sub(rx, rx3, name)
log_info('GENERATOR-MATCH [{0}]: \"{1}\" matches \"{2}\" = \"{3}\" -> \"{4}\"'.format(lst, name, rx.pattern, rx3, result))
else:
result = '\"' + rx2 + '\" (' + lst + ')'
if debug: log_info('REGEX-MATCH [{0}]: \"{1}\" matches \"{2}\"'.format(lst, name, result))
inrx_cache[rxidname] = result
return result
inrx_cache[rxidname] = False
return False
def who_is(ip, desc):
'''Whois lookup'''
asn = '0'
owner = 'UNKNOWN'
if is_v6(ip):
if ip in rebind6:
prefix = rebind6.get_key(ip)
owner = 'REBIND {0}'.format(rebind6.get(prefix, owner))
else:
ipasn = ipasn6
prefix = ip + '/128'
else:
if ip in rebind4:
prefix = rebind4.get_key(ip)
owner = 'REBIND {0}'.format(rebind4.get(prefix, owner))
else:
ipasn = ipasn4
prefix = ip + '/32'
if owner == 'UNKNOWN':
if ip in ipasn:
prefix = ipasn.get_key(ip)
elements = regex.split('\s+', ipasn.get(prefix, asn + ' ' + owner))
if elements:
asn = elements[0]
owner = ' '.join(elements[1:])
if debug: log_info('WHOIS-CACHE-HIT: {0} {1} AS{2} ({3}) - {4}'.format(desc, ip, asn, prefix, owner))
else:
log_info('WHOIS-LOOKUP: {0} {1}'.format(desc, ip))
try:
whois = Client()
lookup = whois.lookup(ip)
asn = str(lookup.asn)
except BaseException as err:
log_err('WHOIS-ERROR: {0} {1} - {2}'.format(desc, ip, err))
asn = 'NONE'
if asn != 'NONE' and asn != '' and asn != 'NA' and asn is not None:
prefix = str(lookup.prefix)
owner = str(lookup.owner).upper()
log_info('WHOIS-RESULT: {0} {1} AS{2} ({3}) - {4}'.format(desc, ip, asn, prefix, owner))
else:
asn = '0'
log_info('WHOIS-UNKNOWN: {0}'.format(ip))
ipasn[prefix] = asn + ' ' + owner
return asn, prefix, owner
def strip_reply(request, reply, cip):
'''Strip v4 or v6 addresses from reply'''
rcode = str(RCODE[reply.header.rcode])
if rcode != 'NOERROR' or (not reply.rr):
return reply
hid = id_str(request.header.id)
strip4 = False
strip6 = False
if blockv4 or (blockv4 is None and is_v6(cip) is True):
strip4 = True
if blockv6 or (blockv6 is None and is_v6(cip) is False):
strip6 = True
new_reply = rc_reply(request, rcode)
for record in reply.rr:
rqname = normalize_dom(record.rname)
rqtype = QTYPE[record.rtype]
data = normalize_dom(record.rdata)
#if debug: log_info('STRIP-IP-REPLY-CHECK [{0}]: Checking IP RR \"{1} {2} {3}\" 4:{4}/{5} 6:{6}/{7}'.format(hid, rqname, rqtype, data, blockv4, strip4, blockv6, strip6))
if strip4 and (rqtype == 'A' or ip4arpa.search(rqname) or ipregex4.search(data)):
log_info('STRIP-IPV4-REPLY [{0}]: Stripping IPv4 RR \"{1} {2} {3}\"'.format(hid, rqname, rqtype, data))
elif strip6 and (rqtype == 'AAAA' or ip6arpa.search(rqname) or ipregex6.search(data)):
log_info('STRIP-IPV6-REPLY [{0}]: Stripping IPv6 RR \"{1} {2} {3}\"'.format(hid, rqname, rqtype, data))
else:
#if debug: log_info('STRIP-IP-REPLY [{0}]: Allowed IP RR \"{1} {2} {3}\"'.format(hid, rqname, rqtype, data))
new_reply.add_answer(record)
if not new_reply.rr:
new_reply = rc_reply(request, blockrcode)
return new_reply
def dns_query(request, qname, qtype, use_tcp, tid, cip, checkbl, force):
'''Do query'''
global broken_servers
queryname = qname + '/IN/' + qtype
hid = id_str(tid)
tag = ''
if not ipregex.search(cip):
tag = ' (' + cip + ')'
#if debug and checkbl: queryname = 'BL:' + queryname
#if debug and force: queryname = 'F:' + queryname
# Process already pending/same query
uid = hash(qname + '/' + qtype + '/' + cip + '/' + str(tid))
count = 0
while uid in pending:
count += 1
if count > 4: # Disembark after 5 seconds
_ = pending.pop(uid, None)
reply = from_cache(qname, 'IN', qtype, tid)
if reply is None:
log_info('DNS-QUERY [{0}]: Skipping query for {1} - ID \"{2}\" already processing, takes more then 5 seconds{3}'.format(hid, queryname, hid, tag))
return rc_reply(request, 'SERVFAIL')
else:
return Reply
log_info('DNS-QUERY [{0}]: Delaying (Try #{1}) query for {2} - ID \"{3}\" already in progress, waiting to finish{4}'.format(hid, count, queryname, hid, tag))
time.sleep(1) # Seconds
# Get from cache if any, only hit when doing internal/alias queries
if not force:
reply = from_cache(qname, 'IN', qtype, tid)
if reply is not None:
return reply
# SafeDNS stuff
firstreply = None
asnstack = set()
ipstack = set()
reply = None
rcttl = False
pending[uid] = int(time.time())
server = in_domain(qname, forward_servers, 'Forward', False)
if server:
servername = 'FORWARD-HIT: ' + server
else:
server = '.'
servername = 'DEFAULT'
query = DNSRecord(q=DNSQuestion(qname, getattr(QTYPE, qtype)))
forward_server = forward_servers.get(server, False)
if forward_server:
if forwardroundrobin and len(forward_server) > 1 and safedns is False:
addrs = round_robin(forward_server)
forward_servers[server] = list(addrs)
else:
addrs = forward_server
if safedns:
log_info('SAFEDNS-QUERY [{0}]: Forwarding query from {1} to all forwarders for {2}{3}'.format(hid, cip, queryname, tag))
for addr in addrs:
if addr not in broken_servers:
forward_address = addr.split('@')[0]
if addr.find('@') > 0:
forward_port = int(addr.split('@')[1])
else:
forward_port = 53
if forward_port not in (53, 443, 853, 5353):
if debug: log_info('DNS-TCP: Force using TCP because port is not 53, 443, 853 or 5353 ({0})'.format(forward_port))
tcp_use = True
else:
tcp_use = use_tcp
useip6 = is_v6(forward_address)
error = False
reply = None
# Try 3 times
for loop in range(1, 3):
log_info('DNS-QUERY [{0}]: Forwarding (Try #{1}/3) query from {2} to {3}@{4} ({5}) for {6}{7}'.format(hid, loop, cip, forward_address, forward_port, servername, queryname, tag))
try:
qstart = time.time()
q = query.send(forward_address, forward_port, tcp=tcp_use, timeout=forward_timeout, ipv6=useip6)
qend = time.time()
reply = DNSRecord.parse(q)
if debug: log_info('DNS-RTT [' + hid + ']: ' + str(qend - qstart) + ' seconds' + tag)
break
except BaseException as err:
log_err('DNS-ERROR [{0}]: Issue using DNS Server {1}@{2} for {3} - {4}{5}'.format(hid, forward_address, forward_port, queryname, err, tag))
if err == 'SERVFAIL':
error = err
break
elif loop > 2:
error = err
if reply: