-
Notifications
You must be signed in to change notification settings - Fork 14
/
DNS.py
1679 lines (1466 loc) · 57.2 KB
/
DNS.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
__version__ = '0.5'
import random
import select
import socket
import string
import struct
import types
import sys
import re
import os
import time
import threading
_EnableDebug = False
T_UNKNOWN = 0
T_A = 1
T_NS = 2
T_MD = 3
T_MF = 4
T_CNAME = 5
T_SOA = 6
T_MB = 7
T_MG = 8
T_MR = 9
T_NULL = 10
T_WKS = 11
T_PTR = 12
T_HINFO = 13
T_MINFO = 14
T_MX = 15
T_TXT = 16
T_RP = 17
T_AFSDB = 18
T_X25 = 19
T_ISDN = 20
T_RT = 21
T_PX = 26
T_GPOS = 27
T_AAAA = 28
T_LOC = 29
T_SRV = 33
T_NAPTR = 35
T_KX = 36
T_APL = 42
T_IXFR = 251
T_AXFR = 252
T_MAILB = 253
T_MAILA = 254
T_ANY = 255
DNS_TYPE = {T_UNKNOWN: 'UNKNOWN',
T_A: 'A',
T_NS: 'NS',
T_MD: 'MD',
T_MF: 'MF',
T_CNAME: 'CNAME',
T_SOA: 'SOA',
T_MB: 'MB',
T_MG: 'MG',
T_MR: 'MR',
T_NULL: 'NULL',
T_WKS: 'WKS',
T_PTR: 'PTR',
T_HINFO: 'HINFO',
T_MINFO: 'MINFO',
T_MX: 'MX',
T_TXT: 'TXT',
T_RP: 'RP',
T_AFSDB: 'AFSDB',
T_X25: 'X25',
T_ISDN: 'ISDN',
T_RT: 'RT',
T_PX: 'PX',
T_GPOS: 'GPOS',
T_AAAA: 'AAAA',
T_LOC: 'LOC',
T_SRV: 'SRV',
T_NAPTR: 'NAPTR',
T_KX: 'KX',
T_APL: 'APL',
T_IXFR: 'IXFR',
T_AXFR: 'AXFR',
T_MAILB: 'MAILB',
T_MAILA: 'MAILA',
T_ANY: 'ANY'}
C_RSV = 0
C_IN = 1
C_CS = 2
C_CH = 3
C_HS = 4
C_NONE = 254
C_ANY = 255
DNS_CLASS = {C_RSV: 'RESERVED',
C_IN: 'IN',
C_CS: 'CS',
C_CH: 'CH',
C_HS: 'HS',
C_NONE: 'NONE',
C_ANY: 'ANY'}
_HDR_REQUEST = 0
_HDR_RESPONSE = 32768
_HDR_OPCODE_MASK = 30720
_HDR_OPCODE_QUERY = 0
_HDR_OPCODE_IQUERY = 2048
_HDR_OPCODE_STATUS = 4096
_HDR_OPCODE_RSV = 6144
_HDR_OPCODE_NOTIFY = 8192
_HDR_OPCODE_UPDATE = 10240
_HDR_AUTH_ANSWER = 1024
_HDR_TRUNCATION = 512
_HDR_REC_DESIRED = 256
_HDR_REC_AVAIL = 128
_HDR_RESERVED_MASK = 112
_HDR_RCODE_MASK = 15
HDR_RCODE_NOERROR = 0
HDR_RCODE_FORMERR = 1
HDR_RCODE_SERVFAIL = 2
HDR_RCODE_NXDOMAIN = 3
HDR_RCODE_NOTIMP = 4
HDR_RCODE_REFUSED = 5
HDR_RCODE_YXDOMAIN = 6
HDR_RCODE_YXRRSET = 7
HDR_RCODE_NXRRSET = 8
HDR_RCODE_NOTAUTH = 9
HDR_RCODE_NOTZONE = 10
HDR_RCODE = {HDR_RCODE_NOERROR: ['Success', 'No error codition'],
HDR_RCODE_FORMERR: ['Format Error', 'Format Error - The name server was unable to interpret the query.'],
HDR_RCODE_SERVFAIL: ['Server Failure', 'Server failure - The name server was unable to process this query due to a problem with the name server'],
HDR_RCODE_NXDOMAIN: ['Non-Existent Domain', 'Name Error - Meaningful only for responses from an authoritative name server, this code signifies that the domain name referenced in the query does not exist.'],
HDR_RCODE_NOTIMP: ['Not Implemented', 'Not Implemented - The name server does not support the requested kind of query.'],
HDR_RCODE_REFUSED: ['Refused', 'Refused - The name server refuses to perform the specified operation for policy reasons.'],
HDR_RCODE_YXDOMAIN: ['Name Exists when it should not', 'Some name that ought not to exist, does exist.'],
HDR_RCODE_YXRRSET: ['RR Set Exists when it should not', 'Some RRset that ought not to exist, does exist.'],
HDR_RCODE_NXRRSET: ['RR Set that should exist does not', 'Some RRset that ought to exist, does not exist.'],
HDR_RCODE_NOTAUTH: ['Server Not Authoritative for zone', 'The server is not authoritative for the zone named in the Zone Section.'],
HDR_RCODE_NOTZONE: ['Name not contained in zone', 'A name used in the Prerequisite or Update Section is not within the zone denoted by the Zone Section.']}
def binipdisplay(s):
"""convert a binary array of ip adresses to a python list"""
if len(s) % 4 != 0:
raise EnvironmentError
ol = []
for i in range(len(s) / 4):
s1 = s[:4]
s = s[4:]
ip = []
for j in s1:
ip.append(str(ord(j)))
ol.append('.'.join(ip))
return ol
def stringdisplay(s):
"""convert "d.d.d.d,d.d.d.d" to ["d.d.d.d","d.d.d.d"].
also handle u'd.d.d.d d.d.d.d', as reporting on SF
"""
import re
return [ str(x) for x in re.split('[ ,]', s) ]
def RegistryResolve():
import re
import _winreg
nameservers = []
x = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
try:
y = _winreg.OpenKey(x, 'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters')
except EnvironmentError:
try:
y = _winreg.OpenKey(x, 'SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP')
nameserver, dummytype = _winreg.QueryValueEx(y, 'NameServer')
if nameserver and nameserver not in nameservers:
nameservers.extend(stringdisplay(nameserver))
except EnvironmentError:
pass
return nameservers
try:
nameserver = _winreg.QueryValueEx(y, 'DhcpNameServer')[0].split()
except:
nameserver = _winreg.QueryValueEx(y, 'NameServer')[0].split()
if nameserver:
nameservers = nameserver
nameserver = _winreg.QueryValueEx(y, 'NameServer')[0]
_winreg.CloseKey(y)
try:
y = _winreg.OpenKey(x, 'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\DNSRegisteredAdapters')
for i in range(1000):
try:
n = _winreg.EnumKey(y, i)
z = _winreg.OpenKey(y, n)
dnscount, dnscounttype = _winreg.QueryValueEx(z, 'DNSServerAddressCount')
dnsvalues, dnsvaluestype = _winreg.QueryValueEx(z, 'DNSServerAddresses')
nameservers.extend(binipdisplay(dnsvalues))
_winreg.CloseKey(z)
except EnvironmentError:
break
_winreg.CloseKey(y)
except EnvironmentError:
pass
try:
y = _winreg.OpenKey(x, 'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces')
for i in range(1000):
try:
n = _winreg.EnumKey(y, i)
z = _winreg.OpenKey(y, n)
try:
nameserver, dummytype = _winreg.QueryValueEx(z, 'NameServer')
if nameserver and nameserver not in nameservers:
nameservers.extend(stringdisplay(nameserver))
except EnvironmentError:
pass
_winreg.CloseKey(z)
except EnvironmentError:
break
_winreg.CloseKey(y)
except EnvironmentError:
pass
_winreg.CloseKey(x)
return nameservers
def _import_dnsservers():
servers = []
if sys.platform in ('win32', 'nt'):
servers = RegistryResolve()
else:
try:
lines = open('/etc/resolv.conf').readlines()
for line in lines:
line = line.strip()
if not line or line[0] == ';' or line[0] == '#':
continue
fields = line.split()
if len(fields) < 2:
continue
if fields[0] == 'nameserver':
servers.append(fields[1])
except:
pass
if len(servers) == 0:
servers.append('114.114.114.114')
servers.append('8.8.8.8')
return servers
_DNSSERVERS = _import_dnsservers()
def _unique(lst):
res = []
for elem in lst:
if elem not in res:
res.append(elem)
return res
class _debug():
def __init__(self, name):
self._name = name
if _EnableDebug:
print '%s.py: %s <<' % (__name__, self._name)
def msg(self, message):
if _EnableDebug:
print '%s.py: %s: %s' % (__name__, self._name, message)
def __del__(self):
if _EnableDebug:
print '%s.py: %s >>' % (__name__, self._name)
class QueryError(Exception):
"""
Exception raised during DNS query compilation
"""
pass
class AnswerError(Exception):
"""
Exception raised during DNS answer parsing
"""
pass
class IncompleteAnswerError(AnswerError):
"""
Exception raised if DNS answer is incomplete
"""
pass
class ResolverError(Exception):
"""
Exception raised during DNS resolution
"""
pass
class ConnectionError(ResolverError):
"""
Exception raised when communicating with name server
"""
pass
class ServerError(ResolverError):
"""
Exception raised by non-zero RCODE field
"""
pass
_QRY_NAME = 0
_QRY_TYPE = 1
_QRY_CLASS = 2
class _dnsquery():
def __init__(self, query, sections = None, recursion = False, id = None):
dbg = _debug('_dnsquery::__init__')
self._query = ()
self._sections = {'AUTHORITY': [],
'ADDITIONAL': []}
self.__sanity(query, sections)
self._recursion = recursion
self._id = id or self.__getID()
dbg.msg('%u: %s' % (self._id, self._query))
def __sanity(self, query, sections):
dbg = _debug('_dnsquery::__sanity')
addr, qtype, qclass = query
if not isinstance(addr, types.StringTypes):
raise ValueError('Invalid name %s' % str(addr))
if qtype == 0 or not DNS_TYPE.has_key(qtype):
raise ValueError('Invalid type %u' % qtype)
if qclass == 0 or not DNS_CLASS.has_key(qclass):
raise ValueError('Invalid class %u' % qclass)
self._query = query
if not sections:
return
sections = self.__normalize(sections)
for k in ['AUTHORITY', 'ADDITIONAL']:
if sections.has_key(k):
v = sections[k]
if not (isinstance(v, types.ListType) or isinstance(v, types.TupleType)):
raise ValueError('%s format error' % k)
self._sections[k] = v
def __normalize(self, the_map):
dbg = _debug('_dnsquery::__normalize')
res = {}
for key in the_map:
if isinstance(key, types.StringTypes):
res[key.upper()] = the_map[key]
return res
def __pack16(self, value):
dbg = _debug('_dnsquery::__pack16')
return struct.pack('>H', value)
def __pack32(self, value):
dbg = _debug('_dnsquery::__pack32')
return struct.pack('>L', value)
def __getID(self):
dbg = _debug('_dnsquery::__getID')
return random.randrange(1, 65535)
def __mkqhead(self):
dbg = _debug('_dnsquery::__mkqhead')
qhead = self.__pack16(self._id)
r = _HDR_REQUEST + _HDR_OPCODE_QUERY
if self._recursion:
r += _HDR_REC_DESIRED
qhead += self.__pack16(r)
qhead += self.__pack16(1)
qhead += self.__pack16(0)
qhead += self.__pack16(len(self._sections['AUTHORITY']))
qhead += self.__pack16(len(self._sections['ADDITIONAL']))
return qhead
def __mkqname(self, req):
dbg = _debug('_dnsquery::__mkqname')
res = ''
tokens = req.split('.')
for token in tokens:
res += '%c' % len(token) + token
return res + '\x00'
def __arpadomain(self, ipaddress):
dbg = _debug('_dnsquery::__arpadomain(%s)' % ipaddress)
addrlist = ipaddress.split('.')
if len(addrlist) != 4 or not self.__isipaddress(addrlist):
return ipaddress
addrlist.reverse()
addrlist.append('in-addr')
addrlist.append('arpa')
return string.join(addrlist, '.')
def __isipaddress(self, ipaddrlist):
for i in ipaddrlist:
try:
ipaddrblock = int(i)
except:
return False
if ipaddrblock != ipaddrblock & 255:
return False
return True
def __SOA_RDATA(self, data):
dbg = _debug('_dnsquery::__SOA_RDATA')
rdata = ''
for name in ['MNAME', 'RNAME']:
rdata += self.__mkqname(name)
rdata += self.__pack32(data['SERIAL'])
for key in ['REFRESH',
'RETRY',
'EXPIRE',
'MINIMUM']:
if data.has_key(key):
rdata += self.__pack32(data[key])
else:
rdata += self.__pack32(0L)
return rdata
def __mkqrdata(self, qtype, qclass, qrdata):
dbg = _debug('_dnsquery::__mkqrdata')
rdata = ''
if qtype == T_SOA:
rdata = self.__SOA_RDATA(qrdata)
else:
raise QueryError('Unsupported TYPE %u' % qtype)
return rdata
def __mkqsection(self, sname):
dbg = _debug('_dnsquery::__mkqsection')
if not self._sections.has_key(sname):
return ''
sqry = ''
for section in self._sections[sname]:
qname = section['NAME']
qtype = section['TYPE']
qclass = section['CLASS']
qttl = 0L
if section.has_key('TTL'):
qttl = section['TTL']
if qtype == T_PTR:
qname = self.__arpadomain(qname)
sqry += self.__mkqname(qname)
sqry += self.__pack16(qtype)
sqry += self.__pack16(qclass)
sqry += self.__pack32(qttl)
rdata = self.__mkqrdata(qtype, qclass, section['RDATA'])
sqry += self.__pack16(len(rdata))
sqry += rdata
return sqry
def get(self, prefix = False):
dbg = _debug('_dnsquery::get')
qry = self.__mkqhead()
qname = self._query[_QRY_NAME]
if self._query[_QRY_TYPE] == T_PTR:
qname = self.__arpadomain(qname)
dbg.msg('QNAME: %s' % qname)
qry += self.__mkqname(qname)
qry += self.__pack16(self._query[_QRY_TYPE])
qry += self.__pack16(self._query[_QRY_CLASS])
qry += self.__mkqsection('AUTHORITY')
qry += self.__mkqsection('ADDITIONAL')
if prefix:
qry = self.__pack16(len(qry)) + qry
return qry
def id(self):
return self._id
def __str__(self):
res = 'ID: %u\n' % self._id
res += 'Query: %s\n' % self._query[_QRY_NAME]
res += 'Type : %s\n' % DNS_TYPE[self._query[_QRY_TYPE]]
res += 'Class: %s\n' % DNS_CLASS[self._query[_QRY_CLASS]]
return res
_PARSE_SECTION = 0
_PARSE_OFFSET = 1
_PARSE_HEADER = 0
_PARSE_QUERY = 1
_PARSE_ANSWER = 2
_PARSE_AUTHORITY = 3
_PARSE_ADDITIONAL = 4
_PARSE_END = 5
class _dnsanswer():
def __init__(self, answer = None, prefix = False):
dbg = _debug('_dnsanswer::__init__')
self._answer = ''
self._prefix = prefix
self._size = 0
self._dict = {}
self._complete = False
self._status = [_PARSE_HEADER, 0]
if answer:
self.add(answer)
def __parse(self):
dbg = _debug('_dnsanswer::__parse')
try:
self.__parseheader()
self.__parsequery()
self.__parsesections()
if self._prefix and self._size != self._status[_PARSE_OFFSET]:
raise IncompleteAnswerError()
self._complete = True
except IncompleteAnswerError:
pass
def __parseheader(self):
dbg = _debug('_dnsanswer::__parseheader')
if self._status[_PARSE_SECTION] > _PARSE_HEADER:
dbg.msg('HEADER already parsed')
return
assert self._status[_PARSE_OFFSET] == 0, 'Inconsistent parse offset when parsing HEADER: %u' % self._status[_PARSE_OFFSET]
self.__sentry(len(self._answer), 12)
self._dict['HEADER'] = {}
self._dict['HEADER']['ID'] = self.__unpack16(self._answer[0:2])
self._dict['HEADER']['OPCODES'] = self.__opcodes(self._answer[2:4])
offset = 4
for i in ('QDCOUNT', 'ANCOUNT', 'NSCOUNT', 'ARCOUNT'):
self._dict['HEADER'][i] = self.__unpack16(self._answer[offset:offset + 2])
offset += 2
self._status[_PARSE_SECTION] += 1
self._status[_PARSE_OFFSET] = offset
dbg.msg('HEADER: %s' % self._dict['HEADER'])
def __parsequery(self):
dbg = _debug('_dnsanswer::__parsequery')
if self._status[_PARSE_SECTION] > _PARSE_QUERY:
dbg.msg('QUERY already parsed')
return
assert self._status[_PARSE_SECTION] == _PARSE_QUERY, 'Inconsistent parse section when parsing QUERY: %u' % self._status[_PARSE_SECTION]
assert self._status[_PARSE_OFFSET] == 12, 'Inconsistent parse offset when parsing QUERY: %u' % self._status[_PARSE_OFFSET]
offset = self._status[_PARSE_OFFSET]
self._dict['QUERY'] = []
for i in range(self._dict['HEADER']['QDCOUNT']):
q, offset = self.__question(self._answer, offset)
self._dict['QUERY'].append(q)
self._status[_PARSE_SECTION] += 1
self._status[_PARSE_OFFSET] = offset
def __parsesections(self):
dbg = _debug('_dnsanswer::__parsesections')
assert self._status[_PARSE_SECTION] > _PARSE_QUERY, 'Inconsistent parse section when parsing ANSWER: %u' % self._status[_PARSE_SECTION]
idx = self._status[_PARSE_SECTION] - _PARSE_ANSWER
offset = self._status[_PARSE_OFFSET]
sections = (('ANCOUNT', 'ANSWER'), ('NSCOUNT', 'AUTHORITY'), ('ARCOUNT', 'ADDITIONAL'))
for count, name in sections[idx:]:
self._dict[name] = []
for i in range(self._dict['HEADER'][count]):
dbg.msg('Starting to read %s[%u] section...' % (name, i))
section, offset = self.__section(self._answer, offset)
self._dict[name].append(section)
self._status[_PARSE_SECTION] += 1
self._status[_PARSE_OFFSET] = offset
dbg.msg('ANSWER: %s' % self._dict)
def __unpack16(self, value):
dbg = _debug('_dnsanswer::__unpack16')
return struct.unpack('>H', value)[0]
def __unpack32(self, value):
dbg = _debug('_dnsanswer::__unpack32')
return struct.unpack('>L', value)[0]
def __question(self, data, offset = 12):
dbg = _debug('_dnsanswer::__question')
res = {}
res['DOMAIN'], offset = self.__domain(data, offset)
res['TYPE'], offset = self.__dnstype(data, offset)
res['CLASS'], offset = self.__dnsclass(data, offset)
dbg.msg('QUESTION: %s' % res)
return (res, offset)
def __section(self, data, offset):
dbg = _debug('_dnsanswer::__section')
res = {}
res['DOMAIN'], offset = self.__domain(data, offset)
res['TYPE'], offset = self.__dnstype(data, offset)
res['CLASS'], offset = self.__dnsclass(data, offset)
res['TTL'], offset = self.__ttl(data, offset)
rdlen, offset = self.__rdlength(data, offset)
res['RDATA'], offset = self.__rdata(data, offset, rdlen, res['TYPE'])
dbg.msg('SECTION: %s' % res)
return (res, offset)
def __sentry(self, datalen, reqlen):
if datalen < reqlen:
raise IncompleteAnswerError('Answer is incomplete')
def __domain(self, data, offset):
dbg = _debug('_dnsanswer::__domain')
datalen = len(data)
self.__sentry(datalen, offset + 2)
anoffset = self.__islink(data, offset)
if anoffset:
token, anoffset = self.__domain(data, anoffset)
return (token, offset + 2)
tokenlist = []
tokenlen = ord(data[offset])
while tokenlen:
self.__sentry(datalen, offset + tokenlen + 1)
tokenlist.append(data[offset + 1:offset + tokenlen + 1])
dbg.msg('Token found: %s' % tokenlist[-1])
offset += tokenlen + 1
self.__sentry(datalen, offset + 1)
anoffset = self.__islink(data, offset)
if anoffset:
token, anoffset = self.__domain(data, anoffset)
tokenlist.append(token)
offset += 1
break
else:
tokenlen = ord(data[offset])
return (string.join(tokenlist, '.'), offset + 1)
def __IPv4(self, data, offset):
dbg = _debug('_dnsanswer::__IPv4')
self.__sentry(len(data), offset + 4)
length = 4
ipaddrlist = []
while length:
ipaddrlist.append(str(ord(data[offset])))
offset += 1
length -= 1
return (string.join(ipaddrlist, '.'), offset)
def __IPv6(self, data, offset, length):
dbg = _debug('_dnsanswer::__IPv6')
self.__sentry(len(data), offset + length)
ret = ''
prev_empty = False
if ord(data[offset]) == 0:
prev_empty = True
else:
ret = '%X' % ord(data[offset])
ret += ':'
length -= 1
offset += 1
while length:
if ord(data[offset]) > 0:
if prev_empty:
ret += ':'
ret += '%X:' % ord(data[offset])
else:
prev_empty = True
length -= 1
offset += 1
return (ret[:-1], offset)
def __strval(self, data, offset):
dbg = _debug('_dnsanswer::__strval')
strlen = ord(data[offset])
self.__sentry(len(data), offset + strlen + 1)
offset += 1
retstr = data[offset:offset + strlen]
return (retstr, offset + strlen)
def __islink(self, data, offset):
dbg = _debug('_dnsanswer::__islink')
if len(data[offset:]) < 2:
dbg.msg('Last octet in sequence (%u)' % offset)
return 0
self.__sentry(len(data), offset + 2)
word = self.__unpack16(data[offset:offset + 2])
if word / 16384 == 3:
dbg.msg('Following link from offset %u to offset %u' % (offset, word & 16383))
return word & 16383
dbg.msg('Not a link at offset %u' % offset)
return 0
def __twobytes(self, data, offset):
offset_end = offset + 2
self.__sentry(len(data), offset_end)
ret = self.__unpack16(data[offset:offset_end])
return (ret, offset_end)
def __fourbytes(self, data, offset):
offset_end = offset + 4
self.__sentry(len(data), offset_end)
ret = self.__unpack32(data[offset:offset_end])
return (ret, offset_end)
def __dnsclass(self, data, offset):
dbg = _debug('_dnsanswer::__dnsclass')
return self.__twobytes(data, offset)
def __dnstype(self, data, offset):
dbg = _debug('_dnsanswer::__dnstype')
return self.__twobytes(data, offset)
def __ttl(self, data, offset):
dbg = _debug('_dnsanswer::__ttl')
return self.__fourbytes(data, offset)
def __rdlength(self, data, offset):
dbg = _debug('_dnsanswer::__rdlength')
return self.__twobytes(data, offset)
def __CNAME_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__CNAME_RDATA')
return self.__domain(data, offset)
def __HINFO_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__HINFO_RDATA')
res = {}
res['CPU'], offset = self.__strval(data, offset)
res['OS'], offset = self.__strval(data, offset)
return (res, offset)
def __MB_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MB_RDATA')
return self.__domain(data, offset)
def __MD_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MD_RDATA')
return self.__domain(data, offset)
def __MF_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MF_RDATA')
return self.__domain(data, offset)
def __MG_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MG_RDATA')
return self.__domain(data, offset)
def __MINFO_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MINFO_RDATA')
res = {}
res['RMAILBX'], offset = self.__domain(data, offset)
res['EMAILBX'], offset = self.__domain(data, offset)
return (res, offset)
def __MR_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MR_RDATA')
return self.__domain(data, offset)
def __MX_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__MX_RDATA')
res = {}
res['REFERENCE'], offset = self.__twobytes(data, offset)
res['DOMAIN'], offset = self.__domain(data, offset)
return (res, offset)
def __NULL_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__NULL')
return self.__UNKNOWN_RDATA(data, offset, length)
def __NS_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__NS_RDATA')
return self.__domain(data, offset)
def __PTR_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__PTR_RDATA')
return self.__domain(data, offset)
def __SOA_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__SOA_RDATA')
res = {}
res['MNAME'], offset = self.__domain(data, offset)
res['RNAME'], offset = self.__domain(data, offset)
res['SERIAL'], offset = self.__fourbytes(data, offset)
res['REFRESH'], offset = self.__fourbytes(data, offset)
res['RETRY'], offset = self.__fourbytes(data, offset)
res['EXPIRE'], offset = self.__fourbytes(data, offset)
res['MINIMUM'], offset = self.__fourbytes(data, offset)
return (res, offset)
def __TXT_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__TXT_RDATA')
return self.__strval(data, offset)
def __A_RDATA(self, data, offset, length = 4):
dbg = _debug('_dnsanswer::__A_RDATA')
return self.__IPv4(data, offset)
def __AAAA_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__AAAA_RDATA')
return self.__IPv6(data, offset, length)
def __AFSDB_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__AFSDB_RDATA')
res = {}
res['TYPE'], offset = self.__twobytes(data, offset)
res['DOMAIN'], offset = self.__domain(data, offset)
return (res, offset)
def __RP_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__RP_RDATA')
res = {}
res['MBOX'], offset = self.__domain(data, offset)
res['TXT'], offset = self.__domain(data, offset)
return (res, offset)
def __X25_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__X25_RDATA')
return self.__strval(data, offset)
def __ISDN_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__ISDN_RDATA')
res = {}
res['ISDN'], offset = self.__strval(data, offset)
if len(res['ISDN']) + 1 < length:
res['SA'], offset = self.__strval(data, offset)
return (res, offset)
def __RT_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__RT_RDATA')
res = {}
res['REFERENCE'], offset = self.__twobytes(data, offset)
res['ROUTE'], offset = self.__domain(data, offset)
return (res, offset)
def __GPOS_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__GPOS_RDATA')
res = {}
res['LONGITUDE'], offset = self.__strval(data, offset)
res['LATITUDE'], offset = self.__strval(data, offset)
res['ALTITUDE'], offset = self.__strval(data, offset)
return (res, offset)
def __WKS_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__WKS_RDATA')
assert length > 4, 'Inconsistent WKS RDATA length %u' % length
self.__sentry(len(data), offset + length)
res = {}
res['ADDRESS'], offset = self.__IPv4(data, offset)
res['PROTOCOL'] = ord(data[offset])
offset += 1
res['SERVICES'] = []
octetno = 0
for i in range(offset, offset + length - 5):
val = ord(data[i])
for j in range(7, 0, -1):
if val & 1 << j:
res['SERVICES'].append(7 - j + 8 * octetno)
octetno += 1
return (res, offset + octetno)
def __SRV_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__SRV_RDATA')
res = {}
res['PRIORITY'], offset = self.__twobytes(data, offset)
res['WEIGHT'], offset = self.__twobytes(data, offset)
res['PORT'], offset = self.__twobytes(data, offset)
res['DOMAIN'], offset = self.__domain(data, offset)
return (res, offset)
def __KX_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__KX_RDATA')
res = {}
res['PREFERENCE'], offset = self.__twobytes(data, offset)
res['DOMAIN'], offset = self.__domain(data, offset)
return (res, offset)
def __APL_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__APL_RDATA')
self.__sentry(len(data), offset + length)
res = {}
res['AF'], offset = self.__twobytes(data, offset)
res['PREFIX'] = ord(data[offset])
offset += 1
tmpvar = ord(data[offset])
res['NEGATION'] = False
if tmpvar & 128:
res['NEGATION'] = True
afdlen = tmpvar & 127
offset += 1
AF_INET = 1
AF_INET6 = 2
if res['AF'] == AF_INET:
if res['PREFIX'] > 32:
raise AnswerError('Wrong PREFIX %u in ARL RR' % res['PREFIX'])
if afdlen > 4:
raise AnswerError('Wrong AFDLENGTH %u for AF_INET' % afdlen)
ipaddrlist = []
while afdlen:
ipaddrlist.append(str(ord(data[offset])))
offset += 1
afdlen -= 1
res['AFD'] = string.join(ipaddrlist, '.')
elif res['AF'] == AF_INET6:
if res['PREFIX'] > 128:
raise AnswerError('Wrong PREFIX %u in ARL RR' % res['PREFIX'])
if afdlen > 16:
raise AnswerError('Wrong AFDLENGTH %u for AF_INET6' % afdlen)
res['AFD'], offset = self.__IPv6(data, offset, afdlen)
else:
raise AnswerError('Unknown Address Family %u' % res['AF'])
return (res, offset)
def __PX_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__PX_RDATA')
res = {}
res['PREFERENCE'], offset = self.__twobytes(data, offset)
res['MAP822'], offset = self.__domain(data, offset)
res['MAPX400'], offset = self.__domain(data, offset)
return (res, offset)
def __LOC_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__LOC_RDATA')
self.__sentry(len(data), offset + length)
res = {}
res['VERSION'] = ord(data[offset])
offset += 1
res['SIZE'] = ord(data[offset])
offset += 1
res['HORIZ_PRE'] = ord(data[offset])
offset += 1
res['VERT_PRE'] = ord(data[offset])
offset += 1
res['LATITUDE'], offset = self.__fourbytes(data, offset)
res['LONGITUDE'], offset = self.__fourbytes(data, offset)
res['ALTITUDE'], offset = self.__fourbytes(data, offset)
return (res, offset)
def __NAPTR_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__NAPTR_RDATA')
res = {}
res['ORDER'], offset = self.__twobytes(data, offset)
res['PREFERENCE'], offset = self.__twobytes(data, offset)
res['FLAGS'], offset = self.__strval(data, offset)
res['SERVICE'], offset = self.__strval(data, offset)
res['REGEXP'], offset = self.__strval(data, offset)
res['REPLACEMENT'], offset = self.__domain(data, offset)
return (res, offset)
def __UNKNOWN_RDATA(self, data, offset, length):
dbg = _debug('_dnsanswer::__UNKNOWN_RDATA')
self.__sentry(len(data), offset + length)
res = "Unsupported TYPE: '%s'" % data[offset:offset + length]
return (res, offset + length)
def __rdata(self, data, offset, length, atype):
dbg = _debug('_dnsanswer::__rdata')
if atype == T_A:
return self.__A_RDATA(data, offset, length)
if atype == T_NS:
return self.__NS_RDATA(data, offset, length)
if atype == T_MD:
return self.__MD_RDATA(data, offset, length)
if atype == T_MF:
return self.__MF_RDATA(data, offset, length)
if atype == T_CNAME:
return self.__CNAME_RDATA(data, offset, length)
if atype == T_SOA:
return self.__SOA_RDATA(data, offset, length)
if atype == T_MB:
return self.__MB_RDATA(data, offset, length)
if atype == T_MG:
return self.__MG_RDATA(data, offset, length)
if atype == T_MR:
return self.__MR_RDATA(data, offset, length)
if atype == T_NULL:
return self.__NULL_RDATA(data, offset, length)
if atype == T_WKS:
return self.__WKS_RDATA(data, offset, length)
if atype == T_PTR:
return self.__PTR_RDATA(data, offset, length)
if atype == T_HINFO: