-
Notifications
You must be signed in to change notification settings - Fork 3
/
adns_server.py
executable file
·1767 lines (1426 loc) · 59.7 KB
/
adns_server.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
"""
An Authoritative DNS server for prototyping and experimentation.
Author: Shumon Huque <[email protected]>
"""
import os
import sys
import getopt
import pwd
import grp
import syslog
import struct
import socket
import atexit
import select
import threading
import signal
import hashlib
import base64
import time
import enum
import random
import binascii
import yaml
import siphash
import dns.zone
import dns.name
import dns.message
import dns.flags
import dns.rcode
import dns.rdatatype
import dns.rdataclass
import dns.query
import dns.edns
import dns.dnssec
from dns.rdtypes.ANY import NSEC
from dns.rdtypes.ANY import NSEC3
from sortedcontainers import SortedDict
from cryptography.hazmat.primitives.serialization import load_pem_private_key
PROGNAME = os.path.basename(sys.argv[0])
VERSION = '0.5.1'
CONFIG_DEFAULT = 'adnsconfig.yaml'
# Parameters for online signing
RRSIG_INCEPTION_OFFSET = 3600
RRSIG_LIFETIME = 172800
# Cookie parameters
COOKIE_TIMESTAMP_DRIFT = 86400 # Allowed DNS Cookie timestamp drift (secs)
COOKIE_RECALCULATE_TIME = 21600
class RRtype(enum.IntEnum):
"""Resource Record types"""
NXNAME = 128
DELEG = 65287
class EdnsFlag(enum.IntFlag):
"""EDNS Header Flags"""
DNSSEC_OK = 0x8000
COMPACT_OK = 0x4000
DELEG_OK = 0x2000
class EDECode(enum.IntEnum):
"""Extended DNS Error Codes"""
INVALID_QTYPE = 30
class Finished(enum.Flag):
"""Finished Boolean enum"""
TRUE = True
FALSE = False
class Preferences:
"""Preferences"""
config = CONFIG_DEFAULT # -c: Configuration file
debug = False # -d: Print debugging output
server = '' # -s: server listening address
server_af = None # server's address family if -s set
port = 53 # -p: port
username = None # username to switch to (if root)
groupname = None # group to switch to (if root)
daemon = True # Become daemon (-f: foreground)
syslog_fac = syslog.LOG_DAEMON # Syslog facility
syslog_pri = syslog.LOG_INFO # Syslog priority
workdir = None # Working directory to change to
pidfile = None # PID file
edns_udp_max = 1432 # -e: Max EDNS UDP payload we send
edns_udp_adv = 1232 # Max EDNS UDP payload we advertise
nsid = None # NSID option string
minimal_any = False # Minimal ANY (RFC 8482)
cookie_secret = None # Secret for DNS cookie generation
def __str__(self):
return "<Preferences object>"
def usage(msg=None):
"""Print usage string and exit"""
if msg is not None:
print(f"ERROR: {msg}\n")
print(f"""\
{PROGNAME} version {VERSION}
Usage: {PROGNAME} [<Options>]
Options:
-h: Print usage string
-c file: Configuration file (default '{CONFIG_DEFAULT}')
-d: Turn on debugging
-p N: Listen on port N (default 53)
-s A: Bind to server address A (default wildcard address)
-u uname: Drop privileges to UID of specified username
(if server started running as root)
-g group: Drop provileges to GID of specified groupname
(if server started running as root)
-4: Use IPv4 only
-6: Use IPv6 only
-f: Remain attached to foreground (default don't)
-e N: Max EDNS bufsize in octets for responses we send out.
(-e 0 will disable EDNS support)
Note: a configuration file that minimally specifies the zones to load
must be present.
""")
sys.exit(1)
def init_config(prefs, zonedict, only_zones=False):
"""Initialize parameters and zone files from config file"""
with open(prefs.config, 'r', encoding="utf-8") as configfile:
ydoc = yaml.safe_load(configfile)
if not only_zones:
if "config" in ydoc:
for key, val in ydoc['config'].items():
if key == 'port':
prefs.port = val
elif key == 'workdir':
prefs.workdir = val
elif key == 'pidfile':
prefs.pidfile = val
elif key == 'edns':
prefs.edns_udp_max = val
elif key == 'user':
prefs.username = val
elif key == 'group':
prefs.groupname = val
elif key == 'nsid':
prefs.nsid = val.encode()
elif key == 'minimal_any':
prefs.minimal_any = val
else:
print(f"error: unrecognized config option: {key}")
sys.exit(1)
if "zones" in ydoc:
load_zones(prefs, zonedict, ydoc['zones'])
if not zonedict.get_zonelist():
print("error: no zones defined.")
sys.exit(1)
def load_zones(prefs, zonedict, zoneconfig):
"""Load zones"""
for entry in zoneconfig:
zonename = entry['name']
zonefile = entry['file']
if not zonefile.startswith('/') and prefs.workdir:
zonefile = os.path.join(prefs.workdir, zonefile)
dnssec = entry.get('dnssec', False)
dynamic_signing = entry.get('dynamic_signing', False)
compact_denial = entry.get('compact_denial', False)
deleg_enabled = entry.get('deleg_enabled', False)
if dnssec and dynamic_signing:
privatekey_path = entry['private_key']
if not privatekey_path.startswith('/') and prefs.workdir:
privatekey_path = os.path.join(prefs.workdir, privatekey_path)
privatekey = load_private_key(privatekey_path)
else:
privatekey = None
try:
zonedict.add(zonename, zonefile,
dnssec=dnssec, key=privatekey,
compact_denial=compact_denial,
deleg_enabled=deleg_enabled)
except dns.exception.DNSException as exc_info:
print(f"error: load zone {zonename} failed: {exc_info}")
sys.exit(1)
zonedict.set_zonelist()
def set_server_af(prefs, address):
"""Set server's address family"""
if address.find('.') != -1:
prefs.server_af = 'IPv4'
elif address.find(':') != -1:
prefs.server_af = 'IPv6'
else:
raise ValueError(f"{address} isn't a valid address")
def process_args(prefs, zonedict, arguments):
"""Process all command line arguments"""
try:
(options, args) = getopt.getopt(arguments, 'hc:dp:s:z:u:g:46fe:')
except getopt.GetoptError as error_info:
usage(str(error_info))
if args:
usage(f"No additional arguments allowed: {' '.join(args)}")
help_requested = [x for x in options if x[0] == '-h']
if help_requested:
usage()
config_supplied = [x for x in options if x[0] == '-c']
if config_supplied:
prefs.config = config_supplied[0][1]
print(f"Reading config from: {PREFS.config}")
init_config(prefs, zonedict)
for (opt, optval) in options:
if opt == "-d":
prefs.debug = True
elif opt == "-p":
prefs.port = int(optval)
elif opt == "-s":
prefs.server = optval
set_server_af(PREFS, optval)
elif opt == "-u":
prefs.username = optval
elif opt == "-g":
prefs.groupname = optval
elif opt == "-4":
prefs.server_af = 'IPv4'
elif opt == "-6":
prefs.server_af = 'IPv6'
elif opt == "-f":
prefs.daemon = False
elif opt == "-e":
prefs.edns_udp_max = int(optval)
def log_message(msg):
"""log informational message"""
if PREFS.daemon:
syslog.syslog(PREFS.syslog_pri, msg)
else:
with tlock:
print(msg)
def log_fatal(msg):
"""log fatal error message and bail out"""
log_message(msg)
sys.exit(1)
def handle_sighup(signum, frame):
"""handle SIGHUP - re-read configuration and zone files"""
_, _ = signum, frame
log_message('control: caught SIGHUP .. re-reading config and zones.')
init_config(PREFS, ZONEDICT)
def handle_sigterm(signum, frame):
"""handle SIGTERM - exit program"""
_, _ = signum, frame
log_message('control: caught SIGTERM .. exiting.')
sys.exit(0)
def install_signal_handlers():
"""Install handlers for HUP and TERM signals"""
signal.signal(signal.SIGTERM, handle_sigterm)
signal.signal(signal.SIGHUP, handle_sighup)
def get_pid_file():
"""Get name of PID file to create"""
if PREFS.pidfile:
return PREFS.pidfile
if PREFS.workdir:
return os.path.join(PREFS.workdir, 'daemon.pid')
return f'/tmp/{PROGNAME}.pid'
def daemon(dirname=None, syslog_fac=syslog.LOG_DAEMON):
"""Turn into daemon"""
pidfile = get_pid_file()
if os.path.exists(pidfile):
print(f"File {pidfile} already exists.")
sys.exit(1)
umask_value = 0o022
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as einfo:
print(f"fork() #1 failed: {einfo:s}")
sys.exit(1)
if dirname:
os.chdir(dirname)
os.umask(umask_value)
os.setsid()
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as einfo:
print(f"fork() #2 failed: {einfo:s}")
sys.exit(1)
with open(pidfile, 'w', encoding="utf-8") as pid_f:
pid_f.write(f'{os.getpid()}\n')
atexit.register(lambda: os.remove(pidfile))
for file_desc in range(0, os.sysconf("SC_OPEN_MAX")):
try:
os.close(file_desc)
except OSError:
pass
syslog.openlog(PROGNAME, syslog.LOG_PID, syslog_fac)
def drop_privs(uname, gname):
"""If run as root, drop privileges to specified uid and gid"""
if os.geteuid() != 0:
log_message("warning: Program didn't start as root. Can't change id.")
else:
os.setgroups([])
if gname:
gid = grp.getgrnam(gname).gr_gid
os.setgid(gid)
os.setegid(gid)
if uname:
uid = pwd.getpwnam(uname).pw_uid
os.setuid(uid)
os.seteuid(uid)
def udp4socket(host, port):
"""Create IPv4 UDP server socket"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
return sock
def udp6socket(host, port):
"""Create IPv6 UDP server socket"""
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.bind((host, port))
return sock
def tcp4socket(host, port):
"""Create IPv4 TCP server socket"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
return sock
def tcp6socket(host, port):
"""Create IPv6 TCP server socket"""
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
return sock
def send_socket(sock, message):
"""Send message on a connected socket"""
try:
octets_sent = 0
while octets_sent < len(message):
sentn = sock.send(message[octets_sent:])
if sentn == 0:
log_message("error: send() returned 0 bytes")
raise ValueError("send() returned 0 bytes")
octets_sent += sentn
except OSError as diag:
log_message(f"error: sendSocket() exception: {diag}")
return False
return True
def recv_socket(sock, num_octets):
"""Read and return num_octets of data from a connected socket"""
response = ""
octets_read = 0
while octets_read < num_octets:
chunk = sock.recv(num_octets - octets_read)
chunklen = len(chunk)
if chunklen == 0:
return ""
octets_read += chunklen
response += chunk
return response
def load_private_key(keyfile):
"""
Load DNSSEC private key from PEM format file for online signing.
"""
with open(keyfile, 'rb') as fkeyfile:
return load_pem_private_key(fkeyfile.read(), password=None)
return None
class Zone(dns.zone.Zone):
"""
Modified dns.zone.Zone class.
The nodes dictionary uses the SortedDict class from sortedcontainers,
rather than the standard dict class. This maintains a sorted keylist,
which makes it easier and more efficient to implement DNSSEC functions.
When add_ent_nodes() is called, it will iterate through the zone and
add all empty non-terminals as explicit nodes in the dictionary.
Fully qualified origin must be specified. Doesn't support relativized
names.
"""
node_factory = dns.node.Node
map_factory = SortedDict
__slots__ = [
'ent_nodes',
'dnssec',
'privatekey',
'signing_dnskey',
'keytag',
'nsec3param',
'compact_denial',
'deleg_enabled'
]
def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=False):
"""Initialize a zone object."""
super().__init__(origin, rdclass, relativize=relativize)
self.nodes = self.map_factory()
self.ent_nodes = {}
self.dnssec = False
self.privatekey = None
self.signing_dnskey = None
self.compact_denial = False
self.deleg_enabled = False
self.keytag = None
self.nsec3param = None
self.soa_min_ttl = None
def init_dnssec(self):
"""set DNSSEC parameters"""
self.dnssec = True
rdataset = self.get_rdataset(self.origin, dns.rdatatype.NSEC3PARAM)
if rdataset and len(rdataset) > 1:
raise ValueError("Only 1 NSEC3PARAM record is supported")
self.nsec3param = rdataset
def init_key(self, privatekey):
"""Initialize key for online signing"""
self.privatekey = privatekey
self.signing_dnskey = self.get_rdataset(self.origin,
dns.rdatatype.DNSKEY)[0]
self.keytag = dns.dnssec.key_id(self.signing_dnskey)
def set_deleg(self, deleg_enabled):
"""Set deleg_enabled flag"""
self.deleg_enabled = deleg_enabled
def set_compact_denial(self, compact_denial):
"""Set compact_denial of existence flag"""
self.compact_denial = compact_denial
def set_soa_min_ttl(self):
"""Calculate SOA min TTL value"""
soa_rrset = self.get_rrset(self.origin, dns.rdatatype.SOA)
self.soa_min_ttl = min(soa_rrset.ttl, soa_rrset[0].minimum)
def online_signing(self):
"""Does this zone utilize online signing?"""
return self.dnssec and (self.privatekey is not None)
def get_ent_nodes(self):
"""Find all empty non-terminals in the zone"""
seen = {}
for name in self.keys():
if name == self.origin:
continue
current_name = name
while current_name not in seen:
seen[current_name] = 1
parent = current_name.parent()
if parent == self.origin:
break
if self.get_node(parent) is None:
self.ent_nodes[parent] = 1
current_name = parent
def add_ent_nodes(self):
"""Add all empty non-terminals as explicits nodes in the Dict"""
self.get_ent_nodes()
for entry in self.ent_nodes:
node = self.node_factory()
self.nodes[entry] = node
def nsec_matching(self, name):
"""Return NSEC RRset matching the name"""
return self.get_rrset(name, dns.rdatatype.NSEC)
def nsec_covering(self, name):
"""Return NSEC RRset covering the name"""
position = self.nodes.bisect_left(name) - 1
while True:
nsec_name = self.nodes.peekitem(position)[0]
nsec_rrset = self.get_rrset(nsec_name, dns.rdatatype.NSEC)
if nsec_rrset:
return nsec_rrset
position -= 1
def nsec3_hash(self, name):
"""Return NSEC3 hash of name"""
params = self.nsec3param[0]
return nsec3hash(name,
params.algorithm, params.salt, params.iterations)
def nsec3_hashed_owner(self, name):
"""Return NSEC3 hashed owner name"""
n3hash = self.nsec3_hash(name)
owner = dns.name.Name((n3hash.encode(),) + self.origin.labels)
return owner
def nsec3_matching(self, name):
"""Return NSEC3 RRset matching the name"""
if not self.nsec3param:
return None
owner = self.nsec3_hashed_owner(name)
return self.get_rrset(owner, dns.rdatatype.NSEC3)
def nsec3_covering(self, name):
"""Return NSEC3 RRset covering the name"""
if not self.nsec3param:
return None
owner = self.nsec3_hashed_owner(name)
search_index = self.nodes.bisect(owner) - 1
while True:
name, node = self.nodes.peekitem(search_index)
rdataset = node.get_rdataset(dns.rdataclass.IN,
dns.rdatatype.NSEC3)
if rdataset:
rrset = dns.rrset.RRset(name, dns.rdataclass.IN,
rdataset.rdtype)
rrset.update(rdataset)
return rrset
search_index -= 1
if search_index < 0:
break
return None
def __str__(self):
return f"<Zone: {self.origin}>"
def zone_from_file(name, zonefile, dnssec=False, key=None,
compact_denial=False, deleg_enabled=False):
"""Obtain Zone object from zone name and file"""
zone = dns.zone.from_file(zonefile, origin=name, zone_factory=Zone,
relativize=False)
if not isinstance(zone.nodes, zone.map_factory):
zone.nodes = zone.map_factory(zone.nodes)
zone.add_ent_nodes()
zone.set_soa_min_ttl()
if dnssec:
zone.init_dnssec()
if key is not None:
zone.init_key(key)
if compact_denial:
zone.set_compact_denial(compact_denial)
zone.set_deleg(deleg_enabled)
return zone
class ZoneDict:
"""Zone Dictionary object: zone names -> zone objects"""
def __init__(self):
self.data = {}
self.zonelist = None
def set_zonelist(self):
"""Create list of zone names"""
self.zonelist = list(reversed(sorted(self.data.keys())))
def get_zonelist(self):
"""Return zone list"""
return self.zonelist
def add(self, zonename, zonefile, dnssec=False, key=None,
compact_denial=False, deleg_enabled=False):
"""Create and add zonename->zone object"""
zonename = dns.name.from_text(zonename)
self.data[zonename] = zone_from_file(zonename, zonefile, dnssec, key,
compact_denial, deleg_enabled)
def find(self, qname):
"""Return closest enclosing zone object for the qname"""
for zname in self.zonelist:
if qname.is_subdomain(zname):
return self.data[zname]
return None
B32_TO_EXT_HEX = bytes.maketrans(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
b'0123456789ABCDEFGHIJKLMNOPQRSTUV')
NSEC3HASH_SIZE_IN_OCTETS = 20
def hashalg(algnum):
"""Return hash function corresponding to hash algorithm number"""
if algnum == 1:
return hashlib.sha1
raise ValueError(f"unsupported NSEC3 hash algorithm {algnum}")
def nsec3hash(name, algnum, wire_salt, iterations, binary_out=False):
"""Compute NSEC3 hash for given domain name and parameters"""
if iterations < 0:
raise ValueError("iterations must be >= 0")
wire_name = name.to_digestable()
hashfunc = hashalg(algnum)
digest = wire_name
while iterations >= 0:
digest = hashfunc(digest + wire_salt).digest()
iterations -= 1
if binary_out:
return digest
output = base64.b32encode(digest)
output = output.translate(B32_TO_EXT_HEX).decode()
return output
def query_meta_type(qtype):
"""Is given query type a meta type (except ANY)?"""
return 128 <= qtype <= 254
def compact_answer_ok(message):
"""Does DNS message have Compact Answers OK EDNS header flag set?"""
return message.ednsflags & EdnsFlag.COMPACT_OK == EdnsFlag.COMPACT_OK
def deleg_ok(message):
"""Does DNS message have DELEG OK EDNS header flag set"""
return message.ednsflags & EdnsFlag.DELEG_OK == EdnsFlag.DELEG_OK
def sign_rrset(zone, rrset):
"""Sign RRset with zone's private key and return RRSIG record"""
rrsig_rdata = dns.dnssec.sign(rrset,
zone.privatekey,
zone.origin,
zone.signing_dnskey,
inception=int(time.time() - RRSIG_INCEPTION_OFFSET),
lifetime=RRSIG_LIFETIME)
rrsig = dns.rrset.RRset(rrset.name,
dns.rdataclass.IN,
dns.rdatatype.RRSIG)
rrsig_rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN,
dns.rdatatype.RRSIG,
ttl=rrset.ttl)
rrsig_rdataset.add(rrsig_rdata)
rrsig.update(rrsig_rdataset)
return rrsig
def make_nsec_rrset(owner, nextname, rrtypes, ttl):
"""Create NSEC RRset from components"""
rdata = NSEC.NSEC(rdclass=dns.rdataclass.IN,
rdtype=dns.rdatatype.NSEC,
next=nextname,
windows=NSEC.Bitmap.from_rdtypes(rrtypes))
rrset = dns.rrset.RRset(owner,
dns.rdataclass.IN,
dns.rdatatype.NSEC)
rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN,
dns.rdatatype.NSEC,
ttl=ttl)
rdataset.add(rdata)
rrset.update(rdataset)
return rrset
def make_nsec3_rrset(params, owner, nextname, rrtypes, ttl):
"""Create NSEC3 RRset from components"""
rdata = NSEC3.NSEC3(rdclass=dns.rdataclass.IN,
rdtype=dns.rdatatype.NSEC3,
algorithm=params.algorithm,
flags=params.flags,
iterations=params.iterations,
salt=params.salt,
next=nextname,
windows=NSEC3.Bitmap.from_rdtypes(rrtypes))
rrset = dns.rrset.RRset(owner,
dns.rdataclass.IN,
dns.rdatatype.NSEC3)
rdataset = dns.rdataset.Rdataset(dns.rdataclass.IN,
dns.rdatatype.NSEC3,
ttl=ttl)
rdataset.add(rdata)
rrset.update(rdataset)
return rrset
def make_nsec3_rrset_minimal(params, zone, owner, rrtypes, ttl, covering=False):
"""
Create minimal NSEC3 RRset. If "covering" is True, then the NSEC3
record will cover the given owner name, otherwise it will match it.
"""
owner_hash = nsec3hash(owner,
params.algorithm, params.salt, params.iterations,
binary_out=True)
hash_owner_int = int.from_bytes(owner_hash, byteorder='big')
owner_int = (hash_owner_int - 1) if covering else hash_owner_int
owner_bytes = owner_int.to_bytes(NSEC3HASH_SIZE_IN_OCTETS, 'big')
owner_hash = base64.b32encode(owner_bytes).translate(NSEC3.b32_normal_to_hex)
new_owner = dns.name.Name((owner_hash,) + zone.labels)
next_int = hash_owner_int + 1
next_bytes = next_int.to_bytes(NSEC3HASH_SIZE_IN_OCTETS, 'big')
return make_nsec3_rrset(params,
new_owner,
next_bytes,
rrtypes,
ttl)
class DNSquery:
"""DNS query object"""
def __init__(self, data, cliaddr, cliport, tcp=False):
self.malformed = False
self.cliaddr = cliaddr
self.cliport = cliport
self.headeronly = False
self.malformed = None
self.tcp = tcp
if self.tcp:
self.msg_len, = struct.unpack('!H', data[:2])
self.wire_message = data[2:2+self.msg_len]
else:
self.wire_message = data
self.msg_len = len(data)
try:
self.message = dns.message.from_wire(self.wire_message)
except dns.exception.DNSException as exc_info:
log_message(f"error: can't parse query: {type(exc_info)}: {exc_info}")
self.message = None
self.malformed = True
else:
if not self.message.question:
self.headeronly = True
else:
self.qname = self.message.question[0].name
self.qtype = self.message.question[0].rdtype
self.qclass = self.message.question[0].rdclass
self.log_query()
def edns_log_info(self):
"""Return string of EDNS parameters for logging purposes"""
edns_version = self.message.edns
if edns_version == -1:
return ""
flags = f'0x{self.message.ednsflags:04x}'
options = ",".join([str(int(x.otype)) for x in self.message.options])
result = f"edns=v{edns_version}/{flags}/{self.message.payload}"
if options:
result += f"/{options}"
return result
def log_query(self):
"""Log information about incoming DNS query"""
transport = "TCP" if self.tcp else "UDP"
if self.headeronly:
msg = (f'query: {transport} header-only '
f'from: {self.cliaddr},{self.cliport} size={self.msg_len}')
else:
msg = (f'query: {transport} '
f'{self.qname} '
f'{dns.rdatatype.to_text(self.qtype)} '
f'{dns.rdataclass.to_text(self.qclass)} '
f'from: {self.cliaddr},{self.cliport} size={self.msg_len}')
edns_log_message = self.edns_log_info()
if edns_log_message:
msg = msg + " " + edns_log_message
log_message(msg)
class DNSresponse:
"""DNS response object"""
def __init__(self, query):
self.query = query
self.response = dns.message.make_response(query.message,
our_payload=PREFS.edns_udp_adv)
if not self.query.headeronly:
self.qname = query.message.question[0].name
self.qtype = query.message.question[0].rdtype
self.qclass = query.message.question[0].rdclass
self.is_referral = False
self.cname_owner_list = []
self.dname_owner_list = []
self.is_nodata = False
self.edns_flags = 0
self.edns_options = []
self.badcookie = False
self.response.set_rcode(dns.rcode.NOERROR)
self.response.flags &= ~dns.flags.AA
self.prepare_response()
def to_wire(self):
"""Generate wire format DNS response"""
payload_max = self.max_size()
try:
wire = self.response.to_wire(max_size=payload_max)
except dns.exception.TooBig:
wire = self.truncate()
if self.query.tcp:
msglen = struct.pack('!H', len(wire))
wire = msglen + wire
return wire
def max_size(self):
"""Compute maximum permissible DNS response size"""
if self.query.tcp:
return 65533
if (PREFS.edns_udp_max == 0) or (self.query.message.edns == -1):
return 512
return min(self.query.message.payload, PREFS.edns_udp_max)
def truncate(self):
"""Truncate response message"""
self.response.flags |= dns.flags.TC
self.response.answer = []
self.response.authority = []
self.response.additional = []
return self.response.to_wire()
def add_rrset(self, zobj, section, rrset, wildcard=None, authoritative=True):
"""Add RRset to section, fetching RRsigs if needed"""
if rrset in section:
return
section.append(rrset)
if not authoritative or not self.dnssec_ok():
return
if zobj.online_signing():
section.append(sign_rrset(zobj, rrset))
return
if zobj.dnssec:
rrname = wildcard if wildcard else rrset.name
rdataset = zobj.get_rdataset(rrname,
dns.rdatatype.RRSIG, covers=rrset.rdtype)
if rdataset:
rrsig = dns.rrset.RRset(rrset.name,
dns.rdataclass.IN, rdataset.rdtype)
rrsig.update(rdataset)
section.append(rrsig)
def add_soa(self, zobj):
"""Add SOA record to authority for negative responses"""
soa_rrset = zobj.get_rrset(zobj.origin, dns.rdatatype.SOA)
soa_rrset.ttl = zobj.soa_min_ttl
self.add_rrset(zobj, self.response.authority, soa_rrset)
def nxdomain(self, zobj, sname):
"""Generate NXDOMAIN response"""
if not zobj.online_signing():
self.response.set_rcode(dns.rcode.NXDOMAIN)
self.add_soa(zobj)
if not self.dnssec_ok():
return
if zobj.online_signing():
if zobj.nsec3param:
if zobj.compact_denial:
self.nxdomain_nsec3_online_compact(zobj)
else:
self.nxdomain_nsec3_online(zobj, sname)
else:
self.nxdomain_nsec_online_compact(zobj)
return
if zobj.dnssec:
if zobj.nsec3param is None:
self.nxdomain_nsec(zobj, sname)
else:
self.nxdomain_nsec3(zobj, sname)
def nxdomain_nsec_online_compact(self, zobj):
"""
Generate online NSEC NXDOMAIN response using Compact Denial
"""
if compact_answer_ok(self.query.message):
self.response.set_rcode(dns.rcode.NXDOMAIN)
rrtypes = [dns.rdatatype.RRSIG, dns.rdatatype.NSEC, RRtype.NXNAME]
nextname = dns.name.Name((b'\x00',) + self.qname.labels)
nsec_rrset = make_nsec_rrset(self.qname, nextname, rrtypes, zobj.soa_min_ttl)
self.add_rrset(zobj, self.response.authority, nsec_rrset)
def nxdomain_nsec3_online(self, zobj, sname):
"""
Generate online NSEC3 NXDOMAIN response using White Lies
"""
self.response.set_rcode(dns.rcode.NXDOMAIN)
closest_encloser = sname.parent()
node = zobj.find_node(closest_encloser)
closest_encloser_rrtypes = [x.rdtype for x in node.rdatasets] + [dns.rdatatype.RRSIG]
n3_closest_encloser = make_nsec3_rrset_minimal(
zobj.nsec3param[0], zobj.origin,
closest_encloser, closest_encloser_rrtypes,
zobj.soa_min_ttl, covering=False)
self.add_rrset(zobj, self.response.authority, n3_closest_encloser)
next_closer = sname
n3_next_closer = make_nsec3_rrset_minimal(
zobj.nsec3param[0], zobj.origin,
next_closer, [],