dyndns

Check-in [773c4f126c]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Clean up "fossil extra". Snapshot of dnslib for our use.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | master | trunk
Files: files | file ages | folders
SHA3-256:773c4f126c07277c095b4b5fbc6f640f8ccd9696e70651eece8a2b7a06dd1241
User & Date: vandys 2018-07-05 16:48:56
Context
2018-07-05
16:57
Drop root privs after we get the DNS server socket Leaf check-in: cd0b3be596 user: vandys tags: master, trunk
16:48
Clean up "fossil extra". Snapshot of dnslib for our use. check-in: 773c4f126c user: vandys tags: master, trunk
2017-06-15
04:59
more fixes, sigh check-in: cdda82734a user: ajv-899-334-8894@vsta.org tags: master, trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added .fossil-settings/ignore-glob.



>
1
*.pyc

Deleted .gitignore.

1
2
dnslib
*.pyc
<
<




Added dnslib/__init__.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
# -*- coding: utf-8 -*-

"""
dnslib
------

A library to encode/decode DNS wire-format packets supporting both 
Python 2.7 and Python 3.2+.

The library provides:

 * Support for encoding/decoding DNS packets between wire format,
   python objects, and Zone/DiG textual representation (dnslib.dns)

 * A server framework allowing the simple creation of custom DNS 
   resolvers (dnslib.server) and a number of example servers 
   created using this framework

 * A number of utilities for testing (dnslib.client, dnslib.proxy,
   dnslib.intercept)

Python 3 support was added in Version 0.9.0 which represented a fairly
major update to the library - the key changes include:

 * Python 2.7/3.2+ support (the last version supporting Python 2.6 
   or earlier was version 0.8.3)

 * The 'Bimap' interface was changed significantly to explicitly 
   split forward (value->text) lookups via __getitem__ and 
   reverse (text->value) lookups via __getattr__. Applications
   using the old interface will need to be updated.

 * Hostnames are now returned with a trailing dot by default (in
   line with RFC)

 * Most object attributes are now typed in line with the record
   definitions to make it harder to generate invalid packets 

 * Support for encoding/decoding resource records in 'Zone' (BIND) 
   file format 

 * Support for encoding/decoding packets in 'DiG' format

 * Server framework allowing (in most cases) custom resolvers to
   be created by just subclassing the DNSResolver class and 
   overriding the 'resolve' method

 * A lot of fixes to error detection/handling which should make 
   the library much more robust to invalid/unsupported data. The
   library should now either return a valid DNSRecord instance
   when parsing a packet or raise DNSError (tested via fuzzing)

 * Improved utilities (dnslib.client, dnslib.proxy, dnslib.intercept)

 * Improvements to encoding/decoding tests including the ability
   to generate test data automatically in test_decode.py (comparing
   outputs against DiG)

 * Ability to compare and diff DNSRecords

Classes
-------

The key DNS packet handling classes are in dnslib.dns and map to the 
standard DNS packet sections:

 * DNSRecord - container for DNS packet. Contains:
    - DNSHeader 
    - Question section containing zero or more DNSQuestion objects 
    - Answer section containing zero or more RR objects 
    - Authority section containing zero or more RR objects 
    - Additional section containing zero or more RR objects 
 * DNS RRs (resource records) contain an RR header and an RD object)
 * Specific RD types are implemented as subclasses of RD
 * DNS labels are represented by a DNSLabel class - in most cases
   this handles conversion to/from textual representation however
   does support arbitatry labels via a tuple of bytes objects

Usage
-----

To decode a DNS packet:

    >>> packet = binascii.unhexlify(b'd5ad818000010005000000000377777706676f6f676c6503636f6d0000010001c00c0005000100000005000803777777016cc010c02c0001000100000005000442f95b68c02c0001000100000005000442f95b63c02c0001000100000005000442f95b67c02c0001000100000005000442f95b93')
    >>> d = DNSRecord.parse(packet)
    >>> d
    <DNS Header: id=0xd5ad type=RESPONSE opcode=QUERY flags=RD,RA rcode='NOERROR' q=1 a=5 ns=0 ar=0>
    <DNS Question: 'www.google.com.' qtype=A qclass=IN>
    <DNS RR: 'www.google.com.' rtype=CNAME rclass=IN ttl=5 rdata='www.l.google.com.'>
    <DNS RR: 'www.l.google.com.' rtype=A rclass=IN ttl=5 rdata='66.249.91.104'>
    <DNS RR: 'www.l.google.com.' rtype=A rclass=IN ttl=5 rdata='66.249.91.99'>
    <DNS RR: 'www.l.google.com.' rtype=A rclass=IN ttl=5 rdata='66.249.91.103'>
    <DNS RR: 'www.l.google.com.' rtype=A rclass=IN ttl=5 rdata='66.249.91.147'>

The default text representation of the DNSRecord is in zone file format:

    >>> print(d)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 54701
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;www.google.com.                IN      A
    ;; ANSWER SECTION:
    www.google.com.         5       IN      CNAME   www.l.google.com.
    www.l.google.com.       5       IN      A       66.249.91.104
    www.l.google.com.       5       IN      A       66.249.91.99
    www.l.google.com.       5       IN      A       66.249.91.103
    www.l.google.com.       5       IN      A       66.249.91.147

To create a DNS Request Packet:

    >>> d = DNSRecord.question("google.com")

(This is equivalent to: d = DNSRecord(q=DNSQuestion("google.com") )

    >>> d
    <DNS Header: id=... type=QUERY opcode=QUERY flags=RD rcode='NOERROR' q=1 a=0 ns=0 ar=0>
    <DNS Question: 'google.com.' qtype=A qclass=IN>

    >>> str(DNSRecord.parse(d.pack())) == str(d)
    True

    >>> print(d)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;google.com.                    IN      A

    >>> d = DNSRecord.question("google.com","MX")

(This is equivalent to: d = DNSRecord(q=DNSQuestion("google.com",QTYPE.MX) )

    >>> str(DNSRecord.parse(d.pack())) == str(d)
    True

    >>> print(d)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;google.com.                    IN      MX

To create a DNS Response Packet:

    >>> d = DNSRecord(DNSHeader(qr=1,aa=1,ra=1),
    ...               q=DNSQuestion("abc.com"),
    ...               a=RR("abc.com",rdata=A("1.2.3.4")))
    >>> d
    <DNS Header: id=... type=RESPONSE opcode=QUERY flags=AA,RD,RA rcode='NOERROR' q=1 a=1 ns=0 ar=0>
    <DNS Question: 'abc.com.' qtype=A qclass=IN>
    <DNS RR: 'abc.com.' rtype=A rclass=IN ttl=0 rdata='1.2.3.4'>
    >>> str(DNSRecord.parse(d.pack())) == str(d)
    True

    >>> print(d)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      A
    ;; ANSWER SECTION:
    abc.com.                0       IN      A       1.2.3.4

It is also possible to create RRs from a string in zone file format

    >>> RR.fromZone("abc.com IN A 1.2.3.4")
    [<DNS RR: 'abc.com.' rtype=A rclass=IN ttl=0 rdata='1.2.3.4'>]

(Note: this produces a list of RRs which should be unpacked if being
    passed to add_answer/add_auth/add_ar etc)

    >>> q = DNSRecord.question("abc.com")
    >>> a = q.reply()
    >>> a.add_answer(*RR.fromZone("abc.com 60 A 1.2.3.4"))
    >>> print(a)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      A
    ;; ANSWER SECTION:
    abc.com.                60      IN      A       1.2.3.4

The zone file can contain multiple entries and supports most of the normal
format defined in RFC1035 (specifically not $INCLUDE)

    >>> z = '''
    ...         $TTL 300
    ...         $ORIGIN abc.com
    ...
    ...         @       IN      MX      10  mail.abc.com.
    ...         www     IN      A       1.2.3.4
    ...                 IN      TXT     "Some Text"
    ...         mail    IN      CNAME   www.abc.com.
    ... '''
    >>> for rr in RR.fromZone(textwrap.dedent(z)):
    ...     print(rr)
    abc.com.                300     IN      MX      10 mail.abc.com.
    www.abc.com.            300     IN      A       1.2.3.4
    www.abc.com.            300     IN      TXT     "Some Text"
    mail.abc.com.           300     IN      CNAME   www.abc.com.

To create a skeleton reply to a DNS query:

    >>> q = DNSRecord(q=DNSQuestion("abc.com",QTYPE.ANY)) 
    >>> a = q.reply()
    >>> a.add_answer(RR("abc.com",QTYPE.A,rdata=A("1.2.3.4"),ttl=60))
    >>> str(DNSRecord.parse(a.pack())) == str(a)
    True
    >>> print(a)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      ANY
    ;; ANSWER SECTION:
    abc.com.                60      IN      A       1.2.3.4

Add additional RRs:

    >>> a.add_answer(RR("xxx.abc.com",QTYPE.A,rdata=A("1.2.3.4")))
    >>> a.add_answer(RR("xxx.abc.com",QTYPE.AAAA,rdata=AAAA("1234:5678::1")))
    >>> str(DNSRecord.parse(a.pack())) == str(a)
    True
    >>> print(a)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      ANY
    ;; ANSWER SECTION:
    abc.com.                60      IN      A       1.2.3.4
    xxx.abc.com.            0       IN      A       1.2.3.4
    xxx.abc.com.            0       IN      AAAA    1234:5678::1


It is also possible to create a reply from a string in zone file format:

    >>> q = DNSRecord(q=DNSQuestion("abc.com",QTYPE.ANY)) 
    >>> a = q.replyZone("abc.com 60 IN CNAME xxx.abc.com")
    >>> print(a)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      ANY
    ;; ANSWER SECTION:
    abc.com.                60      IN      CNAME   xxx.abc.com.

    >>> str(DNSRecord.parse(a.pack())) == str(a)
    True

    >>> q = DNSRecord(q=DNSQuestion("abc.com",QTYPE.ANY)) 
    >>> a = q.replyZone(textwrap.dedent(z))
    >>> print(a)
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.com.                       IN      ANY
    ;; ANSWER SECTION:
    abc.com.                300     IN      MX      10 mail.abc.com.
    www.abc.com.            300     IN      A       1.2.3.4
    www.abc.com.            300     IN      TXT     "Some Text"
    mail.abc.com.           300     IN      CNAME   www.abc.com.


The library also includes a simple framework for generating custom DNS
resolvers in dnslib.server (see module docs). In post cases this just 
requires implementing a custom 'resolve' method which receives a question 
object and returns a response.

A number of sample resolvers are provided as examples (see CLI --help):

 * dnslib.fixedresolver    - Respond to all requests with fixed response
 * dnslib.zoneresolver     - Respond from Zone file 
 * dnslib.shellresolver    - Call shell script to generate response

The library includes a number of client utilities:

 * DiG like client library 

        # python -m dnslib.client --help

 * DNS Proxy Server

        # python -m dnslib.proxy --help

 * Intercepting DNS Proxy Server (replace proxy responses for specified domains)

        # python -m dnslib.intercept --help


Changelog:
----------

 *   0.1     2010-09-19  Initial Release
 *   0.2     2010-09-22  Minor fixes
 *   0.3     2010-10-02  Add DNSLabel class to support arbitrary labels (embedded '.')
 *   0.4     2012-02-26  Merge with dbslib-circuits
 *   0.5     2012-09-13  Add support for RFC2136 DDNS updates
                         Patch provided by Wesley Shields <wxs@FreeBSD.org> - thanks
 *   0.6     2012-10-20  Basic AAAA support
 *   0.7     2012-10-20  Add initial EDNS0 support (untested)
 *   0.8     2012-11-04  Add support for NAPTR, Authority RR and additional RR
                         Patch provided by Stefan Andersson (https://bitbucket.org/norox) - thanks
 *   0.8.1   2012-11-05  Added NAPTR test case and fixed logic error
                         Patch provided by Stefan Andersson (https://bitbucket.org/norox) - thanks
 *   0.8.2   2012-11-11  Patch to fix IPv6 formatting
                         Patch provided by Torbjörn Lönnemark (https://bitbucket.org/tobbezz) - thanks
 *   0.8.3   2013-04-27  Don't parse rdata if rdlength is 0
                         Patch provided by Wesley Shields <wxs@FreeBSD.org> - thanks
 *   0.9.0   2014-05-05  Major update including Py3 support (see docs)
 *   0.9.1   2014-05-05  Minor fixes
 *   0.9.2   2014-08-26  Fix Bimap handling of unknown mappings to avoid exception in printing
                         Add typed attributes to classes
                         Misc fixes from James Mills - thanks
 *   0.9.3   2014-08-26  Workaround for argparse bug which raises AssertionError if [] is
                         present in option text (really?)
 *   0.9.4   2015-04-10  Fix to support multiple strings in TXT record 
                         Patch provided by James Cherry (https://bitbucket.org/james_cherry) - thanks
                         NOTE: For consistency this patch changes the 'repr' output for
                               TXT records to always be quoted
 *   0.9.5   2015-10-27  Add threading & timeout handling to DNSServer
 *   0.9.6   2015-10-28  Replace strftime in RRSIG formatting to avoid possible locale issues
                         Identified by Bryan Everly - thanks
 *   0.9.7   2017-01-15  Sort out CAA/TYPE257 DiG parsing mismatch 


License:
--------

BSD

Author:
-------

 *   Paul Chakravarti (paul.chakravarti@gmail.com)

Master Repository/Issues:
-------------------------

 *   https://bitbucket.org/paulc/dnslib
     (Cloned on GitHub: https://github.com/paulchakravarti/dnslib)

"""

from dnslib.dns import *

version = "0.9.7"

if __name__ == '__main__':
    import doctest,textwrap
    doctest.testmod(optionflags=doctest.ELLIPSIS)

Added dnslib/bimap.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
# -*- coding: utf-8 -*-

"""
    Bimap - bidirectional mapping between code/value
"""

class BimapError(Exception):
    pass

class Bimap(object):

    """
        Bi-directional mapping between code/text. 

        Initialised using:

            name:   Used for exceptions
            dict:   Dict mapping from code (numeric) to text
            error:  Error type to raise if key not found

        The class provides:
        
            * A 'forward' map (code->text) which is accessed through 
              __getitem__ (bimap[code]) 
            * A 'reverse' map (code>value) which is accessed through 
              __getattr__ (bimap.text)
            * A 'get' method which does a forward lookup (code->text)
              and returns a textual version of code if there is no
              explicit mapping (or default provided)
        
        >>> class TestError(Exception):
        ...     pass

        >>> TEST = Bimap('TEST',{1:'A', 2:'B', 3:'C'},TestError)
        >>> TEST[1]
        'A'
        >>> TEST.A
        1
        >>> TEST.X
        Traceback (most recent call last):
        ...
        TestError: TEST: Invalid reverse lookup: [X]
        >>> TEST[99]
        Traceback (most recent call last):
        ...
        TestError: TEST: Invalid forward lookup: [99]
        >>> TEST.get(99)
        '99'
    
    """

    def __init__(self,name,forward,error=KeyError):
        self.name = name
        self.error = error
        self.forward = forward.copy()
        self.reverse = dict([(v,k) for (k,v) in list(forward.items())])

    def get(self,k,default=None):
        try:
            return self.forward[k]
        except KeyError as e:
            return default or str(k)

    def __getitem__(self,k):
        try:
            return self.forward[k]
        except KeyError as e:
            raise self.error("%s: Invalid forward lookup: [%s]" % (self.name,k))

    def __getattr__(self,k):
        try:
            return self.reverse[k]
        except KeyError as e:
            raise self.error("%s: Invalid reverse lookup: [%s]" % (self.name,k))

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Added dnslib/bit.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
# -*- coding: utf-8 -*-

"""
    Some basic bit mainpulation utilities
"""
from __future__ import print_function

FILTER = bytearray([ (i < 32 or i > 127) and 46 or i for i in range(256) ])

def hexdump(src, length=16, prefix=''):
    """
    Print hexdump of string

    >>> print(hexdump(b"abcd" * 4))
    0000  61 62 63 64 61 62 63 64  61 62 63 64 61 62 63 64  abcdabcd abcdabcd

    >>> print(hexdump(bytearray(range(48))))
    0000  00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f  ........ ........
    0010  10 11 12 13 14 15 16 17  18 19 1a 1b 1c 1d 1e 1f  ........ ........
    0020  20 21 22 23 24 25 26 27  28 29 2a 2b 2c 2d 2e 2f   !"#$%&' ()*+,-./

    """
    n = 0
    left = length // 2 
    right = length - left
    result= []
    src = bytearray(src)
    while src:
        s,src = src[:length],src[length:]
        l,r = s[:left],s[left:]
        hexa = "%-*s" % (left*3,' '.join(["%02x"%x for x in l]))
        hexb = "%-*s" % (right*3,' '.join(["%02x"%x for x in r]))
        lf = l.translate(FILTER)
        rf = r.translate(FILTER)
        result.append("%s%04x  %s %s %s %s" % (prefix, n, hexa, hexb, 
                                               lf.decode(), rf.decode()))
        n += length
    return "\n".join(result)

def get_bits(data,offset,bits=1):
    """
        Get specified bits from integer

        >>> bin(get_bits(0b0011100,2))
        '0b1'
        >>> bin(get_bits(0b0011100,0,4))
        '0b1100'
        
    """
    mask = ((1 << bits) - 1) << offset
    return (data & mask) >> offset 

def set_bits(data,value,offset,bits=1):
    """
        Set specified bits in integer

        >>> bin(set_bits(0,0b1010,0,4))
        '0b1010'
        >>> bin(set_bits(0,0b1010,3,4))
        '0b1010000'
    """
    mask = ((1 << bits) - 1) << offset
    clear = 0xffff ^ mask
    data = (data & clear) | ((value << offset) & mask)
    return data

def binary(n,count=16,reverse=False):
    """
        Display n in binary (only difference from built-in `bin` is
        that this function returns a fixed width string and can
        optionally be reversed

        >>> binary(6789)
        '0001101010000101'
        >>> binary(6789,8)
        '10000101'
        >>> binary(6789,reverse=True)
        '1010000101011000'

    """
    bits = [str((n >> y) & 1) for y in range(count-1, -1, -1)]
    if reverse:
        bits.reverse()
    return "".join(bits)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Added dnslib/buffer.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
# -*- coding: utf-8 -*-

"""
    Buffer - simple data buffer
"""

import binascii,struct

class BufferError(Exception):
    pass

class Buffer(object):

    """
    A simple data buffer - supports packing/unpacking in struct format 

    # Needed for Python 2/3 doctest compatibility
    >>> def p(s):
    ...     if not isinstance(s,str):
    ...         return s.decode()
    ...     return s

    >>> b = Buffer()
    >>> b.pack("!BHI",1,2,3)
    >>> b.offset
    7
    >>> b.append(b"0123456789")
    >>> b.offset
    17
    >>> p(b.hex())
    '0100020000000330313233343536373839'
    >>> b.offset = 0
    >>> b.unpack("!BHI")
    (1, 2, 3)
    >>> bytearray(b.get(5))
    bytearray(b'01234')
    >>> bytearray(b.get(5))
    bytearray(b'56789')
    >>> b.update(7,"2s",b"xx")
    >>> b.offset = 7
    >>> bytearray(b.get(5))
    bytearray(b'xx234')
    """

    def __init__(self,data=b''):
        """
            Initialise Buffer from data
        """
        self.data = bytearray(data)
        self.offset = 0

    def remaining(self):
        """
            Return bytes remaining
        """
        return len(self.data) - self.offset

    def get(self,length):
        """
            Gen len bytes at current offset (& increment offset)
        """
        if length > self.remaining():
            raise BufferError("Not enough bytes [offset=%d,remaining=%d,requested=%d]" %
                    (self.offset,self.remaining(),length))
        start = self.offset
        end = self.offset + length
        self.offset += length
        return bytes(self.data[start:end])

    def hex(self):
        """
            Return data as hex string
        """
        return binascii.hexlify(self.data)

    def pack(self,fmt,*args):
        """
            Pack data at end of data according to fmt (from struct) & increment
            offset
        """
        self.offset += struct.calcsize(fmt)
        self.data += struct.pack(fmt,*args)

    def append(self,s):
        """
            Append s to end of data & increment offset
        """
        self.offset += len(s)
        self.data += s

    def update(self,ptr,fmt,*args):
        """
            Modify data at offset `ptr` 
        """
        s = struct.pack(fmt,*args)
        self.data[ptr:ptr+len(s)] = s

    def unpack(self,fmt):
        """
            Unpack data at current offset according to fmt (from struct)
        """
        try:
            data = self.get(struct.calcsize(fmt))
            return struct.unpack(fmt,data)
        except struct.error as e:
            raise BufferError("Error unpacking struct '%s' <%s>" % 
                    (fmt,binascii.hexlify(data).decode()))

    def __len__(self):
        return len(self.data)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Added dnslib/client.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
# -*- coding: utf-8 -*-

"""
    DNS Client - DiG-like CLI utility. 
    
    Mostly useful for testing. Can optionally compare results from two
    nameservers (--diff) or compare results against DiG (--dig).

    Usage: python -m dnslib.client [options|--help]
    
    See --help for usage.
"""

from __future__ import print_function

try:
    from subprocess import getoutput
except ImportError:
    from commands import getoutput

import binascii,code,pprint

from dnslib.dns import DNSRecord,DNSHeader,DNSQuestion,QTYPE
from dnslib.digparser import DigParser

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="DNS Client")
    p.add_argument("--server","-s",default="8.8.8.8",
                    metavar="<address:port>",
                    help="Server address:port (default:8.8.8.8:53) (port is optional)")
    p.add_argument("--query",action='store_true',default=False,
                    help="Show query (default: False)")
    p.add_argument("--hex",action='store_true',default=False,
                    help="Dump packet in hex (default: False)")
    p.add_argument("--tcp",action='store_true',default=False,
                    help="Use TCP (default: UDP)")
    p.add_argument("--noretry",action='store_true',default=False,
                    help="Don't retry query using TCP if truncated (default: false)")
    p.add_argument("--diff",default="",
                    help="Compare response from alternate nameserver (format: address:port / default: false)")
    p.add_argument("--dig",action='store_true',default=False,
                    help="Compare result with DiG - if ---diff also specified use alternative nameserver for DiG request (default: false)")
    p.add_argument("--short",action='store_true',default=False,
                    help="Short output - rdata only (default: false)")
    p.add_argument("--debug",action='store_true',default=False,
                    help="Drop into CLI after request (default: false)")
    p.add_argument("domain",metavar="<domain>",
                    help="Query domain")
    p.add_argument("qtype",metavar="<type>",default="A",nargs="?",
                    help="Query type (default: A)")
    args = p.parse_args()

    # Construct request
    q = DNSRecord(q=DNSQuestion(args.domain,getattr(QTYPE,args.qtype)))

    address,_,port = args.server.partition(':')
    port = int(port or 53)

    if args.query:
        print(";; Sending%s:" % (" (TCP)" if args.tcp else ""))
        if args.hex:
            print(";; QUERY:",binascii.hexlify(q.pack()).decode())
        print(q)
        print()

    a_pkt = q.send(address,port,tcp=args.tcp)
    a = DNSRecord.parse(a_pkt)

    if a.header.tc and args.noretry == False:
        # Truncated - retry in TCP mode
        a_pkt = q.send(address,port,tcp=True)
        a = DNSRecord.parse(a_pkt)

    if args.dig or args.diff:
        if args.diff:
            address,_,port = args.diff.partition(':')
            port = int(port or 53)

        if args.dig:
            dig = getoutput("dig +qr -p %d %s %s @%s" % (
                                port, args.domain, args.qtype, address))
            dig_reply = list(iter(DigParser(dig)))
            # DiG might have retried in TCP mode so get last q/a
            q_diff = dig_reply[-2]
            a_diff = dig_reply[-1]
        else:
            q_diff = DNSRecord(header=DNSHeader(id=q.header.id),
                               q=DNSQuestion(args.domain,
                                             getattr(QTYPE,args.qtype)))
            q_diff = q
            diff = q_diff.send(address,port,tcp=args.tcp)
            a_diff = DNSRecord.parse(diff)
            if a_diff.header.tc and args.noretry == False:
                diff = q_diff.send(address,port,tcp=True)
                a_diff = DNSRecord.parse(diff)

    if args.short:
        print(a.short())
    else:
        print(";; Got answer:")
        if args.hex:
            print(";; RESPONSE:",binascii.hexlify(a_pkt).decode())
            if args.diff and not args.dig:
                print(";; DIFF    :",binascii.hexlify(diff).decode())
        print(a)
        print()

        if args.dig or args.diff:
            if q != q_diff:
                print(";;; ERROR: Diff Question differs")
                for (d1,d2) in q.diff(q_diff):
                    if d1:
                        print(";; - %s" % d1)
                    if d2:
                        print(";; + %s" % d2)
            if a != a_diff:
                print(";;; ERROR: Diff Response differs")
                for (d1,d2) in a.diff(a_diff):
                    if d1:
                        print(";; - %s" % d1)
                    if d2:
                        print(";; + %s" % d2)

    if args.debug:
        code.interact(local=locals())

Added dnslib/digparser.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
# -*- coding: utf-8 -*-
"""

    digparser
    ---------

    Encode/decode DNS packets from DiG textual representation. Parses 
    question (if present: +qr flag) & answer sections and returns list 
    of DNSRecord objects.

    Unsupported RR types are skipped (this is different from the packet 
    parser which will store and encode the RDATA as a binary blob)

    >>> dig = os.path.join(os.path.dirname(__file__),"test","dig","google.com-A.dig")
    >>> with open(dig) as f:
    ...     l = DigParser(f)
    ...     for record in l:
    ...         print('---')
    ...         print(repr(record))
    ---
    <DNS Header: id=0x5c9a type=QUERY opcode=QUERY flags=RD rcode='NOERROR' q=1 a=0 ns=0 ar=0>
    <DNS Question: 'google.com.' qtype=A qclass=IN>
    ---
    <DNS Header: id=0x5c9a type=RESPONSE opcode=QUERY flags=RD,RA rcode='NOERROR' q=1 a=16 ns=0 ar=0>
    <DNS Question: 'google.com.' qtype=A qclass=IN>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.183'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.152'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.172'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.177'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.157'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.153'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.182'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.168'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.178'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.162'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.187'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.167'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.148'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.173'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.158'>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='62.252.169.163'>

    >>> dig = os.path.join(os.path.dirname(__file__),"test","dig","google.com-ANY.dig")
    >>> with open(dig) as f:
    ...     l = DigParser(f)
    ...     for record in l:
    ...         print('---')
    ...         print(repr(record))
    ---
    <DNS Header: id=0xb294 type=QUERY opcode=QUERY flags=RD rcode='NOERROR' q=1 a=0 ns=0 ar=0>
    <DNS Question: 'google.com.' qtype=ANY qclass=IN>
    ---
    <DNS Header: id=0xb294 type=RESPONSE opcode=QUERY flags=RD,RA rcode='NOERROR' q=1 a=14 ns=0 ar=0>
    <DNS Question: 'google.com.' qtype=ANY qclass=IN>
    <DNS RR: 'google.com.' rtype=A rclass=IN ttl=299 rdata='216.58.212.110'>
    <DNS RR: 'google.com.' rtype=AAAA rclass=IN ttl=299 rdata='2a00:1450:4009:807::200e'>
    <DNS RR: 'google.com.' rtype=CAA rclass=IN ttl=86399 rdata='0 issue "symantec.com"'>
    <DNS RR: 'google.com.' rtype=MX rclass=IN ttl=599 rdata='40 alt3.aspmx.l.google.com.'>
    <DNS RR: 'google.com.' rtype=MX rclass=IN ttl=599 rdata='10 aspmx.l.google.com.'>
    <DNS RR: 'google.com.' rtype=NS rclass=IN ttl=86399 rdata='ns2.google.com.'>
    <DNS RR: 'google.com.' rtype=MX rclass=IN ttl=599 rdata='20 alt1.aspmx.l.google.com.'>
    <DNS RR: 'google.com.' rtype=SOA rclass=IN ttl=59 rdata='ns2.google.com. dns-admin.google.com. 144578247 900 900 1800 60'>
    <DNS RR: 'google.com.' rtype=NS rclass=IN ttl=86399 rdata='ns1.google.com.'>
    <DNS RR: 'google.com.' rtype=NS rclass=IN ttl=86399 rdata='ns4.google.com.'>
    <DNS RR: 'google.com.' rtype=NS rclass=IN ttl=86399 rdata='ns3.google.com.'>
    <DNS RR: 'google.com.' rtype=MX rclass=IN ttl=599 rdata='50 alt4.aspmx.l.google.com.'>
    <DNS RR: 'google.com.' rtype=TXT rclass=IN ttl=3599 rdata='"v=spf1 include:_spf.google.com ~all"'>
    <DNS RR: 'google.com.' rtype=MX rclass=IN ttl=599 rdata='30 alt2.aspmx.l.google.com.'>

"""

from __future__ import print_function

import glob,os.path,string

from dnslib.lex import WordLexer
from dnslib.dns import (DNSRecord,DNSHeader,DNSQuestion,DNSError,
                        RR,RD,RDMAP,QR,RCODE,CLASS,QTYPE)

class DigParser:

    """
        Parse Dig output
    """

    def __init__(self,dig,debug=False):
        self.debug = debug
        self.l = WordLexer(dig)
        self.l.commentchars = ';'
        self.l.nltok = ('NL',None)
        self.i = iter(self.l)
        
    def parseHeader(self,l1,l2):
        _,_,_,opcode,_,status,_,_id = l1.split()
        _,flags,_ = l2.split(';')
        header = DNSHeader(id=int(_id),bitmap=0)
        header.opcode = getattr(QR,opcode.rstrip(','))
        header.rcode = getattr(RCODE,status.rstrip(','))
        for f in ('qr','aa','tc','rd','ra'):
            if f in flags:
                setattr(header,f,1)
        return header

    def expect(self,expect):
        t,val = next(self.i)
        if t != expect:
            raise ValueError("Invalid Token: %s (expecting: %s)" % (t,expect))
        return val

    def parseQuestions(self,q,dns):
        for qname,qclass,qtype in q:
            dns.add_question(DNSQuestion(qname,
                                         getattr(QTYPE,qtype),
                                         getattr(CLASS,qclass)))

    def parseAnswers(self,a,auth,ar,dns):
        sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
        for sect in 'a','auth','ar':
            f = getattr(dns,sect_map[sect])
            for rr in locals()[sect]:
                rname,ttl,rclass,rtype = rr[:4]
                rdata = rr[4:]
                rd = RDMAP.get(rtype,RD)
                try:
                    if rd == RD and \
                       any([ x not in string.hexdigits for x in rdata[-1]]):
                        # Only support hex encoded data for fallback RD
                        pass
                    else:
                        f(RR(rname=rname,
                                ttl=int(ttl),
                                rtype=getattr(QTYPE,rtype),
                                rclass=getattr(CLASS,rclass),
                                rdata=rd.fromZone(rdata)))
                except DNSError as e:
                    if self.debug:
                        print("DNSError:",e,rr)
                    else:
                        # Skip records we dont understand
                        pass

    def __iter__(self):
        return self.parse()

    def parse(self):
        dns = None
        section = None
        paren = False
        rr = []
        try:
            while True:
                tok,val = next(self.i)
                if tok == 'COMMENT':
                    if 'Sending:' in val or 'Got answer:' in val:
                        if dns:
                            self.parseQuestions(q,dns)
                            self.parseAnswers(a,auth,ar,dns)
                            yield(dns)
                        dns = DNSRecord()
                        q,a,auth,ar = [],[],[],[]
                    elif val.startswith('; ->>HEADER<<-'):
                        self.expect('NL')
                        val2 = self.expect('COMMENT')
                        dns.header = self.parseHeader(val,val2)
                    elif val.startswith('; QUESTION'):
                        section = q
                    elif val.startswith('; ANSWER'):
                        section = a
                    elif val.startswith('; AUTHORITY'):
                        section = auth
                    elif val.startswith('; ADDITIONAL'):
                        section = ar
                    elif val.startswith(';') or tok[1].startswith('<<>>'):
                        pass
                    elif dns and section == q:
                        q.append(val.split())
                elif tok == 'ATOM':
                    if val == '(':
                        paren = True
                    elif val == ')':
                        paren = False
                    else:
                        rr.append(val)
                elif tok == 'NL' and not paren and rr:
                    if self.debug:
                        print(">>",rr)
                    section.append(rr)
                    rr = []
        except StopIteration:
            if rr:
                self.section.append(rr)
            if dns:
                self.parseQuestions(q,dns)
                self.parseAnswers(a,auth,ar,dns)
                yield(dns)

if __name__ == '__main__':

    import argparse,doctest,sys

    p = argparse.ArgumentParser(description="DigParser Test")
    p.add_argument("--dig",action='store_true',default=False,
                    help="Parse DiG output (stdin)")
    p.add_argument("--debug",action='store_true',default=False,
                    help="Debug output")

    args = p.parse_args()

    if args.dig:
        l = DigParser(sys.stdin,args.debug)
        for record in l:
            print(repr(record))
    else:
        doctest.testmod()

Added dnslib/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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732

"""
    DNS - main dnslib module 

    Contains core DNS packet handling code
"""

from __future__ import print_function

import base64,binascii,calendar,collections,copy,os.path,random,socket,\
       string,struct,textwrap,time

from itertools import chain

try:
    from itertools import zip_longest
except ImportError:
    from itertools import izip_longest as zip_longest

from dnslib.bit import get_bits,set_bits
from dnslib.bimap import Bimap,BimapError
from dnslib.buffer import Buffer,BufferError
from dnslib.label import DNSLabel,DNSLabelError,DNSBuffer
from dnslib.lex import WordLexer
from dnslib.ranges import BYTES,B,H,I,IP4,IP6,ntuple_range,check_range,\
                          check_bytes

class DNSError(Exception):
    pass

# DNS codes

QTYPE =  Bimap('QTYPE', 
                {1:'A', 2:'NS', 5:'CNAME', 6:'SOA', 12:'PTR', 15:'MX',
                 16:'TXT', 17:'RP', 18:'AFSDB', 24:'SIG', 25:'KEY', 28:'AAAA',
                 29:'LOC', 33:'SRV', 35:'NAPTR', 36:'KX', 37:'CERT', 38:'A6',
                 39:'DNAME', 41:'OPT', 42:'APL', 43:'DS', 44:'SSHFP',
                 45:'IPSECKEY', 46:'RRSIG', 47:'NSEC', 48:'DNSKEY', 49:'DHCID',
                 50:'NSEC3', 51:'NSEC3PARAM', 52:'TLSA', 55:'HIP', 99:'SPF',
                 249:'TKEY', 250:'TSIG', 251:'IXFR', 252:'AXFR', 255:'ANY',
                 257:'CAA', 32768:'TA', 32769:'DLV'},
                DNSError)
CLASS =  Bimap('CLASS',
                {1:'IN', 2:'CS', 3:'CH', 4:'Hesiod', 254:'None', 255:'*'},
                DNSError)
QR =     Bimap('QR',
                {0:'QUERY', 1:'RESPONSE'},
                DNSError)
RCODE =  Bimap('RCODE',
                {0:'NOERROR', 1:'FORMERR', 2:'SERVFAIL', 3:'NXDOMAIN', 
                 4:'NOTIMP', 5:'REFUSED', 6:'YXDOMAIN', 7:'YXRRSET', 
                 8:'NXRRSET', 9:'NOTAUTH', 10:'NOTZONE'},
                DNSError)
OPCODE = Bimap('OPCODE',{0:'QUERY', 1:'IQUERY', 2:'STATUS', 5:'UPDATE'},
                DNSError)

def label(label,origin=None):
    if label.endswith("."):
        return DNSLabel(label)
    else:
        return (origin if isinstance(origin,DNSLabel) 
                       else DNSLabel(origin)).add(label)

class DNSRecord(object):

    """
        Main DNS class - corresponds to DNS packet & comprises DNSHeader, 
        DNSQuestion and RR sections (answer,ns,ar)

        >>> d = DNSRecord()
        >>> d.add_question(DNSQuestion("abc.com")) # Or DNSRecord.question("abc.com")
        >>> d.add_answer(RR("abc.com",QTYPE.CNAME,ttl=60,rdata=CNAME("ns.abc.com")))
        >>> d.add_auth(RR("abc.com",QTYPE.SOA,ttl=60,rdata=SOA("ns.abc.com","admin.abc.com",(20140101,3600,3600,3600,3600))))
        >>> d.add_ar(RR("ns.abc.com",ttl=60,rdata=A("1.2.3.4")))
        >>> print(d)
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
        ;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 1
        ;; QUESTION SECTION:
        ;abc.com.                       IN      A
        ;; ANSWER SECTION:
        abc.com.                60      IN      CNAME   ns.abc.com.
        ;; AUTHORITY SECTION:
        abc.com.                60      IN      SOA     ns.abc.com. admin.abc.com. 20140101 3600 3600 3600 3600
        ;; ADDITIONAL SECTION:
        ns.abc.com.             60      IN      A       1.2.3.4
        >>> str(d) == str(DNSRecord.parse(d.pack()))
        True
    """

    @classmethod
    def parse(cls,packet):
        """
            Parse DNS packet data and return DNSRecord instance
            Recursively parses sections (calling appropriate parse method)
        """
        buffer = DNSBuffer(packet)
        try:
            header = DNSHeader.parse(buffer)
            questions = []
            rr = []
            auth = []
            ar = []
            for i in range(header.q):
                questions.append(DNSQuestion.parse(buffer))
            for i in range(header.a):
                rr.append(RR.parse(buffer))
            for i in range(header.auth):
                auth.append(RR.parse(buffer))
            for i in range(header.ar):
                ar.append(RR.parse(buffer))
            return cls(header,questions,rr,auth=auth,ar=ar)
        except DNSError:
            raise
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking DNSRecord [offset=%d]: %s" % (
                                    buffer.offset,e))

    @classmethod
    def question(cls,qname,qtype="A",qclass="IN"):
        """
            Shortcut to create question

            >>> q = DNSRecord.question("www.google.com")
            >>> print(q)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;www.google.com.                IN      A

            >>> q = DNSRecord.question("www.google.com","NS")
            >>> print(q)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;www.google.com.                IN      NS
        """
        return DNSRecord(q=DNSQuestion(qname,getattr(QTYPE,qtype),
                                             getattr(CLASS,qclass)))


    def __init__(self,header=None,questions=None,
                      rr=None,q=None,a=None,auth=None,ar=None):
        """
            Create new DNSRecord
        """
        self.header = header or DNSHeader()
        self.questions = questions or []
        self.rr = rr or []
        self.auth = auth or []
        self.ar = ar or []
        # Shortcuts to add a single Question/Answer
        if q:
            self.questions.append(q)
        if a:
            self.rr.append(a)
        self.set_header_qa()

    def reply(self,ra=1,aa=1):
        """
            Create skeleton reply packet

            >>> q = DNSRecord.question("abc.com")
            >>> a = q.reply()
            >>> a.add_answer(RR("abc.com",QTYPE.A,rdata=A("1.2.3.4"),ttl=60))
            >>> print(a)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                60      IN      A       1.2.3.4
        """
        return DNSRecord(DNSHeader(id=self.header.id,
                                   bitmap=self.header.bitmap,
                                   qr=1,ra=ra,aa=aa),
                         q=self.q)

    def replyZone(self,zone,ra=1,aa=1):
        """
            Create reply with response data in zone-file format
            >>> q = DNSRecord.question("abc.com")
            >>> a = q.replyZone("abc.com 60 A 1.2.3.4")
            >>> print(a)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                60      IN      A       1.2.3.4
        """
        return DNSRecord(DNSHeader(id=self.header.id,
                                   bitmap=self.header.bitmap,
                                   qr=1,ra=ra,aa=aa),
                         q=self.q,
                         rr=RR.fromZone(zone))

    def add_question(self,*q):
        """ 
            Add question(s)

            >>> q = DNSRecord()
            >>> q.add_question(DNSQuestion("abc.com"),
            ...                DNSQuestion("abc.com",QTYPE.MX))
            >>> print(q)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: rd; QUERY: 2, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;abc.com.                       IN      MX
        """
        self.questions.extend(q)
        self.set_header_qa()

    def add_answer(self,*rr):
        """
            Add answer(s)

            >>> q = DNSRecord.question("abc.com")
            >>> a = q.reply()
            >>> a.add_answer(*RR.fromZone("abc.com A 1.2.3.4"))
            >>> print(a)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                0       IN      A       1.2.3.4
        """
        self.rr.extend(rr)
        self.set_header_qa()

    def add_auth(self,*auth):
        """
            Add authority records

            >>> q = DNSRecord.question("abc.com")
            >>> a = q.reply()
            >>> a.add_answer(*RR.fromZone("abc.com 60 A 1.2.3.4"))
            >>> a.add_auth(*RR.fromZone("abc.com 3600 NS nsa.abc.com"))
            >>> print(a)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                60      IN      A       1.2.3.4
            ;; AUTHORITY SECTION:
            abc.com.                3600    IN      NS      nsa.abc.com.
        """
        self.auth.extend(auth)
        self.set_header_qa()

    def add_ar(self,*ar):
        """
            Add additional records

            >>> q = DNSRecord.question("abc.com")
            >>> a = q.reply()
            >>> a.add_answer(*RR.fromZone("abc.com 60 CNAME x.abc.com"))
            >>> a.add_ar(*RR.fromZone("x.abc.com 3600 A 1.2.3.4"))
            >>> print(a)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                60      IN      CNAME   x.abc.com.
            ;; ADDITIONAL SECTION:
            x.abc.com.              3600    IN      A       1.2.3.4
        """
        self.ar.extend(ar)
        self.set_header_qa()

    def set_header_qa(self):
        """
            Reset header q/a/auth/ar counts to match numver of records
            (normally done transparently)
        """
        self.header.q = len(self.questions)
        self.header.a = len(self.rr)
        self.header.auth = len(self.auth)
        self.header.ar = len(self.ar)

    # Shortcut to get first question
    def get_q(self):
        return self.questions[0] if self.questions else DNSQuestion()
    q = property(get_q)

    # Shortcut to get first answer
    def get_a(self):
        return self.rr[0] if self.rr else RR()
    a = property(get_a)

    def pack(self):
        """
            Pack record into binary packet
            (recursively packs each section into buffer)

            >>> q = DNSRecord.question("abc.com")
            >>> q.header.id = 1234
            >>> a = q.replyZone("abc.com A 1.2.3.4")
            >>> a.header.aa = 0
            >>> pkt = a.pack()
            >>> print(DNSRecord.parse(pkt))
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1234
            ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
            ;; QUESTION SECTION:
            ;abc.com.                       IN      A
            ;; ANSWER SECTION:
            abc.com.                0       IN      A       1.2.3.4
        """
        self.set_header_qa()
        buffer = DNSBuffer()
        self.header.pack(buffer)
        for q in self.questions:
            q.pack(buffer)
        for rr in self.rr:
            rr.pack(buffer)
        for auth in self.auth:
            auth.pack(buffer)
        for ar in self.ar:
            ar.pack(buffer)
        return buffer.data

    def truncate(self):
        """
            Return truncated copy of DNSRecord (with TC flag set)
            (removes all Questions & RRs and just returns header)
            
            >>> q = DNSRecord.question("abc.com")
            >>> a = q.reply()
            >>> a.add_answer(*RR.fromZone('abc.com IN TXT %s' % ('x' * 255)))
            >>> a.add_answer(*RR.fromZone('abc.com IN TXT %s' % ('x' * 255)))
            >>> a.add_answer(*RR.fromZone('abc.com IN TXT %s' % ('x' * 255)))
            >>> len(a.pack())
            829
            >>> t = a.truncate()
            >>> print(t)
            ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
            ;; flags: qr aa tc rd ra; QUERY: 0, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

        """
        return DNSRecord(DNSHeader(id=self.header.id,
                                   bitmap=self.header.bitmap,
                                   tc=1))

    def send(self,dest,port=53,tcp=False,timeout=None,ipv6=False):
        """
            Send packet to nameserver and return response
        """
        data = self.pack()
        if ipv6:
            inet = socket.AF_INET6
        else:
            inet = socket.AF_INET
        if tcp:
            if len(data) > 65535:
                raise ValueError("Packet length too long: %d" % len(data))
            data = struct.pack("!H",len(data)) + data
            sock = socket.socket(inet,socket.SOCK_STREAM)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.connect((dest,port))
            sock.sendall(data)
            response = sock.recv(8192)
            length = struct.unpack("!H",bytes(response[:2]))[0]
            while len(response) - 2 < length:
                response += sock.recv(8192)
            sock.close()
            response = response[2:]
        else:
            sock = socket.socket(inet,socket.SOCK_DGRAM)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.sendto(self.pack(),(dest,port))
            response,server = sock.recvfrom(8192)
            sock.close()
        return response
        
    def format(self,prefix="",sort=False):
        """
            Formatted 'repr'-style representation of record
            (optionally with prefix and/or sorted RRs)
        """
        s = sorted if sort else lambda x:x
        sections = [ repr(self.header) ]
        sections.extend(s([repr(q) for q in self.questions]))
        sections.extend(s([repr(rr) for rr in self.rr]))
        sections.extend(s([repr(rr) for rr in self.auth]))
        sections.extend(s([repr(rr) for rr in self.ar]))
        return prefix + ("\n" + prefix).join(sections)

    def toZone(self,prefix=""):
        """
            Formatted 'DiG' (zone) style output 
            (with optional prefix)
        """
        z = self.header.toZone().split("\n")
        if self.questions:
            z.append(";; QUESTION SECTION:")
            [ z.extend(q.toZone().split("\n")) for q in self.questions ]
        if self.rr:
            z.append(";; ANSWER SECTION:")
            [ z.extend(rr.toZone().split("\n")) for rr in self.rr ]
        if self.auth:
            z.append(";; AUTHORITY SECTION:")
            [ z.extend(rr.toZone().split("\n")) for rr in self.auth ]
        if self.ar:
            z.append(";; ADDITIONAL SECTION:")
            [ z.extend(rr.toZone().split("\n")) for rr in self.ar ]
        return prefix + ("\n" + prefix).join(z)

    def short(self):
        """
            Just return RDATA
        """
        return "\n".join([rr.rdata.toZone() for rr in self.rr])

    def __eq__(self,other):
        """
            Test for equality by diffing records
        """
        if type(other) != type(self):
            return False
        else:
            return self.diff(other) == []

    def __ne__(self,other):
        return not(self.__eq__(other))

    def diff(self,other):
        """
            Diff records - recursively diff sections (sorting RRs)
        """
        err = []
        if self.header != other.header:
            err.append((self.header,other.header))
        for section in ('questions','rr','auth','ar'):
            if section == 'questions':
                k = lambda x:tuple(map(str,(x.qname,x.qtype)))
            else:
                k = lambda x:tuple(map(str,(x.rname,x.rtype,x.rdata)))
            a = dict([(k(rr),rr) for rr in getattr(self,section)])
            b = dict([(k(rr),rr) for rr in getattr(other,section)])
            sa = set(a)
            sb = set(b)
            for e in sorted(sa.intersection(sb)):
                if a[e] != b[e]:
                    err.append((a[e],b[e]))
            for e in sorted(sa.difference(sb)):
                err.append((a[e],None))
            for e in sorted(sb.difference(sa)):
                err.append((None,b[e]))
        return err

    def __repr__(self):
        return self.format()

    def __str__(self):
        return self.toZone()

class DNSHeader(object):

    """
        DNSHeader section
    """

    # Ensure attribute values match packet
    id = H('id')
    bitmap = H('bitmap')
    q = H('q')
    a = H('a')
    auth = H('auth')
    ar = H('ar')

    @classmethod
    def parse(cls,buffer):
        """
            Implements parse interface 
        """
        try:
            (id,bitmap,q,a,auth,ar) = buffer.unpack("!HHHHHH")
            return cls(id,bitmap,q,a,auth,ar)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking DNSHeader [offset=%d]: %s" % (
                                buffer.offset,e))

    def __init__(self,id=None,bitmap=None,q=0,a=0,auth=0,ar=0,**args):
        if id is None:
            self.id = random.randint(0,65535)
        else:
            self.id = id 
        if bitmap is None:
            self.bitmap = 0
            self.rd = 1
        else:
            self.bitmap = bitmap
        self.q = q
        self.a = a
        self.auth = auth
        self.ar = ar
        for k,v in args.items():
            if k.lower() == "qr":
                self.qr = v
            elif k.lower() == "opcode":
                self.opcode = v
            elif k.lower() == "aa":
                self.aa = v
            elif k.lower() == "tc":
                self.tc = v
            elif k.lower() == "rd":
                self.rd = v
            elif k.lower() == "ra":
                self.ra = v
            elif k.lower() == "rcode":
                self.rcode = v
    
    # Accessors for header properties (automatically pack/unpack
    # into bitmap)
    def get_qr(self):
        return get_bits(self.bitmap,15)

    def set_qr(self,val):
        self.bitmap = set_bits(self.bitmap,val,15)

    qr = property(get_qr,set_qr)

    def get_opcode(self):
        return get_bits(self.bitmap,11,4)

    def set_opcode(self,val):
        self.bitmap = set_bits(self.bitmap,val,11,4)

    opcode = property(get_opcode,set_opcode)

    def get_aa(self):
        return get_bits(self.bitmap,10)

    def set_aa(self,val):
        self.bitmap = set_bits(self.bitmap,val,10)

    aa = property(get_aa,set_aa)
        
    def get_tc(self):
        return get_bits(self.bitmap,9)

    def set_tc(self,val):
        self.bitmap = set_bits(self.bitmap,val,9)

    tc = property(get_tc,set_tc)
        
    def get_rd(self):
        return get_bits(self.bitmap,8)

    def set_rd(self,val):
        self.bitmap = set_bits(self.bitmap,val,8)

    rd = property(get_rd,set_rd)
        
    def get_ra(self):
        return get_bits(self.bitmap,7)

    def set_ra(self,val):
        self.bitmap = set_bits(self.bitmap,val,7)

    ra = property(get_ra,set_ra)

    def get_rcode(self):
        return get_bits(self.bitmap,0,4)

    def set_rcode(self,val):
        self.bitmap = set_bits(self.bitmap,val,0,4)

    rcode = property(get_rcode,set_rcode)

    def pack(self,buffer):
        buffer.pack("!HHHHHH",self.id,self.bitmap,
                              self.q,self.a,self.auth,self.ar)

    def __repr__(self):
        f = [ self.aa and 'AA', 
              self.tc and 'TC', 
              self.rd and 'RD', 
              self.ra and 'RA' ] 
        if OPCODE.get(self.opcode) == 'UPDATE':
            f1='zo'
            f2='pr'
            f3='up'
            f4='ad'
        else:
            f1='q'
            f2='a'
            f3='ns'
            f4='ar'
        return "<DNS Header: id=0x%x type=%s opcode=%s flags=%s " \
                            "rcode='%s' %s=%d %s=%d %s=%d %s=%d>" % ( 
                    self.id,
                    QR.get(self.qr),
                    OPCODE.get(self.opcode),
                    ",".join(filter(None,f)),
                    RCODE.get(self.rcode),
                    f1, self.q, f2, self.a, f3, self.auth, f4, self.ar )

    def toZone(self):
        f = [ self.qr and 'qr',
              self.aa and 'aa', 
              self.tc and 'tc', 
              self.rd and 'rd', 
              self.ra and 'ra' ] 
        z1 = ';; ->>HEADER<<- opcode: %s, status: %s, id: %d' % (
                    OPCODE.get(self.opcode),RCODE.get(self.rcode),self.id)
        z2 = ';; flags: %s; QUERY: %d, ANSWER: %d, AUTHORITY: %d, ADDITIONAL: %d' % (
                      " ".join(filter(None,f)),
                      self.q,self.a,self.auth,self.ar)
        return z1 + "\n" + z2

    def __str__(self):
        return self.toZone()

    def __ne__(self,other):
        return not(self.__eq__(other))

    def __eq__(self,other):
        if type(other) != type(self):
            return False
        else:
            # Ignore id
            attrs = ('qr','aa','tc','rd','ra','opcode','rcode')
            return all([getattr(self,x) == getattr(other,x) for x in attrs])

class DNSQuestion(object):
    
    """
        DNSQuestion section
    """
        
    @classmethod
    def parse(cls,buffer):
        try:
            qname = buffer.decode_name()
            qtype,qclass = buffer.unpack("!HH")
            return cls(qname,qtype,qclass)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking DNSQuestion [offset=%d]: %s" % (
                                buffer.offset,e))

    def __init__(self,qname=None,qtype=1,qclass=1):
        self.qname = qname
        self.qtype = qtype
        self.qclass = qclass

    def set_qname(self,qname):
        if isinstance(qname,DNSLabel):
            self._qname = qname
        else:
            self._qname = DNSLabel(qname)

    def get_qname(self):
        return self._qname

    qname = property(get_qname,set_qname)

    def pack(self,buffer):
        buffer.encode_name(self.qname)
        buffer.pack("!HH",self.qtype,self.qclass)

    def toZone(self):
       return ';%-30s %-7s %s' % (self.qname,CLASS.get(self.qclass),
                                             QTYPE.get(self.qtype))

    def __repr__(self):
        return "<DNS Question: '%s' qtype=%s qclass=%s>" % (
                    self.qname, QTYPE.get(self.qtype), CLASS.get(self.qclass))

    def __str__(self):
        return self.toZone()

    def __ne__(self,other):
        return not(self.__eq__(other))

    def __eq__(self,other):
        if type(other) != type(self):
            return False
        else:
            # List of attributes to compare when diffing
            attrs = ('qname','qtype','qclass')
            return all([getattr(self,x) == getattr(other,x) for x in attrs])
            
class EDNSOption(object):

    """
        EDNSOption pseudo-section

        Very rudimentary support for EDNS0 options however this has not been
        tested due to a lack of data (anyone wanting to improve support or
        provide test data please raise an issue)

        >>> EDNSOption(1,b"1234")
        <EDNS Option: Code=1 Data='31323334'>
        >>> EDNSOption(99999,b"1234")
        Traceback (most recent call last):
        ...
        ValueError: Attribute 'code' must be between 0-65535 [99999]
        >>> EDNSOption(1,None)
        Traceback (most recent call last):
        ...
        ValueError: Attribute 'data' must be instance of ...

    """

    code = H('code')
    data = BYTES('data')

    def __init__(self,code,data):
        self.code = code
        self.data = data

    def pack(self,buffer):
        buffer.pack("!HH",self.code,len(self.data))
        buffer.append(self.data)

    def __repr__(self):
        return "<EDNS Option: Code=%d Data='%s'>" % (
                    self.code,binascii.hexlify(self.data).decode())

    def toZone(self):
        return ";EDNS: code: %s; data: %s" % (
                    self.code,binascii.hexlify(self.data).decode())

    def __str__(self):
        return self.toZone()

    def __ne__(self,other):
        return not(self.__eq__(other))

    def __eq__(self,other):
        if type(other) != type(self):
            return False
        else:
            # List of attributes to compare when diffing
            attrs = ('code','data')
            return all([getattr(self,x) == getattr(other,x) for x in attrs])

class RR(object):

    """
        DNS Resource Record 
        Contains RR header and RD (resource data) instance
    """

    rtype = H('rtype')
    rclass = H('rclass')
    ttl = I('ttl')
    rdlength = H('rdlength')

    @classmethod
    def parse(cls,buffer):
        try:
            rname = buffer.decode_name()
            rtype,rclass,ttl,rdlength = buffer.unpack("!HHIH")
            if rtype == QTYPE.OPT:
                options = []
                option_buffer = Buffer(buffer.get(rdlength))
                while option_buffer.remaining() > 4:
                    code,length = option_buffer.unpack("!HH")
                    data = option_buffer.get(length)
                    options.append(EDNSOption(code,data))
                rdata = options
            else:
                if rdlength:
                    rdata = RDMAP.get(QTYPE.get(rtype),RD).parse(
                                            buffer,rdlength)
                else:
                    rdata = ''
            return cls(rname,rtype,rclass,ttl,rdata)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking RR [offset=%d]: %s" % (
                                buffer.offset,e))

    @classmethod
    def fromZone(cls,zone,origin="",ttl=0):
        """
            Parse RR data from zone file and return list of RRs
        """
        return list(ZoneParser(zone,origin=origin,ttl=ttl))

    def __init__(self,rname=None,rtype=1,rclass=1,ttl=0,rdata=None):
        self.rname = rname
        self.rtype = rtype
        self.rclass = rclass
        self.ttl = ttl
        self.rdata = rdata
        # TODO Add property getters/setters
        if self.rtype == QTYPE.OPT:
            self.edns_len = self.rclass
            self.edns_do = get_bits(self.ttl,15)
            self.edns_ver = get_bits(self.ttl,16,8)
            self.edns_rcode = get_bits(self.ttl,24,8)

    def set_rname(self,rname):
        if isinstance(rname,DNSLabel):
            self._rname = rname
        else:
            self._rname = DNSLabel(rname)

    def get_rname(self):
        return self._rname

    rname = property(get_rname,set_rname)

    def pack(self,buffer):
        buffer.encode_name(self.rname)
        buffer.pack("!HHI",self.rtype,self.rclass,self.ttl)
        rdlength_ptr = buffer.offset
        buffer.pack("!H",0)
        start = buffer.offset
        if self.rtype == QTYPE.OPT:
            for opt in self.rdata:
                opt.pack(buffer)
        else:
            self.rdata.pack(buffer)
        end = buffer.offset
        buffer.update(rdlength_ptr,"!H",end-start)

    def __repr__(self):
        if self.rtype == QTYPE.OPT:
            s = ["<DNS OPT: edns_ver=%d do=%d ext_rcode=%d udp_len=%d>" % (
                        self.edns_ver,self.edns_do,self.edns_rcode,self.edns_len)]
            s.extend([repr(opt) for opt in self.rdata])
            return "\n".join(s)
        else:
            return "<DNS RR: '%s' rtype=%s rclass=%s ttl=%d rdata='%s'>" % (
                    self.rname, QTYPE.get(self.rtype), CLASS.get(self.rclass), 
                    self.ttl, self.rdata)

    def toZone(self):
        if self.rtype == QTYPE.OPT:
            edns = [ ";OPT PSEUDOSECTION", 
                     ";EDNS: version: %d, flags: %s; udp: %d" % (
                             self.edns_ver, 
                             "do" if self.edns_do else "",
                             self.edns_len)
                    ]
            edns.extend([str(opt) for opt in self.rdata])
            return "\n".join(edns)
        else:
            return '%-23s %-7s %-7s %-7s %s' % (self.rname,self.ttl,
                                                CLASS.get(self.rclass),
                                                QTYPE.get(self.rtype),
                                                self.rdata.toZone())

    def __str__(self):
        return self.toZone()

    def __ne__(self,other):
        return not(self.__eq__(other))

    def __eq__(self,other):
        # Handle OPT specially as may be different types (RR/EDNS0)
        if self.rtype == QTYPE.OPT and getattr(other,"rtype",False) == QTYPE.OPT:
            attrs = ('rname','rclass','rtype','ttl','rdata')
            return all([getattr(self,x) == getattr(other,x) for x in attrs])
        else:
            if type(other) != type(self):
                return False
            else:
                # List of attributes to compare when diffing (ignore ttl)
                attrs = ('rname','rclass','rtype','rdata')
                return all([getattr(self,x) == getattr(other,x) for x in attrs])

class EDNS0(RR):

    """

        ENDS0 pseudo-record

        Wrapper around the ENDS0 support in RR to make it more convenient to
        create EDNS0 pseudo-record - this just makes it easier to specify the
        EDNS0 parameters directly

        EDNS flags should be passed as a space separated string of options 
        (currently only 'do' is supported)

        >>> EDNS0("abc.com",flags="do",udp_len=2048,version=1)
        <DNS OPT: edns_ver=1 do=1 ext_rcode=0 udp_len=2048>
        >>> print(_)
        ;OPT PSEUDOSECTION
        ;EDNS: version: 1, flags: do; udp: 2048
        >>> opt = EDNS0("abc.com",flags="do",ext_rcode=1,udp_len=2048,version=1,opts=[EDNSOption(1,b'abcd')])
        >>> opt
        <DNS OPT: edns_ver=1 do=1 ext_rcode=1 udp_len=2048>
        <EDNS Option: Code=1 Data='61626364'>
        >>> print(opt)
        ;OPT PSEUDOSECTION
        ;EDNS: version: 1, flags: do; udp: 2048
        ;EDNS: code: 1; data: 61626364
        >>> r = DNSRecord.question("abc.com").replyZone("abc.com A 1.2.3.4")
        >>> r.add_ar(opt)
        >>> print(r)
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
        ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
        ;; QUESTION SECTION:
        ;abc.com.                       IN      A
        ;; ANSWER SECTION:
        abc.com.                0       IN      A       1.2.3.4
        ;; ADDITIONAL SECTION:
        ;OPT PSEUDOSECTION
        ;EDNS: version: 1, flags: do; udp: 2048
        ;EDNS: code: 1; data: 61626364
        >>> DNSRecord.parse(r.pack()) == r
        True
    """

    def __init__(self,rname=None,rtype=QTYPE.OPT,
            ext_rcode=0,version=0,flags="",udp_len=0,opts=None):
        check_range('ext_rcode',ext_rcode,0,255)
        check_range('version',version,0,255)
        edns_flags = { 'do' : 1 << 15 }
        flag_bitmap = sum([edns_flags[x] for x in flags.split()])
        ttl = (ext_rcode << 24) + (version << 16) + flag_bitmap
        if opts and not all([isinstance(o,EDNSOption) for o in opts]):
            raise ValueError("Option must be instance of EDNSOption")
        super(EDNS0,self).__init__(rname,rtype,udp_len,ttl,opts or [])

class RD(object):
    """
        Base RD object - also used as placeholder for unknown RD types

        To create a new RD type subclass this and add to RDMAP (below)

        Subclass should implement (as a mininum):

            parse (parse from packet data)
            __init__ (create class)
            __repr__ (return in zone format)
            fromZone (create from zone format)

            (toZone uses __repr__ by default)

        Unknown rdata types default to RD and store rdata as a binary
        blob (this allows round-trip encoding/decoding)
    """

    @classmethod
    def parse(cls,buffer,length):
        """
            Unpack from buffer
        """
        try:
            data = buffer.get(length)
            return cls(data)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking RD [offset=%d]: %s" % 
                                    (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        """
            Create new record from zone format data
            RD is a list of strings parsed from DiG output
        """
        # Unknown rata - assume hexdump in zone format
        # (DiG prepends "\\# <len>" to the hexdump so get last item)
        return cls(binascii.unhexlify(rd[-1].encode('ascii')))

    def __init__(self,data=b""):
        # Assume raw bytes
        check_bytes('data',data)
        self.data = bytes(data)

    def pack(self,buffer):
        """
            Pack record into buffer
        """
        buffer.append(self.data)

    def __repr__(self):
        """
            Default 'repr' format should be equivalent to RD zone format
        """
        # For unknown rdata just default to hex
        return binascii.hexlify(self.data).decode()

    def toZone(self):
        return repr(self)

    # Comparison operations - in most cases only need to override 'attrs'
    # in subclass (__eq__ will automatically compare defined atttrs)

    # Attributes for comparison
    attrs = ('data',)

    def __eq__(self,other):
        if type(other) != type(self):
            return False
        else:
            return all([getattr(self,x) == getattr(other,x) for x in self.attrs])

    def __ne__(self,other):
        return not(self.__eq__(other))

def _force_bytes(x):
    if isinstance(x,bytes):
        return x
    else:
        return x.encode()

class TXT(RD):
    """
        DNS TXT record. Pass in either a single string, or a tuple/list of strings.

        >>> TXT('txtvers=1')
        "txtvers=1"
        >>> TXT(('txtvers=1',))
        "txtvers=1"
        >>> TXT(['txtvers=1',])
        "txtvers=1"
        >>> TXT(['txtvers=1','swver=2.5'])
        "txtvers=1","swver=2.5"
        >>> a = DNSRecord()
        >>> a.add_answer(*RR.fromZone('example.com 60 IN TXT "txtvers=1"'))
        >>> a.add_answer(*RR.fromZone('example.com 120 IN TXT "txtvers=1" "swver=2.3"'))
        >>> print(a)
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
        ;; flags: rd; QUERY: 0, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0
        ;; ANSWER SECTION:
        example.com.            60      IN      TXT     "txtvers=1"
        example.com.            120     IN      TXT     "txtvers=1" "swver=2.3"
    """

    @classmethod
    def parse(cls,buffer,length):
        try:
            data = list()
            start_bo = buffer.offset
            now_length = 0
            while buffer.offset < start_bo + length:
                (txtlength,) = buffer.unpack("!B")
                # First byte is TXT length (not in RFC?)
                if now_length + txtlength < length:
                    now_length += txtlength
                    data.append(buffer.get(txtlength))
                else:
                    raise DNSError("Invalid TXT record: len(%d) > RD len(%d)" % 
                                            (txtlength,length))
            return cls(data)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking TXT [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(list(map(lambda x: x.encode(), rd)))

    def __init__(self,data):
        if type(data) in (tuple,list):
            self.data = [ _force_bytes(x) for x in data ]
        else:
            self.data = [ _force_bytes(data) ]
        if any([len(x)>255 for x in self.data]):
            raise DNSError("TXT record too long: %s" % self.data)

    def pack(self,buffer):
        for ditem in self.data:
            if len(ditem) > 255:
                raise DNSError("TXT record too long: %s" % ditem)
            buffer.pack("!B",len(ditem))
            buffer.append(ditem)

    def toZone(self):
        return " ".join([ '"%s"' % x.decode(errors='replace') for x in self.data ])

    def __repr__(self):
        return ",".join([ '"%s"' % x.decode(errors='replace') for x in self.data ])

class A(RD):

    data = IP4('data')

    @classmethod
    def parse(cls,buffer,length):
        try:
            data = buffer.unpack("!BBBB")
            return cls(data)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking A [offset=%d]: %s" % 
                                (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(rd[0])

    def __init__(self,data):
        if type(data) in (tuple,list):
            self.data = tuple(data)
        else:
            self.data = tuple(map(int,data.rstrip(".").split(".")))

    def pack(self,buffer):
        buffer.pack("!BBBB",*self.data)

    def __repr__(self):
        return "%d.%d.%d.%d" % self.data

def _parse_ipv6(a):
    """
        Parse IPv6 address. Ideally we would use the ipaddress module in 
        Python3.3 but can't rely on having this.

        Does not handle dotted-quad addresses or subnet prefix

        >>> _parse_ipv6("::") == (0,) * 16
        True
        >>> _parse_ipv6("1234:5678::abcd:0:ff00")
        (18, 52, 86, 120, 0, 0, 0, 0, 0, 0, 171, 205, 0, 0, 255, 0)

    """
    l,_,r = a.partition("::")
    l_groups = list(chain(*[divmod(int(x,16),256) for x in l.split(":") if x]))
    r_groups = list(chain(*[divmod(int(x,16),256) for x in r.split(":") if x]))
    zeros = [0] * (16 - len(l_groups) - len(r_groups))
    return tuple(l_groups + zeros + r_groups) 

def _format_ipv6(a):
    """
        Format IPv6 address (from tuple of 16 bytes) compressing sequence of
        zero bytes to '::'. Ideally we would use the ipaddress module in
        Python3.3 but can't rely on having this.

        >>> _format_ipv6([0]*16)
        '::'
        >>> _format_ipv6(_parse_ipv6("::0012:5678"))
        '::12:5678'
        >>> _format_ipv6(_parse_ipv6("1234:0:5678::ff:0:1"))
        '1234:0:5678::ff:0:1'
    """
    left = []
    right = []
    current = 'left'
    for i in range(0,16,2):
        group = (a[i] << 8) + a[i+1]
        if current == 'left':
            if group == 0 and i < 14:
                if (a[i+2] << 8) + a[i+3] == 0:
                    current = 'right'
                else:
                    left.append("0")
            else:
                left.append("%x" % group)
        else:
            if group == 0 and len(right) == 0:
                pass
            else:
                right.append("%x" % group)
    if len(left) < 8:
        return ":".join(left) + "::" + ":".join(right)
    else:
        return ":".join(left)
    
class AAAA(RD):

    """
        Basic support for AAAA record - accepts IPv6 address data as either
        a tuple of 16 bytes or in text format
    """
 
    data = IP6('data')

    @classmethod
    def parse(cls,buffer,length):
        try:
            data = buffer.unpack("!16B")
            return cls(data)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking AAAA [offset=%d]: %s" % 
                                        (buffer.offset,e))
 
    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(rd[0])

    def __init__(self,data):
        if type(data) in (tuple,list):
            self.data = tuple(data)
        else:
            self.data = _parse_ipv6(data)

    def pack(self,buffer):
        buffer.pack("!16B",*self.data)

    def __repr__(self):
        return _format_ipv6(self.data)

class MX(RD):

    preference = H('preference')

    @classmethod
    def parse(cls,buffer,length):
        try:
            (preference,) = buffer.unpack("!H")
            mx = buffer.decode_name()
            return cls(mx,preference)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking MX [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(label(rd[1],origin),int(rd[0]))

    def __init__(self,label=None,preference=10):
        self.label = label
        self.preference = preference

    def set_label(self,label):
        if isinstance(label,DNSLabel):
            self._label = label
        else:
            self._label = DNSLabel(label)

    def get_label(self):
        return self._label

    label = property(get_label,set_label)

    def pack(self,buffer):
        buffer.pack("!H",self.preference)
        buffer.encode_name(self.label)
        
    def __repr__(self):
        return "%d %s" % (self.preference,self.label)

    attrs = ('preference','label')

class CNAME(RD):
        
    @classmethod
    def parse(cls,buffer,length):
        try:
            label = buffer.decode_name()
            return cls(label)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking CNAME [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(label(rd[0],origin))

    def __init__(self,label=None):
        self.label = label

    def set_label(self,label):
        if isinstance(label,DNSLabel):
            self._label = label
        else:
            self._label = DNSLabel(label)

    def get_label(self):
        return self._label

    label = property(get_label,set_label)

    def pack(self,buffer):
        buffer.encode_name(self.label)

    def __repr__(self):
        return "%s" % (self.label)

    attrs = ('label',)

class PTR(CNAME):
    pass

class NS(CNAME):
    pass

class SOA(RD):
        
    times = ntuple_range('times',5,0,4294967295)
    @classmethod
    def parse(cls,buffer,length):
        try:
            mname = buffer.decode_name()
            rname = buffer.decode_name()
            times = buffer.unpack("!IIIII")
            return cls(mname,rname,times)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking SOA [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(label(rd[0],origin),label(rd[1],origin),[parse_time(t) for t in rd[2:]])

    def __init__(self,mname=None,rname=None,times=None):
        self.mname = mname
        self.rname = rname
        self.times = tuple(times) if times else (0,0,0,0,0)

    def set_mname(self,mname):
        if isinstance(mname,DNSLabel):
            self._mname = mname
        else:
            self._mname = DNSLabel(mname)

    def get_mname(self):
        return self._mname

    mname = property(get_mname,set_mname)

    def set_rname(self,rname):
        if isinstance(rname,DNSLabel):
            self._rname = rname
        else:
            self._rname = DNSLabel(rname)

    def get_rname(self):
        return self._rname

    rname = property(get_rname,set_rname)

    def pack(self,buffer):
        buffer.encode_name(self.mname)
        buffer.encode_name(self.rname)
        buffer.pack("!IIIII", *self.times)

    def __repr__(self):
        return "%s %s %s" % (self.mname,self.rname,
                             " ".join(map(str,self.times)))

    attrs = ('mname','rname','times')

class SRV(RD):
        
    priority = H('priority')
    weight = H('weight')
    port = H('port')

    @classmethod
    def parse(cls,buffer,length):
        try:
            priority,weight,port = buffer.unpack("!HHH")
            target = buffer.decode_name()
            return cls(priority,weight,port,target)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking SRV [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(int(rd[0]),int(rd[1]),int(rd[2]),rd[3])

    def __init__(self,priority=0,weight=0,port=0,target=None):
        self.priority = priority
        self.weight = weight
        self.port = port
        self.target = target

    def set_target(self,target):
        if isinstance(target,DNSLabel):
            self._target = target
        else:
            self._target = DNSLabel(target)

    def get_target(self):
        return self._target

    target = property(get_target,set_target)
    
    def pack(self,buffer):
        buffer.pack("!HHH",self.priority,self.weight,self.port)
        buffer.encode_name(self.target)

    def __repr__(self):
        return "%d %d %d %s" % (self.priority,self.weight,self.port,self.target)

    attrs = ('priority','weight','port','target')

class NAPTR(RD):

    order = H('order')
    preference = H('preference')

    @classmethod
    def parse(cls, buffer, length):
        try:
            order, preference = buffer.unpack('!HH')
            (length,) = buffer.unpack('!B')
            flags = buffer.get(length)
            (length,) = buffer.unpack('!B')
            service = buffer.get(length)
            (length,) = buffer.unpack('!B')
            regexp = buffer.get(length)
            replacement = buffer.decode_name()
            return cls(order, preference, flags, service, regexp, replacement)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking NAPTR [offset=%d]: %s" % 
                                    (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        encode = lambda s : s.encode()
        _label = lambda s : label(s,origin)
        m = (int,int,encode,encode,encode,_label)
        return cls(*[ f(v) for f,v in zip(m,rd)])

    def __init__(self,order,preference,flags,service,regexp,replacement=None):
        self.order = order
        self.preference = preference
        self.flags = flags
        self.service = service
        self.regexp = regexp
        self.replacement = replacement

    def set_replacement(self,replacement):
        if isinstance(replacement,DNSLabel):
            self._replacement = replacement
        else:
            self._replacement = DNSLabel(replacement)

    def get_replacement(self):
        return self._replacement

    replacement = property(get_replacement,set_replacement)

    def pack(self, buffer):
        buffer.pack('!HH', self.order, self.preference)
        buffer.pack('!B', len(self.flags))
        buffer.append(self.flags)
        buffer.pack('!B', len(self.service))
        buffer.append(self.service)
        buffer.pack('!B', len(self.regexp))
        buffer.append(self.regexp)
        buffer.encode_name(self.replacement)

    def __repr__(self):
        return '%d %d "%s" "%s" "%s" %s' %(
            self.order,self.preference,self.flags.decode(),
            self.service.decode(),
            self.regexp.decode().replace('\\','\\\\'),
            self.replacement or '.'
        )

    attrs = ('order','preference','flags','service','regexp','replacement')

class DNSKEY(RD):

    flags = H('flags')
    protocol = B('protocol')
    algorithm = B('algorithm')

    @classmethod
    def parse(cls,buffer,length):
        try:
            (flags,protocol,algorithm) = buffer.unpack("!HBB")
            key = buffer.get(length - 4)
            return cls(flags,protocol,algorithm,key)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking DNSKEY [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(int(rd[0]),int(rd[1]),int(rd[2]),
                   base64.b64decode(("".join(rd[3:])).encode('ascii')))

    def __init__(self,flags,protocol,algorithm,key):
        self.flags = flags
        self.protocol = protocol
        self.algorithm = algorithm
        self.key = key

    def pack(self,buffer):
        buffer.pack("!HBB",self.flags,self.protocol,self.algorithm)
        buffer.append(self.key)
        
    def __repr__(self):
        return "%d %d %d %s" % (self.flags,self.protocol,self.algorithm,
                                base64.b64encode(self.key).decode())

    attrs = ('flags','protocol','algorithm','key')

class RRSIG(RD):

    covered = H('covered')
    algorithm = B('algorithm')
    labels = B('labels')
    orig_ttl = I('orig_ttl')
    sig_exp = I('sig_exp')
    sig_inc = I('sig_inc')
    key_tag = H('key_tag')

    @classmethod
    def parse(cls,buffer,length):
        try:
            start = buffer.offset
            (covered,algorithm,labels,
                orig_ttl,sig_exp,sig_inc,key_tag) = buffer.unpack("!HBBIIIH")
            name = buffer.decode_name()
            sig = buffer.get(length - (buffer.offset - start))
            return cls(covered,algorithm,labels,orig_ttl,sig_exp,sig_inc,key_tag,
                            name,sig)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking DNSKEY [offset=%d]: %s" % 
                                        (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        return cls(getattr(QTYPE,rd[0]),int(rd[1]),int(rd[2]),int(rd[3]),
                        int(calendar.timegm(time.strptime(rd[4]+'UTC',"%Y%m%d%H%M%S%Z"))),
                        int(calendar.timegm(time.strptime(rd[5]+'UTC',"%Y%m%d%H%M%S%Z"))),
                        int(rd[6]),rd[7],
                        base64.b64decode(("".join(rd[8:])).encode('ascii')))

    def __init__(self,covered,algorithm,labels,orig_ttl,
                      sig_exp,sig_inc,key_tag,name,sig):
        self.covered = covered
        self.algorithm = algorithm
        self.labels = labels
        self.orig_ttl = orig_ttl
        self.sig_exp = sig_exp
        self.sig_inc = sig_inc
        self.key_tag = key_tag
        self.name = DNSLabel(name)
        self.sig = sig

    def pack(self,buffer):
        buffer.pack("!HBBIIIH",self.covered,self.algorithm,self.labels,
                               self.orig_ttl,self.sig_exp,self.sig_inc,
                               self.key_tag)
        buffer.encode_name_nocompress(self.name)
        buffer.append(self.sig)
        
    def __repr__(self):
        timestamp_fmt = "{0.tm_year}{0.tm_mon:02}{0.tm_mday:02}{0.tm_hour:02}{0.tm_min:02}{0.tm_sec:02}"
        return "%s %d %d %d %s %s %d %s %s" % (
                        QTYPE.get(self.covered),
                        self.algorithm,
                        self.labels,
                        self.orig_ttl,
                        timestamp_fmt.format(time.gmtime(self.sig_exp)),
                        timestamp_fmt.format(time.gmtime(self.sig_inc)),
                        self.key_tag,
                        self.name,
                        base64.b64encode(self.sig).decode())

    attrs = ('covered','algorithm','labels','orig_ttl','sig_exp','sig_inc',
             'key_tag','name','sig')

class CAA(RD):
    """
        CAA record.

        >>> CAA(0, 'issue', 'letsencrypt.org')
        0 issue \"letsencrypt.org\"
        >>> a = DNSRecord()
        >>> a.add_answer(*RR.fromZone('example.com 60 IN CAA 0 issue "letsencrypt.org"'))
        >>> print(a)
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
        ;; flags: rd; QUERY: 0, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
        ;; ANSWER SECTION:
        example.com.            60      IN      CAA     0 issue "letsencrypt.org"
    """

    @classmethod
    def parse(cls,buffer,length):
        try:
            (flags, tag_length) = buffer.unpack("!BB")
            tag = buffer.get(tag_length).decode()
            value = buffer.get(length - tag_length - 2).decode() 
            return cls(flags, tag, value)
        except (BufferError,BimapError) as e:
            raise DNSError("Error unpacking CAA [offset=%d]: %s" % 
                               (buffer.offset,e))

    @classmethod
    def fromZone(cls,rd,origin=None):
        if len(rd) == 1:
            try:
                hex_parsed = bytes.fromhex(rd[0])
                flags = hex_parsed[0]
                tag_length = hex_parsed[1]
            except:
                hex_parsed = rd[0].decode('hex').encode()
                flags = ord(hex_parsed[0])
                tag_length = ord(hex_parsed[1])
            tag = hex_parsed[2:2+tag_length].decode()
            value = hex_parsed[tag_length+2:].decode()
        else:
            (flags, tag, value) = rd
        return cls(int(flags), tag, value.replace('"', ''))

    def __init__(self, flags, tag, value):
        self.flags = flags
        self.tag = tag
        self.value = value
        self.data = None

    def pack(self,buffer):
        buffer.pack("!BB", self.flags, len(self.tag))
        buffer.append(self.tag.encode())
        buffer.append(self.value.encode())

    def toZone(self):
        return "%d %s \"%s\"" % (self.flags, self.tag, self.value)

    def __repr__(self):
        return "%d %s \"%s\"" % (self.flags, self.tag, self.value)




# Map from RD type to class (used to pack/unpack records)
# If you add a new RD class you must add to RDMAP

RDMAP = { 'CNAME':CNAME, 'A':A, 'AAAA':AAAA, 'TXT':TXT, 'MX':MX, 
          'PTR':PTR, 'SOA':SOA, 'NS':NS, 'NAPTR': NAPTR, 'SRV':SRV,
          'DNSKEY':DNSKEY, 'RRSIG':RRSIG, 'CAA':CAA
        }

##
## Zone parser
## TODO  - ideally this would be in a separate file but have to deal 
##         with circular dependencies 
##

secs = {'s':1,'m':60,'h':3600,'d':86400,'w':604800}

def parse_time(s):
    """
        Parse time spec with optional s/m/h/d/w suffix
    """
    if s[-1].lower() in secs:
        return int(s[:-1]) * secs[s[-1].lower()]
    else:
        return int(s)

class ZoneParser:

    """
        Zone file parser

        >>> z = ZoneParser("www.example.com. 60 IN A 1.2.3.4")
        >>> list(z.parse())
        [<DNS RR: 'www.example.com.' rtype=A rclass=IN ttl=60 rdata='1.2.3.4'>]
    """

    def __init__(self,zone,origin="",ttl=0):
        self.l = WordLexer(zone)
        self.l.commentchars = ';'
        self.l.nltok = ('NL',None)
        self.l.spacetok = ('SPACE',None)
        self.i = iter(self.l)
        if type(origin) is DNSLabel:
            self.origin = origin
        else:
            self.origin= DNSLabel(origin)
        self.ttl = ttl
        self.label = DNSLabel("")
        self.prev = None

    def expect(self,expect):
        t,val = next(self.i)
        if t != expect:
            raise ValueError("Invalid Token: %s (expecting: %s)" % (t,expect))
        return val

    def parse_label(self,label):
        if label.endswith("."):
            self.label = DNSLabel(label)
        elif label == "@":
            self.label = self.origin
        elif label == '':
            pass
        else:
            self.label = self.origin.add(label)
        return self.label

    def parse_rr(self,rr):
        label = self.parse_label(rr.pop(0))
        ttl = int(rr.pop(0)) if rr[0].isdigit() else self.ttl
        rclass = rr.pop(0) if rr[0] in ('IN','CH','HS') else 'IN'
        rtype = rr.pop(0)
        rdata = rr
        rd = RDMAP.get(rtype,RD)
        return RR(rname=label,
                         ttl=ttl,
                         rclass=getattr(CLASS,rclass),
                         rtype=getattr(QTYPE,rtype),
                         rdata=rd.fromZone(rdata,self.origin))

    def __iter__(self):
        return self.parse()

    def parse(self):
        rr = []
        paren = False
        try:
            while True:
                tok,val = next(self.i)
                if tok == 'NL':
                    if not paren and rr:
                        self.prev = tok
                        yield self.parse_rr(rr)
                        rr = []
                elif tok == 'SPACE' and self.prev == 'NL' and not paren:
                    rr.append('')
                elif tok == 'ATOM':
                    if val == '(':
                        paren = True
                    elif val == ')':
                        paren = False
                    elif val == '$ORIGIN':
                        self.expect('SPACE')
                        origin = self.expect('ATOM')
                        self.origin = self.label = DNSLabel(origin)
                    elif val == '$TTL':
                        self.expect('SPACE')
                        ttl = self.expect('ATOM')
                        self.ttl = parse_time(ttl)
                    else:
                        rr.append(val)
                self.prev = tok
        except StopIteration:
            if rr:
                yield self.parse_rr(rr)

if __name__ == '__main__':
    import doctest
    doctest.testmod(optionflags=doctest.ELLIPSIS)

Added dnslib/fixedresolver.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
# -*- coding: utf-8 -*-

"""
    FixedResolver - example resolver which responds with fixed response
                    to all requests
"""

from __future__ import print_function

import copy

from dnslib import RR
from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger

class FixedResolver(BaseResolver):
    """
        Respond with fixed response to all requests
    """
    def __init__(self,zone):
        # Parse RRs
        self.rrs = RR.fromZone(zone)

    def resolve(self,request,handler):
        reply = request.reply()
        qname = request.q.qname
        # Replace labels with request label
        for rr in self.rrs:
            a = copy.copy(rr)
            a.rname = qname
            reply.add_answer(a)
        return reply

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="Fixed DNS Resolver")
    p.add_argument("--response","-r",default=". 60 IN A 127.0.0.1",
                    metavar="<response>",
                    help="DNS response (zone format) (default: 127.0.0.1)")
    p.add_argument("--zonefile","-f",
                    metavar="<zonefile>",
                    help="DNS response (zone file, '-' for stdin)")
    p.add_argument("--port","-p",type=int,default=53,
                    metavar="<port>",
                    help="Server port (default:53)")
    p.add_argument("--address","-a",default="",
                    metavar="<address>",
                    help="Listen address (default:all)")
    p.add_argument("--udplen","-u",type=int,default=0,
                    metavar="<udplen>",
                    help="Max UDP packet length (default:0)")
    p.add_argument("--tcp",action='store_true',default=False,
                    help="TCP server (default: UDP only)")
    p.add_argument("--log",default="request,reply,truncated,error",
                    help="Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)")
    p.add_argument("--log-prefix",action='store_true',default=False,
                    help="Log prefix (timestamp/handler/resolver) (default: False)")
    args = p.parse_args()
    
    if args.zonefile:
        if args.zonefile == '-':
            args.response = sys.stdin
        else:
            args.response = open(args.zonefile)

    resolver = FixedResolver(args.response)
    logger = DNSLogger(args.log,args.log_prefix)

    print("Starting Fixed Resolver (%s:%d) [%s]" % (
                        args.address or "*",
                        args.port,
                        "UDP/TCP" if args.tcp else "UDP"))

    for rr in resolver.rrs:
        print("    | ",rr.toZone().strip(),sep="")
    print()

    if args.udplen:
        DNSHandler.udplen = args.udplen

    udp_server = DNSServer(resolver,
                           port=args.port,
                           address=args.address,
                           logger=logger)
    udp_server.start_thread()

    if args.tcp:
        tcp_server = DNSServer(resolver,
                               port=args.port,
                               address=args.address,
                               tcp=True,
                               logger=logger)
        tcp_server.start_thread()

    while udp_server.isAlive():
        time.sleep(1)

Added dnslib/intercept.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
# -*- coding: utf-8 -*-

"""
    InterceptResolver - proxy requests to upstream server 
                        (optionally intercepting)
        
"""
from __future__ import print_function

import binascii,copy,socket,struct,sys

from dnslib import DNSRecord,RR,QTYPE,RCODE,parse_time
from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger
from dnslib.label import DNSLabel

class InterceptResolver(BaseResolver):

    """
        Intercepting resolver 
        
        Proxy requests to upstream server optionally intercepting requests
        matching local records
    """

    def __init__(self,address,port,ttl,intercept,skip,nxdomain,timeout=0):
        """
            address/port    - upstream server
            ttl             - default ttl for intercept records
            intercept       - list of wildcard RRs to respond to (zone format)
            skip            - list of wildcard labels to skip 
            nxdomain        - list of wildcard labels to retudn NXDOMAIN
            timeout         - timeout for upstream server
        """
        self.address = address
        self.port = port
        self.ttl = parse_time(ttl)
        self.skip = skip
        self.nxdomain = nxdomain
        self.timeout = timeout
        self.zone = []
        for i in intercept:
            if i == '-':
                i = sys.stdin.read()
            for rr in RR.fromZone(i,ttl=self.ttl):
                self.zone.append((rr.rname,QTYPE[rr.rtype],rr))

    def resolve(self,request,handler):
        reply = request.reply()
        qname = request.q.qname
        qtype = QTYPE[request.q.qtype]
        # Try to resolve locally unless on skip list
        if not any([qname.matchGlob(s) for s in self.skip]):
            for name,rtype,rr in self.zone:
                if qname.matchGlob(name) and (qtype in (rtype,'ANY','CNAME')):
                    a = copy.copy(rr)
                    a.rname = qname
                    reply.add_answer(a)
        # Check for NXDOMAIN
        if any([qname.matchGlob(s) for s in self.nxdomain]):
            reply.header.rcode = getattr(RCODE,'NXDOMAIN')
            return reply
        # Otherwise proxy
        if not reply.rr:
            try:
                if handler.protocol == 'udp':
                    proxy_r = request.send(self.address,self.port,
                                    timeout=self.timeout)
                else:
                    proxy_r = request.send(self.address,self.port,
                                    tcp=True,timeout=self.timeout)
                reply = DNSRecord.parse(proxy_r)
            except socket.timeout:
                reply.header.rcode = getattr(RCODE,'NXDOMAIN')

        return reply

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="DNS Intercept Proxy")
    p.add_argument("--port","-p",type=int,default=53,
                    metavar="<port>",
                    help="Local proxy port (default:53)")
    p.add_argument("--address","-a",default="",
                    metavar="<address>",
                    help="Local proxy listen address (default:all)")
    p.add_argument("--upstream","-u",default="8.8.8.8:53",
            metavar="<dns server:port>",
                    help="Upstream DNS server:port (default:8.8.8.8:53)")
    p.add_argument("--tcp",action='store_true',default=False,
                    help="TCP proxy (default: UDP only)")
    p.add_argument("--intercept","-i",action="append",
                    metavar="<zone record>",
                    help="Intercept requests matching zone record (glob) ('-' for stdin)")
    p.add_argument("--skip","-s",action="append",
                    metavar="<label>",
                    help="Don't intercept matching label (glob)")
    p.add_argument("--nxdomain","-x",action="append",
                    metavar="<label>",
                    help="Return NXDOMAIN (glob)")
    p.add_argument("--ttl","-t",default="60s",
                    metavar="<ttl>",
                    help="Intercept TTL (default: 60s)")
    p.add_argument("--timeout","-o",type=float,default=5,
                    metavar="<timeout>",
                    help="Upstream timeout (default: 5s)")
    p.add_argument("--log",default="request,reply,truncated,error",
                    help="Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)")
    p.add_argument("--log-prefix",action='store_true',default=False,
                    help="Log prefix (timestamp/handler/resolver) (default: False)")
    args = p.parse_args()

    args.dns,_,args.dns_port = args.upstream.partition(':')
    args.dns_port = int(args.dns_port or 53)

    resolver = InterceptResolver(args.dns,
                                 args.dns_port,
                                 args.ttl,
                                 args.intercept or [],
                                 args.skip or [],
                                 args.nxdomain or [],
                                 args.timeout)
    logger = DNSLogger(args.log,args.log_prefix)

    print("Starting Intercept Proxy (%s:%d -> %s:%d) [%s]" % (
                        args.address or "*",args.port,
                        args.dns,args.dns_port,
                        "UDP/TCP" if args.tcp else "UDP"))

    for rr in resolver.zone:
        print("    | ",rr[2].toZone(),sep="")
    if resolver.nxdomain:
        print("    NXDOMAIN:",", ".join(resolver.nxdomain))
    if resolver.skip:
        print("    Skipping:",", ".join(resolver.skip))
    print()


    DNSHandler.log = { 
        'log_request',      # DNS Request
        'log_reply',        # DNS Response
        'log_truncated',    # Truncated
        'log_error',        # Decoding error
    }

    udp_server = DNSServer(resolver,
                           port=args.port,
                           address=args.address,
                           logger=logger)
    udp_server.start_thread()

    if args.tcp:
        tcp_server = DNSServer(resolver,
                               port=args.port,
                               address=args.address,
                               tcp=True,
                               logger=logger)
        tcp_server.start_thread()

    while udp_server.isAlive():
        time.sleep(1)

Added dnslib/label.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
# -*- coding: utf-8 -*-

"""
    DNSLabel/DNSBuffer - DNS label handling & encoding/decoding
"""

from __future__ import print_function

import fnmatch

from dnslib.bit import get_bits,set_bits
from dnslib.buffer import Buffer, BufferError

class DNSLabelError(Exception):
    pass

class DNSLabel(object):

    """
    Container for DNS label

    Supports IDNA encoding for unicode domain names

    >>> l1 = DNSLabel("aaa.bbb.ccc.")
    >>> l2 = DNSLabel([b"aaa",b"bbb",b"ccc"])
    >>> l1 == l2
    True
    >>> l3 = DNSLabel("AAA.BBB.CCC")
    >>> l1 == l3
    True
    >>> l1 == 'AAA.BBB.CCC'
    True
    >>> x = { l1 : 1 }
    >>> x[l1]
    1
    >>> l1
    <DNSLabel: 'aaa.bbb.ccc.'>
    >>> str(l1)
    'aaa.bbb.ccc.'
    >>> l3 = l1.add("xxx.yyy")
    >>> l3
    <DNSLabel: 'xxx.yyy.aaa.bbb.ccc.'>
    >>> l3.matchSuffix(l1)
    True
    >>> l3.matchSuffix("xxx.yyy.")
    False
    >>> l3.stripSuffix("bbb.ccc.")
    <DNSLabel: 'xxx.yyy.aaa.'>
    >>> l3.matchGlob("*.[abc]aa.BBB.ccc")
    True
    >>> l3.matchGlob("*.[abc]xx.bbb.ccc")
    False

    # Too hard to get unicode doctests to work on Python 3.2  
    # (works on 3.3)
    # >>> u1 = DNSLabel(u'\u2295.com')
    # >>> u1.__str__() == u'\u2295.com.'
    # True
    # >>> u1.label == ( b"xn--keh", b"com" )
    # True

    """
    def __init__(self,label):
        """
            Create DNS label instance 

            Label can be specified as:
            - a list/tuple of byte strings
            - a byte string (split into components separated by b'.')
            - a unicode string which will be encoded according to RFC3490/IDNA
        """
        if type(label) == DNSLabel:
            self.label = label.label
        elif type(label) in (list,tuple):
            self.label = tuple(label)
        else:
            if not label or label in (b'.','.'):
                self.label = ()
            elif type(label) is not bytes:
                self.label = tuple(label.encode("idna").\
                                rstrip(b".").split(b"."))
            else:
                self.label = tuple(label.rstrip(b".").split(b"."))

    def add(self,name):
        """
            Prepend name to label 
        """
        new = DNSLabel(name)
        if self.label:
            new.label += self.label
        return new

    def matchGlob(self,pattern):
        if type(pattern) != DNSLabel:
            pattern = DNSLabel(pattern)
        return fnmatch.fnmatch(str(self).lower(),str(pattern).lower())

    def matchSuffix(self,suffix):
        """
            Return True if label suffix matches 
        """
        suffix = DNSLabel(suffix)
        return self.label[-len(suffix.label):] == suffix.label

    def stripSuffix(self,suffix):
        """
            Strip suffix from label
        """
        suffix = DNSLabel(suffix)
        if self.label[-len(suffix.label):] == suffix.label:
            return DNSLabel(self.label[:-len(suffix.label)])
        else:
            return self

    def idna(self):
        return ".".join([ s.decode("idna") for s in self.label ]) + "."

    def __str__(self):
        return ".".join([ s.decode() for s in self.label ]) + "."

    def __repr__(self):
        return "<DNSLabel: '%s'>" % str(self)

    def __hash__(self):
        return hash(self.label)

    def __ne__(self,other):
        return not self == other

    def __eq__(self,other):
        if type(other) != DNSLabel:
            return self.__eq__(DNSLabel(other))
        else:
            return [ l.lower() for l in self.label ] == \
                   [ l.lower() for l in other.label ]

    def __len__(self):
        return len(b'.'.join(self.label))

class DNSBuffer(Buffer):

    """
    Extends Buffer to provide DNS name encoding/decoding (with caching)

    # Needed for Python 2/3 doctest compatibility
    >>> def p(s):
    ...     if not isinstance(s,str):
    ...         return s.decode()
    ...     return s

    >>> b = DNSBuffer()
    >>> b.encode_name(b'aaa.bbb.ccc.')
    >>> len(b)
    13
    >>> b.encode_name(b'aaa.bbb.ccc.')
    >>> len(b)
    15
    >>> b.encode_name(b'xxx.yyy.zzz')
    >>> len(b)
    28
    >>> b.encode_name(b'zzz.xxx.bbb.ccc.')
    >>> len(b)
    38
    >>> b.encode_name(b'aaa.xxx.bbb.ccc')
    >>> len(b)
    44
    >>> b.offset = 0
    >>> print(b.decode_name())
    aaa.bbb.ccc.
    >>> print(b.decode_name())
    aaa.bbb.ccc.
    >>> print(b.decode_name())
    xxx.yyy.zzz.
    >>> print(b.decode_name())
    zzz.xxx.bbb.ccc.
    >>> print(b.decode_name())
    aaa.xxx.bbb.ccc.

    >>> b = DNSBuffer()
    >>> b.encode_name([b'a.aa',b'b.bb',b'c.cc'])
    >>> b.offset = 0
    >>> len(b.decode_name().label)
    3

    >>> b = DNSBuffer()
    >>> b.encode_name_nocompress(b'aaa.bbb.ccc.')
    >>> len(b)
    13
    >>> b.encode_name_nocompress(b'aaa.bbb.ccc.')
    >>> len(b)
    26
    >>> b.offset = 0
    >>> print(b.decode_name())
    aaa.bbb.ccc.
    >>> print(b.decode_name())
    aaa.bbb.ccc.
    """

    def __init__(self,data=b''):
        """
            Add 'names' dict to cache stored labels
        """
        super(DNSBuffer,self).__init__(data)
        self.names = {}

    def decode_name(self,last=-1):
        """
            Decode label at current offset in buffer (following pointers
            to cached elements where necessary)
        """
        label = []
        done = False
        while not done:
            (length,) = self.unpack("!B")
            if get_bits(length,6,2) == 3:
                # Pointer
                self.offset -= 1
                pointer = get_bits(self.unpack("!H")[0],0,14)
                save = self.offset
                if last == save:
                    raise BufferError("Recursive pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % 
                            (self.offset,pointer,len(self.data)))
                if pointer < self.offset:
                    self.offset = pointer
                else:
                    # Pointer can't point forwards
                    raise BufferError("Invalid pointer in DNSLabel [offset=%d,pointer=%d,length=%d]" % 
                            (self.offset,pointer,len(self.data)))
                label.extend(self.decode_name(save).label)
                self.offset = save
                done = True
            else:
                if length > 0:
                    l = self.get(length)
                    try:
                        l.decode()
                    except UnicodeDecodeError:
                        raise BufferError("Invalid label <%s>" % l)
                    label.append(l)
                else:
                    done = True
        return DNSLabel(label)

    def encode_name(self,name):
        """
            Encode label and store at end of buffer (compressing
            cached elements where needed) and store elements
            in 'names' dict
        """
        if not isinstance(name,DNSLabel):
            name = DNSLabel(name)
        if len(name) > 253:
            raise DNSLabelError("Domain label too long: %r" % name)
        name = list(name.label)
        while name:
            if tuple(name) in self.names:
                # Cached - set pointer
                pointer = self.names[tuple(name)]
                pointer = set_bits(pointer,3,14,2)
                self.pack("!H",pointer)
                return
            else:
                self.names[tuple(name)] = self.offset
                element = name.pop(0)
                if len(element) > 63:
                    raise DNSLabelError("Label component too long: %r" % element)
                self.pack("!B",len(element))
                self.append(element)
        self.append(b'\x00')

    def encode_name_nocompress(self,name):
        """
            Encode and store label with no compression 
            (needed for RRSIG)
        """
        if not isinstance(name,DNSLabel):
            name = DNSLabel(name)
        if len(name) > 253:
            raise DNSLabelError("Domain label too long: %r" % name)
        name = list(name.label)
        while name:
            element = name.pop(0)
            if len(element) > 63:
                raise DNSLabelError("Label component too long: %r" % element)
            self.pack("!B",len(element))
            self.append(element)
        self.append(b'\x00')

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Added dnslib/lex.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
# -*- coding: utf-8 -*-

from __future__ import print_function

import collections,string

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

class Lexer(object):

    """
        Simple Lexer base class. Provides basic lexer framework and 
        helper functionality (read/peek/pushback etc)

        Each state is implemented using a method (lexXXXX) which should
        match a single token and return a (token,lexYYYY) tuple, with lexYYYY
        representing the next state. If token is None this is not emitted
        and if lexYYYY is None or the lexer reaches the end of the 
        input stream the lexer exits.

        The 'parse' method returns a generator that will return tokens
        (the class also acts as an iterator)

        The default start state is 'lexStart'

        Input can either be a string/bytes or file object.

        The approach is based loosely on Rob Pike's Go lexer presentation
        (using generators rather than channels).

        >>> p = Lexer("a bcd efgh")
        >>> p.read()
        'a'
        >>> p.read()
        ' '
        >>> p.peek(3)
        'bcd'
        >>> p.read(5)
        'bcd e'
        >>> p.pushback('e')
        >>> p.read(4)
        'efgh'
    """

    escape_chars = '\\'
    escape = {'n':'\n','t':'\t','r':'\r'}

    def __init__(self,f,debug=False):
        if hasattr(f,'read'):
            self.f = f
        elif type(f) == str:
            self.f = StringIO(f)
        elif type(f) == bytes:
            self.f = StringIO(f.decode())
        else:
            raise ValueError("Invalid input")
        self.debug = debug
        self.q = collections.deque()
        self.state = self.lexStart
        self.escaped = False
        self.eof = False

    def __iter__(self):
        return self.parse()

    def next_token(self):
        if self.debug:
            print("STATE",self.state)
        (tok,self.state) = self.state()
        return tok

    def parse(self):
        while self.state is not None and not self.eof:
            tok = self.next_token()
            if tok:
                yield tok 

    def read(self,n=1):
        s = ""
        while self.q and n > 0:
            s += self.q.popleft()
            n -= 1
        s += self.f.read(n)
        if s == '':
            self.eof = True
        if self.debug:
            print("Read: >%s<" % repr(s))
        return s

    def peek(self,n=1):
        s = ""
        i = 0
        while len(self.q) > i and n > 0:
            s += self.q[i]
            i += 1
            n -= 1
        r = self.f.read(n)
        if n > 0 and r == '':
            self.eof = True
        self.q.extend(r)
        if self.debug:
            print("Peek : >%s<" % repr(s + r))
        return s + r

    def pushback(self,s):
        p = collections.deque(s)
        p.extend(self.q)
        self.q = p

    def readescaped(self):
        c = self.read(1)
        if c in self.escape_chars:
            self.escaped = True
            n = self.peek(3)
            if n.isdigit():
                n = self.read(3)
                if self.debug:
                    print("Escape: >%s<" % n)
                return chr(int(n,8))
            elif n[0] in 'x':
                x = self.read(3)
                if self.debug:
                    print("Escape: >%s<" % x)
                return chr(int(x[1:],16))
            else:
                c = self.read(1)
                if self.debug:
                    print("Escape: >%s<" % c)
                return self.escape.get(c,c)
        else:
            self.escaped = False
            return c

    def lexStart(self):
        return (None,None)

class WordLexer(Lexer):
    """
        Example lexer which will split input stream into words (respecting
        quotes)

        To emit SPACE tokens: self.spacetok = ('SPACE',None)
        To emit NL tokens: self.nltok = ('NL',None)

        >>> l = WordLexer(r'abc "def\100\x3d\. ghi" jkl')
        >>> list(l)
        [('ATOM', 'abc'), ('ATOM', 'def@=. ghi'), ('ATOM', 'jkl')]
        >>> l = WordLexer(r"1 '2 3 4' 5")
        >>> list(l)
        [('ATOM', '1'), ('ATOM', '2 3 4'), ('ATOM', '5')]
        >>> l = WordLexer("abc# a comment")
        >>> list(l)
        [('ATOM', 'abc'), ('COMMENT', 'a comment')]
    """

    wordchars = set(string.ascii_letters) | set(string.digits) | \
                set(string.punctuation)
    quotechars = set('"\'')
    commentchars = set('#')
    spacechars = set(' \t\x0b\x0c')
    nlchars = set('\r\n')
    spacetok = None
    nltok = None

    def lexStart(self):
        return (None,self.lexSpace)

    def lexSpace(self):
        s = []
        if self.spacetok:
            tok = lambda n : (self.spacetok,n) if s else (None,n)
        else:
            tok = lambda n : (None,n)
        while not self.eof:
            c = self.peek()
            if c in self.spacechars:
                s.append(self.read())
            elif c in self.nlchars:
                return tok(self.lexNL)
            elif c in self.commentchars:
                return tok(self.lexComment)
            elif c in self.quotechars:
                return tok(self.lexQuote)
            elif c in self.wordchars:
                return tok(self.lexWord)
                return (self.spacetok,self.lexWord)
            elif c:
                raise ValueError("Invalid input [%d]: %s" % (
                                        self.f.tell(),c))
        return (None,None)

    def lexNL(self):
        while True:
            c = self.read()
            if c not in self.nlchars:
                self.pushback(c)
                return (self.nltok,self.lexSpace)

    def lexComment(self):
        s = []
        tok = lambda n : (('COMMENT',''.join(s)),n) if s else (None,n) 
        start = False
        _ = self.read()
        while not self.eof:
            c = self.read()
            if c == '\n':
                self.pushback(c)
                return tok(self.lexNL)
            elif start or c not in string.whitespace:
                start = True
                s.append(c)
        return tok(None)

    def lexWord(self):
        s = []
        tok = lambda n : (('ATOM',''.join(s)),n) if s else (None,n) 
        while not self.eof:
            c = self.peek()
            if c == '"':
                return tok(self.lexQuote)
            elif c in self.commentchars:
                return tok(self.lexComment)
            elif c.isspace():
                return tok(self.lexSpace)
            elif c in self.wordchars:
                s.append(self.read())
            elif c:
                raise ValueError('Invalid input [%d]: %s' % (
                                    self.f.tell(),c))
        return tok(None)

    def lexQuote(self):
        s = []
        tok = lambda n : (('ATOM',''.join(s)),n) 
        q = self.read(1)
        while not self.eof:
            c = self.readescaped()
            if c == q and not self.escaped:
                break
            else:
                s.append(c)
        return tok(self.lexSpace)

class RandomLexer(Lexer):

    """
        Test lexing from infinite stream. 

        Extract strings of letters/numbers from /dev/urandom

        >>> import itertools,sys
        >>> if sys.version[0] == '2':
        ...     f = open("/dev/urandom")
        ... else:
        ...     f = open("/dev/urandom",encoding="ascii",errors="replace")
        >>> r = RandomLexer(f)
        >>> i = iter(r)
        >>> len(list(itertools.islice(i,10)))
        10
    """

    minalpha = 4
    mindigits = 3

    def lexStart(self):
        return (None,self.lexRandom)

    def lexRandom(self):
        n = 0
        c = self.peek(1)
        while not self.eof:
            if c.isalpha():
                return (None,self.lexAlpha)
            elif c.isdigit():
                return (None,self.lexDigits)
            else:
                n += 1
                _ = self.read(1)
                c = self.peek(1)
        return (None,None)

    def lexDigits(self):
        s = []
        c = self.read(1)
        while c.isdigit():
            s.append(c)
            c = self.read(1)
        self.pushback(c)
        if len(s) >= self.mindigits:
            return (('NUMBER',"".join(s)),self.lexRandom)
        else:
            return (None,self.lexRandom)

    def lexAlpha(self):
        s = []
        c = self.read(1)
        while c.isalpha():
            s.append(c)
            c = self.read(1)
        self.pushback(c)
        if len(s) >= self.minalpha:
            return (('STRING',"".join(s)),self.lexRandom)
        else:
            return (None,self.lexRandom)

if __name__ == '__main__':

    import argparse,doctest,sys

    p = argparse.ArgumentParser(description="Lex Tester")
    p.add_argument("--lex","-l",action='store_true',default=False,
                    help="Lex input (stdin)")
    p.add_argument("--nl",action='store_true',default=False,
                    help="Output NL tokens")
    p.add_argument("--space",action='store_true',default=False,
                    help="Output Whitespace tokens")
    p.add_argument("--wordchars",help="Wordchars")
    p.add_argument("--quotechars",help="Quotechars")
    p.add_argument("--commentchars",help="Commentchars")
    p.add_argument("--spacechars",help="Spacechars")
    p.add_argument("--nlchars",help="NLchars")

    args = p.parse_args()

    if args.lex:
        l = WordLexer(sys.stdin)
        if args.wordchars:
            l.wordchars = set(args.wordchars)
        if args.quotechars:
            l.quotechars = set(args.quotechars)
        if args.commentchars:
            l.commentchars = set(args.commentchars)
        if args.spacechars:
            l.spacechars = set(args.spacechars)
        if args.nlchars:
            l.nlchars = set(args.nlchars)
        if args.space:
            l.spacetok = ('SPACE',)
        if args.nl:
            l.nltok = ('NL',)

        for tok in l:
            print(tok)
    else:
        try:
            # Test if we have /dev/urandom
            open("/dev/urandom")
            doctest.testmod()
        except IOError:
            # Don't run stream test
            doctest.run_docstring_examples(Lexer, globals())
            doctest.run_docstring_examples(WordLexer, globals())

Added dnslib/proxy.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
# -*- coding: utf-8 -*-

from __future__ import print_function

import binascii,socket,struct

from dnslib import DNSRecord,RCODE
from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger

class ProxyResolver(BaseResolver):
    """
        Proxy resolver - passes all requests to upstream DNS server and
        returns response

        Note that the request/response will be each be decoded/re-encoded 
        twice:

        a) Request packet received by DNSHandler and parsed into DNSRecord 
        b) DNSRecord passed to ProxyResolver, serialised back into packet 
           and sent to upstream DNS server
        c) Upstream DNS server returns response packet which is parsed into
           DNSRecord
        d) ProxyResolver returns DNSRecord to DNSHandler which re-serialises
           this into packet and returns to client

        In practice this is actually fairly useful for testing but for a
        'real' transparent proxy option the DNSHandler logic needs to be
        modified (see PassthroughDNSHandler)

    """

    def __init__(self,address,port,timeout=0):
        self.address = address
        self.port = port
        self.timeout = timeout

    def resolve(self,request,handler):
        try:
            if handler.protocol == 'udp':
                proxy_r = request.send(self.address,self.port,
                                timeout=self.timeout)
            else:
                proxy_r = request.send(self.address,self.port,
                                tcp=True,timeout=self.timeout)
            reply = DNSRecord.parse(proxy_r)
        except socket.timeout:
            reply = request.reply()
            reply.header.rcode = getattr(RCODE,'NXDOMAIN')

        return reply

class PassthroughDNSHandler(DNSHandler):
    """
        Modify DNSHandler logic (get_reply method) to send directly to 
        upstream DNS server rather then decoding/encoding packet and
        passing to Resolver (The request/response packets are still
        parsed and logged but this is not inline)
    """
    def get_reply(self,data):
        host,port = self.server.resolver.address,self.server.resolver.port

        request = DNSRecord.parse(data)
        self.log_request(request)

        if self.protocol == 'tcp':
            data = struct.pack("!H",len(data)) + data
            response = send_tcp(data,host,port)
            response = response[2:]
        else:
            response = send_udp(data,host,port)

        reply = DNSRecord.parse(response)
        self.log_reply(reply)

        return response

def send_tcp(data,host,port):
    """
        Helper function to send/receive DNS TCP request
        (in/out packets will have prepended TCP length header)
    """
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect((host,port))
    sock.sendall(data)
    response = sock.recv(8192)
    length = struct.unpack("!H",bytes(response[:2]))[0]
    while len(response) - 2 < length:
        response += sock.recv(8192)
    sock.close()
    return response

def send_udp(data,host,port):
    """
        Helper function to send/receive DNS UDP request
    """
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.sendto(data,(host,port))
    response,server = sock.recvfrom(8192)
    sock.close()
    return response

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="DNS Proxy")
    p.add_argument("--port","-p",type=int,default=53,
                    metavar="<port>",
                    help="Local proxy port (default:53)")
    p.add_argument("--address","-a",default="",
                    metavar="<address>",
                    help="Local proxy listen address (default:all)")
    p.add_argument("--upstream","-u",default="8.8.8.8:53",
            metavar="<dns server:port>",
                    help="Upstream DNS server:port (default:8.8.8.8:53)")
    p.add_argument("--tcp",action='store_true',default=False,
                    help="TCP proxy (default: UDP only)")
    p.add_argument("--timeout","-o",type=float,default=5,
                    metavar="<timeout>",
                    help="Upstream timeout (default: 5s)")
    p.add_argument("--passthrough",action='store_true',default=False,
                    help="Dont decode/re-encode request/response (default: off)")
    p.add_argument("--log",default="request,reply,truncated,error",
                    help="Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)")
    p.add_argument("--log-prefix",action='store_true',default=False,
                    help="Log prefix (timestamp/handler/resolver) (default: False)")
    args = p.parse_args()

    args.dns,_,args.dns_port = args.upstream.partition(':')
    args.dns_port = int(args.dns_port or 53)

    print("Starting Proxy Resolver (%s:%d -> %s:%d) [%s]" % (
                        args.address or "*",args.port,
                        args.dns,args.dns_port,
                        "UDP/TCP" if args.tcp else "UDP"))

    resolver = ProxyResolver(args.dns,args.dns_port,args.timeout)
    handler = PassthroughDNSHandler if args.passthrough else DNSHandler
    logger = DNSLogger(args.log,args.log_prefix)
    udp_server = DNSServer(resolver,
                           port=args.port,
                           address=args.address,
                           logger=logger,
                           handler=handler)
    udp_server.start_thread()

    if args.tcp:
        tcp_server = DNSServer(resolver,
                               port=args.port,
                               address=args.address,
                               tcp=True,
                               logger=logger,
                               handler=handler)
        tcp_server.start_thread()

    while udp_server.isAlive():
        time.sleep(1)

Added dnslib/ranges.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
# -*- coding: utf-8 -*-

"""
    Wrapper around property builtin to restrict attribute to defined
    integer value range (throws ValueError). 

    Intended to ensure that values packed with struct are in the 
    correct range

    >>> class T(object):
    ...     a = range_property('a',-100,100)
    ...     b = B('b')
    ...     c = H('c')
    ...     d = I('d')
    ...     e = instance_property('e',(int,bool))
    >>> t = T()
    >>> for i in [0,100,-100]:
    ...     t.a = i
    ...     assert t.a == i
    >>> t.a = 101
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'a' must be between -100-100 [101]
    >>> t.a = -101
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'a' must be between -100-100 [-101]
    >>> t.a = 'blah'
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'a' must be between -100-100 [blah]
    >>> t.e = 999
    >>> t.e = False
    >>> t.e = None
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'e' must be instance of ...

    >>> check_range("test",123,0,255)
    >>> check_range("test",999,0,255)
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'test' must be between 0-255 [999]

    >>> check_instance("test",123,int)
    >>> check_instance("test","xxx",int)
    Traceback (most recent call last):
    ...
    ValueError: Attribute 'test' must be instance of ...

"""

import sys
if sys.version < '3':
    int_types = (int, long,)
    byte_types = (str,bytearray)
else:
    int_types = (int,)
    byte_types = (bytes,bytearray)

def check_instance(name,val,types):
    if not isinstance(val,types):
        raise ValueError("Attribute '%s' must be instance of %s [%s]" % 
                                        (name,types,type(val)))

def check_bytes(name,val):
    return check_instance(name,val,byte_types)

def instance_property(attr,types):
    def getter(obj):
        return getattr(obj,"_%s" % attr)
    def setter(obj,val):
        if isinstance(val,types):
            setattr(obj,"_%s" % attr,val)
        else:
            raise ValueError("Attribute '%s' must be instance of %s [%s]" % 
                                        (attr,types,type(val)))
    return property(getter,setter)

def BYTES(attr):
    return instance_property(attr,byte_types)

def check_range(name,val,min,max):
    if not (isinstance(val,int_types) and min <= val <= max):
        raise ValueError("Attribute '%s' must be between %d-%d [%s]" % 
                                        (name,min,max,val))

def range_property(attr,min,max):
    def getter(obj):
        return getattr(obj,"_%s" % attr)
    def setter(obj,val):
        if isinstance(val,int_types) and min <= val <= max:
            setattr(obj,"_%s" % attr,val)
        else:
            raise ValueError("Attribute '%s' must be between %d-%d [%s]" % 
                                        (attr,min,max,val))
    return property(getter,setter)

def B(attr):
    """
        Unsigned Byte
    """
    return range_property(attr,0,255)

def H(attr):
    """
        Unsigned Short
    """
    return range_property(attr,0,65535)

def I(attr):
    """
        Unsigned Long
    """
    return range_property(attr,0,4294967295)

def ntuple_range(attr,n,min,max):
    f = lambda x : isinstance(x,int_types) and min <= x <= max
    def getter(obj):
        return getattr(obj,"_%s" % attr)
    def setter(obj,val):
        if len(val) != n:
            raise ValueError("Attribute '%s' must be tuple with %d elements [%s]" % 
                                        (attr,n,val))
        if all(map(f,val)):
            setattr(obj,"_%s" % attr,val)
        else:
            raise ValueError("Attribute '%s' elements must be between %d-%d [%s]" % 
                                        (attr,min,max,val))
    return property(getter,setter)

def IP4(attr):
    return ntuple_range(attr,4,0,255)

def IP6(attr):
    return ntuple_range(attr,16,0,255)

if __name__ == '__main__':
    import doctest
    doctest.testmod(optionflags=doctest.ELLIPSIS)

Added dnslib/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
# -*- coding: utf-8 -*-

"""
    DNS server framework - intended to simplify creation of custom resolvers.

    Comprises the following components:

        DNSServer   - socketserver wrapper (in most cases you should just
                      need to pass this an appropriate resolver instance
                      and start in either foreground/background)

        DNSHandler  - handler instantiated by DNSServer to handle requests
                      The 'handle' method deals with the sending/receiving
                      packets (handling TCP length prefix) and delegates
                      the protocol handling to 'get_reply'. This decodes
                      packet, hands off a DNSRecord to the Resolver instance, 
                      and encodes the returned DNSRecord. 
                      
                      In most cases you dont need to change DNSHandler unless
                      you need to get hold of the raw protocol data in the
                      Resolver

        DNSLogger   - The class provides a default set of logging functions for
                      the various stages of the request handled by a DNSServer
                      instance which are enabled/disabled by flags in the 'log'
                      class variable. 

        Resolver    - Instance implementing a 'resolve' method that receives 
                      the decodes request packet and returns a response. 
                        
                      To implement a custom resolver in most cases all you need
                      is to implement this interface.

                      Note that there is only a single instance of the Resolver
                      so need to be careful about thread-safety and blocking

        The following examples use the server framework:

            fixedresolver.py    - Simple resolver which will respond to all
                                  requests with a fixed response
            zoneresolver.py     - Resolver which will take a standard zone
                                  file input
            shellresolver.py    - Example of a dynamic resolver
            proxy.py            - DNS proxy
            intercept.py        - Intercepting DNS proxy

        >>> resolver = BaseResolver()
        >>> logger = DNSLogger(prefix=False)
        >>> server = DNSServer(resolver,port=8053,address="localhost",logger=logger)
        >>> server.start_thread()
        >>> q = DNSRecord.question("abc.def")
        >>> a = q.send("localhost",8053)
        Request: [...] (udp) / 'abc.def.' (A)
        Reply: [...] (udp) / 'abc.def.' (A) / NXDOMAIN
        >>> print(DNSRecord.parse(a))
        ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: ...
        ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
        ;; QUESTION SECTION:
        ;abc.def.                       IN      A
        >>> server.stop()

        >>> class TestResolver:
        ...     def resolve(self,request,handler):
        ...         reply = request.reply()
        ...         reply.add_answer(*RR.fromZone("abc.def. 60 A 1.2.3.4"))
        ...         return reply
        >>> resolver = TestResolver()
        >>> server = DNSServer(resolver,port=8053,address="localhost",logger=logger,tcp=True)
        >>> server.start_thread()
        >>> a = q.send("localhost",8053,tcp=True)
        Request: [...] (tcp) / 'abc.def.' (A)
        Reply: [...] (tcp) / 'abc.def.' (A) / RRs: A
        >>> print(DNSRecord.parse(a))
        ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
        ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
        ;; QUESTION SECTION:
        ;abc.def.                       IN      A
        ;; ANSWER SECTION:
        abc.def.                60      IN      A       1.2.3.4
        >>> server.stop()


"""
from __future__ import print_function

import binascii,socket,struct,threading,time

try:
    import socketserver
except ImportError:
    import SocketServer as socketserver

from dnslib import DNSRecord,DNSError,QTYPE,RCODE,RR

class BaseResolver(object):
    """
        Base resolver implementation. Provides 'resolve' method which is
        called by DNSHandler with the decode request (DNSRecord instance) 
        and returns a DNSRecord instance as reply.

        In most cases you should be able to create a custom resolver by
        just replacing the resolve method with appropriate resolver code for
        application (see fixedresolver/zoneresolver/shellresolver for
        examples)

        Note that a single instance is used by all DNSHandler instances so 
        need to consider blocking & thread safety.
    """
    def resolve(self,request,handler):
        """
            Example resolver - respond to all requests with NXDOMAIN
        """
        reply = request.reply()
        reply.header.rcode = getattr(RCODE,'NXDOMAIN')
        return reply

class DNSHandler(socketserver.BaseRequestHandler):
    """
        Handler for socketserver. Transparently handles both TCP/UDP requests
        (TCP requests have length prepended) and hands off lookup to resolver
        instance specified in <SocketServer>.resolver 
    """

    udplen = 0                  # Max udp packet length (0 = ignore)

    def handle(self):
        if self.server.socket_type == socket.SOCK_STREAM:
            self.protocol = 'tcp'
            data = self.request.recv(8192)
            length = struct.unpack("!H",bytes(data[:2]))[0]
            while len(data) - 2 < length:
                new_data = self.request.recv(8192)
                if not new_data:
                    break
                data += new_data
            data = data[2:]
        else:
            self.protocol = 'udp'
            data,connection = self.request

        self.server.logger.log_recv(self,data)

        try:
            rdata = self.get_reply(data)
            self.server.logger.log_send(self,rdata)

            if self.protocol == 'tcp':
                rdata = struct.pack("!H",len(rdata)) + rdata
                self.request.sendall(rdata)
            else:
                connection.sendto(rdata,self.client_address)

        except DNSError as e:
            self.server.logger.log_error(self,e)

    def get_reply(self,data):
        request = DNSRecord.parse(data)
        self.server.logger.log_request(self,request)

        resolver = self.server.resolver
        reply = resolver.resolve(request,self)
        self.server.logger.log_reply(self,reply)

        if self.protocol == 'udp':
            rdata = reply.pack()
            if self.udplen and len(rdata) > self.udplen:
                truncated_reply = reply.truncate()
                rdata = truncated_reply.pack()
                self.server.logger.log_truncated(self,truncated_reply)
        else:
            rdata = reply.pack()

        return rdata

class DNSLogger:

    """
        The class provides a default set of logging functions for the various
        stages of the request handled by a DNSServer instance which are
        enabled/disabled by flags in the 'log' class variable.

        To customise logging create an object which implements the DNSLogger
        interface and pass instance to DNSServer.

        The methods which the logger instance must implement are:

            log_recv          - Raw packet received
            log_send          - Raw packet sent
            log_request       - DNS Request
            log_reply         - DNS Response
            log_truncated     - Truncated
            log_error         - Decoding error
            log_data          - Dump full request/response
    """

    def __init__(self,log="",prefix=True):
        """
            Selectively enable log hooks depending on log argument
            (comma separated list of hooks to enable/disable)

            - If empty enable default log hooks
            - If entry starts with '+' (eg. +send,+recv) enable hook
            - If entry starts with '-' (eg. -data) disable hook
            - If entry doesn't start with +/- replace defaults

            Prefix argument enables/disables log prefix
        """
        default = ["request","reply","truncated","error"]
        log = log.split(",") if log else []
        enabled = set([ s for s in log if s[0] not in '+-'] or default)
        [ enabled.add(l[1:]) for l in log if l.startswith('+') ]
        [ enabled.discard(l[1:]) for l in log if l.startswith('-') ]
        for l in ['log_recv','log_send','log_request','log_reply',
                  'log_truncated','log_error','log_data']:
            if l[4:] not in enabled:
                setattr(self,l,self.log_pass)
        self.prefix = prefix

    def log_pass(self,*args):
        pass

    def log_prefix(self,handler):
        if self.prefix:
            return "%s [%s:%s] " % (time.strftime("%Y-%m-%d %X"),
                               handler.__class__.__name__,
                               handler.server.resolver.__class__.__name__)
        else:
            return ""

    def log_recv(self,handler,data):
        print("%sReceived: [%s:%d] (%s) <%d> : %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    len(data),
                    binascii.hexlify(data)))

    def log_send(self,handler,data):
        print("%sSent: [%s:%d] (%s) <%d> : %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    len(data),
                    binascii.hexlify(data)))

    def log_request(self,handler,request):
        print("%sRequest: [%s:%d] (%s) / '%s' (%s)" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    request.q.qname,
                    QTYPE[request.q.qtype]))
        self.log_data(request)

    def log_reply(self,handler,reply):
        if reply.header.rcode == RCODE.NOERROR:
            print("%sReply: [%s:%d] (%s) / '%s' (%s) / RRs: %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    ",".join([QTYPE[a.rtype] for a in reply.rr])))
        else:
            print("%sReply: [%s:%d] (%s) / '%s' (%s) / %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    RCODE[reply.header.rcode]))
        self.log_data(reply)

    def log_truncated(self,handler,reply):
        print("%sTruncated Reply: [%s:%d] (%s) / '%s' (%s) / RRs: %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    ",".join([QTYPE[a.rtype] for a in reply.rr])))
        self.log_data(reply)

    def log_error(self,handler,e):
        print("%sInvalid Request: [%s:%d] (%s) :: %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    e))

    def log_data(self,dnsobj):
        print("\n",dnsobj.toZone("    "),"\n",sep="")


class UDPServer(socketserver.ThreadingMixIn,socketserver.UDPServer):
    allow_reuse_address = True

class TCPServer(socketserver.ThreadingMixIn,socketserver.TCPServer):
    allow_reuse_address = True

class DNSServer(object):

    """
        Convenience wrapper for socketserver instance allowing
        either UDP/TCP server to be started in blocking more
        or as a background thread.

        Processing is delegated to custom resolver (instance) and
        optionally custom logger (instance), handler (class), and 
        server (class)

        In most cases only a custom resolver instance is required
        (and possibly logger)
    """
    def __init__(self,resolver,
                      address="",
                      port=53,
                      tcp=False,
                      logger=None,
                      handler=DNSHandler,
                      server=None):
        """
            resolver:   resolver instance
            address:    listen address (default: "")
            port:       listen port (default: 53)
            tcp:        UDP (false) / TCP (true) (default: False)
            logger:     logger instance (default: DNSLogger)
            handler:    handler class (default: DNSHandler)
            server:     socketserver class (default: UDPServer/TCPServer)
        """
        if not server:
            if tcp:
                server = TCPServer
            else:
                server = UDPServer
        self.server = server((address,port),handler)
        self.server.resolver = resolver
        self.server.logger = logger or DNSLogger()
    
    def start(self):
        self.server.serve_forever()

    def start_thread(self):
        self.thread = threading.Thread(target=self.server.serve_forever)
        self.thread.daemon = True
        self.thread.start()

    def stop(self):
        self.server.shutdown()

    def isAlive(self):
        return self.thread.isAlive()

if __name__ == "__main__":
    import doctest
    doctest.testmod(optionflags=doctest.ELLIPSIS)

Added dnslib/shellresolver.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
# -*- coding: utf-8 -*-

from __future__ import print_function

try:
    from subprocess import getoutput
except ImportError:
    from commands import getoutput

from dnslib import RR,QTYPE,RCODE,TXT,parse_time
from dnslib.label import DNSLabel
from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger

class ShellResolver(BaseResolver):
    """
        Example dynamic resolver. 
        Maps DNS labels to shell commands and returns result as TXT record
        (Note: No context is passed to the shell command)

        Shell commands are passed in a a list in <label>:<cmd> format - eg:

            [ 'uptime.abc.com.:uptime', 'ls:ls' ]

        Would respond to requests to 'uptime.abc.com.' with the output
        of the 'uptime' command.

        For non-absolute labels the 'origin' parameter is prepended
        
    """
    def __init__(self,routes,origin,ttl):
        self.origin = DNSLabel(origin)
        self.ttl = parse_time(ttl)
        self.routes = {}
        for r in routes:
            route,_,cmd = r.partition(":")
            if route.endswith('.'):
                route = DNSLabel(route)
            else:
                route = self.origin.add(route)
            self.routes[route] = cmd

    def resolve(self,request,handler):
        reply = request.reply()
        qname = request.q.qname
        cmd = self.routes.get(qname)
        if cmd:
            output = getoutput(cmd).encode()
            reply.add_answer(RR(qname,QTYPE.TXT,ttl=self.ttl,
                                rdata=TXT(output[:254])))
        else:
            reply.header.rcode = RCODE.NXDOMAIN
        return reply

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="Shell DNS Resolver")
    p.add_argument("--map","-m",action="append",required=True,
                    metavar="<label>:<shell command>",
                    help="Map label to shell command (multiple supported)")
    p.add_argument("--origin","-o",default=".",
                    metavar="<origin>",
                    help="Origin domain label (default: .)")
    p.add_argument("--ttl","-t",default="60s",
                    metavar="<ttl>",
                    help="Response TTL (default: 60s)")
    p.add_argument("--port","-p",type=int,default=53,
                    metavar="<port>",
                    help="Server port (default:53)")
    p.add_argument("--address","-a",default="",
                    metavar="<address>",
                    help="Listen address (default:all)")
    p.add_argument("--udplen","-u",type=int,default=0,
                    metavar="<udplen>",
                    help="Max UDP packet length (default:0)")
    p.add_argument("--tcp",action='store_true',default=False,
                    help="TCP server (default: UDP only)")
    p.add_argument("--log",default="request,reply,truncated,error",
                    help="Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)")
    p.add_argument("--log-prefix",action='store_true',default=False,
                    help="Log prefix (timestamp/handler/resolver) (default: False)")
    args = p.parse_args()

    resolver = ShellResolver(args.map,args.origin,args.ttl)
    logger = DNSLogger(args.log,args.log_prefix)

    print("Starting Shell Resolver (%s:%d) [%s]" % (
                        args.address or "*",
                        args.port,
                        "UDP/TCP" if args.tcp else "UDP"))

    for route,cmd in resolver.routes.items():
        print("    | ",route,"-->",cmd)
    print()

    if args.udplen:
        DNSHandler.udplen = args.udplen

    udp_server = DNSServer(resolver,
                           port=args.port,
                           address=args.address,
                           logger=logger)
    udp_server.start_thread()

    if args.tcp:
        tcp_server = DNSServer(resolver,
                               port=args.port,
                               address=args.address,
                               tcp=True,
                               logger=logger)
        tcp_server.start_thread()

    while udp_server.isAlive():
        time.sleep(1)

Added dnslib/test/20120113._domainkey.gmail.com.-TXT.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 40ca010000010000000000000832303132303131330a5f646f6d61696e6b657905676d61696c03636f6d0000100001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 16586
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;20120113._domainkey.gmail.com. IN      TXT

;; Got answer:
;; RESPONSE: 40ca818000010001000000000832303132303131330a5f646f6d61696e6b657905676d61696c03636f6d0000100001c00c00100001000001090193b36b3d7273613b20703d4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b4341514541314b6438372f55654a6a656e70616267624677682b65424373535472716d774959597679776c626862716f6f3244796d6e64466b626a4f564950496c644e732f6d34304b462b797a4d6e31736b796f7863545547435173386733466744324170335a423544656b416f35774d6d6b3477696d444f2b5538517a4933534430de3779322b3037776c4e577749743873766e78676478476b566262687a5938692b525139447053567050624637796b5178744b586b762f616857334b6a56696941482b6768767649686b78347859534963396f5377566d416c354f63744d456557557767384973746a717a38425a6554576266343166624e68746537592b59715a4f777131536430446276594144394e4f5a4b39766c667561633035393848592b76745342637a55694b4552487631795262636151745a46683577746952724e3034424c55544432314d79634258356a596368486a50592f77494441514142
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 16586
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;20120113._domainkey.gmail.com. IN      TXT
;; ANSWER SECTION:
20120113._domainkey.gmail.com. 265     IN      TXT     "k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1Kd87/UeJjenpabgbFwh+eBCsSTrqmwIYYvywlbhbqoo2DymndFkbjOVIPIldNs/m40KF+yzMn1skyoxcTUGCQs8g3FgD2Ap3ZB5DekAo5wMmk4wimDO+U8QzI3SD0" "7y2+07wlNWwIt8svnxgdxGkVbbhzY8i+RQ9DpSVpPbF7ykQxtKXkv/ahW3KjViiAH+ghvvIhkx4xYSIc9oSwVmAl5OctMEeWUwg8Istjqz8BZeTWbf41fbNhte7Y+YqZOwq1Sd0DbvYAD9NOZK9vlfuac0598HY+vtSBczUiKERHv1yRbcaQtZFh5wtiRrN04BLUTD21MycBX5jYchHjPY/wIDAQAB"

Added dnslib/test/_sip._udp.sipgate.co.uk-SRV.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 923001000001000000000000045f736970045f756470077369706761746502636f02756b0000210001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37424
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;_sip._udp.sipgate.co.uk.       IN      SRV

;; Got answer:
;; RESPONSE: 923081800001000100000000045f736970045f756470077369706761746502636f02756b0000210001c00c002100010000017800150000000013c4077369706761746502636f02756b00
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37424
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;_sip._udp.sipgate.co.uk.       IN      SRV
;; ANSWER SECTION:
_sip._udp.sipgate.co.uk. 376     IN      SRV     0 0 5060 sipgate.co.uk.

Added dnslib/test/dig/google.com-A.dig.

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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

; <<>> DiG 9.8.5-P1 <<>> +qr google.com
;; global options: +cmd
;; Sending:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23706
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.com.			IN	A

;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23706
;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;google.com.			IN	A

;; ANSWER SECTION:
google.com.		299	IN	A	62.252.169.183
google.com.		299	IN	A	62.252.169.152
google.com.		299	IN	A	62.252.169.172
google.com.		299	IN	A	62.252.169.177
google.com.		299	IN	A	62.252.169.157
google.com.		299	IN	A	62.252.169.153
google.com.		299	IN	A	62.252.169.182
google.com.		299	IN	A	62.252.169.168
google.com.		299	IN	A	62.252.169.178
google.com.		299	IN	A	62.252.169.162
google.com.		299	IN	A	62.252.169.187
google.com.		299	IN	A	62.252.169.167
google.com.		299	IN	A	62.252.169.148
google.com.		299	IN	A	62.252.169.173
google.com.		299	IN	A	62.252.169.158
google.com.		299	IN	A	62.252.169.163

;; Query time: 42 msec
;; SERVER: 10.0.1.1#53(10.0.1.1)
;; WHEN: Mon May 05 12:01:30 BST 2014
;; MSG SIZE  rcvd: 284

Added dnslib/test/dig/google.com-ANY.dig.























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45716
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      ANY

;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45716
;; flags: qr rd ra; QUERY: 1, ANSWER: 14, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      ANY
;; ANSWER SECTION:
google.com.             299     IN      A       216.58.212.110
google.com.             299     IN      AAAA    2a00:1450:4009:807::200e
google.com.             86399   IN      CAA     0 issue "symantec.com"
google.com.             599     IN      MX      40 alt3.aspmx.l.google.com.
google.com.             599     IN      MX      10 aspmx.l.google.com.
google.com.             86399   IN      NS      ns2.google.com.
google.com.             599     IN      MX      20 alt1.aspmx.l.google.com.
google.com.             59      IN      SOA     ns2.google.com. dns-admin.google.com. 144578247 900 900 1800 60
google.com.             86399   IN      NS      ns1.google.com.
google.com.             86399   IN      NS      ns4.google.com.
google.com.             86399   IN      NS      ns3.google.com.
google.com.             599     IN      MX      50 alt4.aspmx.l.google.com.
google.com.             3599    IN      TXT     "v=spf1 include:_spf.google.com ~all"
google.com.             599     IN      MX      30 alt2.aspmx.l.google.com.

Added dnslib/test/e164.org-NAPTR.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 1235010000010000000000000130013001300130013101310131013301390133013001310138013701380465313634036f72670000230001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 4661
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;0.0.0.0.1.1.1.3.9.3.0.1.8.7.8.e164.org. IN      NAPTR

;; Got answer:
;; RESPONSE: 1235818000010001000000000130013001300130013101310131013301390133013001310138013701380465313634036f72670000230001c00c002300010000540200320064000a0175074532552b53495022215e5c2b3f282e2a2924217369703a5c5c31406677642e70756c7665722e636f6d2100
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 4661
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;0.0.0.0.1.1.1.3.9.3.0.1.8.7.8.e164.org. IN      NAPTR
;; ANSWER SECTION:
0.0.0.0.1.1.1.3.9.3.0.1.8.7.8.e164.org. 21506   IN      NAPTR   100 10 "u" "E2U+SIP" "!^\\+?(.*)$!sip:\\\\1@fwd.pulver.com!" .

Added dnslib/test/example.com-ANY.



































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: e42401000001000000000000076578616d706c6503636f6d0000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 58404
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;example.com.                   IN      ANY

;; Got answer:
;; RESPONSE: e42481800001001200000000076578616d706c6503636f6d0000ff0001c00c0006000100000df1002d03736e7303646e73056963616e6e036f726700036e6f63c02d77fd85fd00001c2000000e100012750000000e10c00c000100010000544100045db8d877c00c002e000100005441009f00010802000151805367224b535d68421927076578616d706c6503636f6d007102c2139c377d9eb02f67de77a6bd8f58d6ba831dbcfcb5622dadf68b7c9b1430f8e82673a636e3dac4541d6c0d4e7cdebc8978364f5161500fbd739477432e3d654860eefbefc7a575e63c2d088acafba4e6af152841ec98bc5547c55adde23f8d9fd8a8e15251a148bd96da491aea510532be30a0c4926ee5265fd97612c1c00c0002000100005441001401610c69616e612d73657276657273036e657400c00c000200010000544100040162c11fc00c002e000100005441009f000208020002a30053670424535d68421927076578616d706c6503636f6d001726dd76c3fbd0851557d24c53fa0c8576388fbddb8777d3ccc16abe0d756de2d367320a8d98f613c0357c8648e64c80e00eb9dd9d1ff09ccb7e4806eb49924b7ef85cf9b2f3dc2cd99a8e8f1535d10e037c2a37fee3a3e6b534e9f67176605b13e77315bbd38f712d97a05fc91ee378c9b73dc1d3b231350f94175cc213c2f6c00c002e000100000df1009f0006080200000e105366c9fa535d68421927076578616d706c6503636f6d003e71f9ee2b02c8796f745af6d41d7d633abdb56596243a12c3d3a1641f2ecd2e3f8b49c60ed9efbb814d801f6d5ca6af02fb81189435fdba3b07937a5f21a225a4c7fb28f0af15d5b7947fd8dc552eab88ba821bf8051394c189edd3a645b9c616e9923a87b39baa54095dfccf064a8ea5076571b71ef4806666dff597917cb7c00c001000010000001d000c0b763d73706631202d616c6cc00c001000010000001d0035342449643a206578616d706c652e636f6d203139323120323031332d31302d32312030343a30303a33395a20646b6e696768742024c00c002e00010000001d009f001008020000003c5366d73d535d68421927076578616d706c6503636f6d00563226ba14d3e01b3ca716fa7f6c43eff81a4bf121a870fc193d962bf0443a81b6e696a2473a597aba4dc51b29abb68d06f8b6bd421113e90220cd23aeb404c7245fe6ea1ef73780f3463e33bd192de1e3aa6c6de63364a3c003d1bdaf7f88057da608209eabf85fee3f0436be2e7adaad0c44391b3c51a9a0fcc8f5b70ae0e4c00c001c0001000054410010260628000220006d26bf144710970aa7c00c002e000100005441009f001c0802000151805366f55f535d68421927076578616d706c6503636f6d003817df928147fb0feb3b80a7c98f4e58fba5469936f49be5d694f9c2e741fdf8552f6d5cb5444589fb81c0baa6731ba24bf92d32876b6c1b81a2234ae5449ba05eb5d66d8da88d17d86339a6416c1bb35817a52cf1709987cfa58d83ac4b7afe3ca5ce514551ad509f1e9b05e63bb61964e52b883b5a6bb449d730a77d037cccc00c0030000100000df101080101030803010001ac2dec7a6523933c18602cc6ec82ca317497e42572054dd75091678bcfebaa9b0c25f40674a1675d4119bfffe33486ffc9a60478ab2f614b83e995b882318a0fa2ae86588e1e224ca54e86fda165fb51c32ad01cafbea97bc2096377922e75446fdef11e2438457bd6b67c3a042f3d6c7a17dd6aae8a8e3e971fecf3f18a9a5e1ce9fe3f19cfd21a722f2a359b1d6b3ecfdc3292f78ce32e7c63fe2c9621f9f054ee5b74b0fe62d3d1da24faeecf264c2fd04fb69bfc640750870b57546d3e327113daa4ffd7e4e58e9c599fac9e7a0151085447063328ea2891267516adafe4964ae0127d90f815c64ce3134ca41d633e0ec5811ad73edaa6eddad3d7583413c00c0030000100000df100880100030803010001a78e26559e478c1470e50dc96cb173a5f71881cdbd930780d4622cd6b70020b61e7242f5c97e7d1953cff7df5b61e100b8a0f4831adb8c6004c416fb140bc07c326f7c6c5380b8811306e00cd79850f61fad150bceeb3ef8485fda885be7ecf92ad9b1afc4163c5dff2d80eca073e8861c359064d2e9b7ae43064152211de795c00c0030000100000df101080101030803010001e8a4bf16e86699fd542c66dd80cb1e8e344af03d1264702471d0c89d0e0b3ad04910528a9a23ad6ef21125d68830f2cdf952f2b8330ececcddf21d49db8e772362e790e65cf7644bc1d83914cc372cc5b123a0fb1c7ab54c922b6a785808656ec24d2f3e0891009e939f4da0304e2f2435e67a6cafb4e07dbfc71d4ef398232f9f18744aa3b697286741f936f5385cde70b828d24d6f776b8d628eb82c399a0fb61ab11961cfd5a9d786beb3824367a5f23599a525397316fb11d132e01f6711e6620691d7699e5727e7b08b8be67142b9ff8e3998626a578ac37a2732e7f4a10bf049f35bf76c844f59e6ef0d12660db8ebd9df4c9cb5d413bcb2113ad0775fc00c002e000100000df1011f0030080200000e105366ff19535d68427b65076578616d706c6503636f6d00d1e77998935c63796316122e6b27feec3351801a0eaa066d45d900dfac7902db361dcc10067e9cfaa8b56ca6ed7c2757db5701d3a72b541f3ec3b2d388738297e1b6c5d3ea1b09751e6411e3e4f2b98a68f02c81fbe657a50c341aa890f9b5871029854ae0517bba620d146903230e2240b32cf785a63623eaafddea8bff64fdbe995bf2cfa306876d18ac74d9fcef65573a840fcdfb6bba5001d83b86261baa3a8baa81d2318be437ca5f3fdc7ae3eb39030231368d55b87e050ee0e5f41de3793b28b646d5ba2ef5ca820f22ff1cccad7b44e19e883a77dc3e8ed4fb70708f7eef955d48e556dc4140cb250aec1c73a9fe4f9f3b252026aab973db06b78d79c00c002f000100000df1001a03777777076578616d706c6503636f6d00000762008008000380c00c002e000100000df1009f002f080200000e105366c0cc535d68421927076578616d706c6503636f6d000e879eab3067c41bed4f27782b87596c3ab95d72928a5e71026c92af5b149efab4d693a920d34a84463ca2ba3c3af76ba0ae9a153210a67d304433adf60ef9f238c6adfeef78fa60ecd1962b0175ac1ce1054bc796591468195f78379f5bb741a7852c6ae88979f692f7f0461b468a66504d48cf7d215220ed2cea664d4870e1
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 58404
;; flags: qr rd ra; QUERY: 1, ANSWER: 18, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;example.com.                   IN      ANY
;; ANSWER SECTION:
example.com.            3569    IN      SOA     sns.dns.icann.org. noc.dns.icann.org. 2013103613 7200 3600 1209600 3600
example.com.            21569   IN      A       93.184.216.119
example.com.            21569   IN      RRSIG   A 8 2 86400 20140505053155 20140427202746 6439 example.com. cQLCE5w3fZ6wL2fed6a9j1jWuoMdvPy1Yi2t9ot8mxQw+Ogmc6Y249rEVB1sDU583ryJeDZPUWFQD71zlHdDLj1lSGDu++/HpXXmPC0Iisr7pOavFShB7Ji8VUfFWt3iP42f2KjhUlGhSL2W2kka6lEFMr4woMSSbuUmX9l2EsE=
example.com.            21569   IN      NS      a.iana-servers.net.
example.com.            21569   IN      NS      b.iana-servers.net.
example.com.            21569   IN      RRSIG   NS 8 2 172800 20140505032316 20140427202746 6439 example.com. FybddsP70IUVV9JMU/oMhXY4j73bh3fTzMFqvg11beLTZzIKjZj2E8A1fIZI5kyA4A653Z0f8JzLfkgG60mSS374XPmy89ws2ZqOjxU10Q4DfCo3/uOj5rU06fZxdmBbE+dzFbvTj3Etl6BfyR7jeMm3PcHTsjE1D5QXXMITwvY=
example.com.            3569    IN      RRSIG   SOA 8 2 3600 20140504231506 20140427202746 6439 example.com. PnH57isCyHlvdFr21B19Yzq9tWWWJDoSw9OhZB8uzS4/i0nGDtnvu4FNgB9tXKavAvuBGJQ1/bo7B5N6XyGiJaTH+yjwrxXVt5R/2NxVLquIuoIb+AUTlMGJ7dOmRbnGFumSOoezm6pUCV38zwZKjqUHZXG3HvSAZmbf9ZeRfLc=
example.com.            29      IN      TXT     "v=spf1 -all"
example.com.            29      IN      TXT     "$Id: example.com 1921 2013-10-21 04:00:39Z dknight $"
example.com.            29      IN      RRSIG   TXT 8 2 60 20140505001141 20140427202746 6439 example.com. VjImuhTT4Bs8pxb6f2xD7/gaS/EhqHD8GT2WK/BEOoG25paiRzpZerpNxRspq7aNBvi2vUIRE+kCIM0jrrQExyRf5uoe9zeA80Y+M70ZLeHjqmxt5jNko8AD0b2vf4gFfaYIIJ6r+F/uPwQ2vi562q0MRDkbPFGpoPzI9bcK4OQ=
example.com.            21569   IN      AAAA    2606:2800:220:6d:26bf:1447:1097:aa7
example.com.            21569   IN      RRSIG   AAAA 8 2 86400 20140505022015 20140427202746 6439 example.com. OBffkoFH+w/rO4CnyY9OWPulRpk29Jvl1pT5wudB/fhVL21ctURFifuBwLqmcxuiS/ktModrbBuBoiNK5USboF611m2NqI0X2GM5pkFsG7NYF6Us8XCZh8+ljYOsS3r+PKXOUUVRrVCfHpsF5ju2GWTlK4g7Wmu0Sdcwp30DfMw=
example.com.            3569    IN      DNSKEY  257 3 8 AwEAAawt7HplI5M8GGAsxuyCyjF0l+QlcgVN11CRZ4vP66qbDCX0BnShZ11BGb//4zSG/8mmBHirL2FLg+mVuIIxig+iroZYjh4iTKVOhv2hZftRwyrQHK++qXvCCWN3ki51RG/e8R4kOEV71rZ8OgQvPWx6F91qroqOPpcf7PPxippeHOn+PxnP0hpyLyo1mx1rPs/cMpL3jOMufGP+LJYh+fBU7lt0sP5i09HaJPruzyZML9BPtpv8ZAdQhwtXVG0+MnET2qT/1+TljpxZn6yeegFRCFRHBjMo6iiRJnUWra/klkrgEn2Q+BXGTOMTTKQdYz4OxYEa1z7apu3a09dYNBM=
example.com.            3569    IN      DNSKEY  256 3 8 AwEAAaeOJlWeR4wUcOUNyWyxc6X3GIHNvZMHgNRiLNa3ACC2HnJC9cl+fRlTz/ffW2HhALig9IMa24xgBMQW+xQLwHwyb3xsU4C4gRMG4AzXmFD2H60VC87rPvhIX9qIW+fs+SrZsa/EFjxd/y2A7KBz6IYcNZBk0um3rkMGQVIhHeeV
example.com.            3569    IN      DNSKEY  257 3 8 AwEAAeikvxboZpn9VCxm3YDLHo40SvA9EmRwJHHQyJ0OCzrQSRBSipojrW7yESXWiDDyzflS8rgzDs7M3fIdSduOdyNi55DmXPdkS8HYORTMNyzFsSOg+xx6tUySK2p4WAhlbsJNLz4IkQCek59NoDBOLyQ15npsr7Tgfb/HHU7zmCMvnxh0SqO2lyhnQfk29Thc3nC4KNJNb3drjWKOuCw5mg+2GrEZYc/VqdeGvrOCQ2el8jWZpSU5cxb7EdEy4B9nEeZiBpHXaZ5XJ+ewi4vmcUK5/445mGJqV4rDeicy5/ShC/BJ81v3bIRPWebvDRJmDbjr2d9MnLXUE7yyETrQd18=
example.com.            3569    IN      RRSIG   DNSKEY 8 2 3600 20140505030145 20140427202746 31589 example.com. 0ed5mJNcY3ljFhIuayf+7DNRgBoOqgZtRdkA36x5Ats2HcwQBn6c+qi1bKbtfCdX21cB06crVB8+w7LTiHOCl+G2xdPqGwl1HmQR4+TyuYpo8CyB++ZXpQw0GqiQ+bWHECmFSuBRe7piDRRpAyMOIkCzLPeFpjYj6q/d6ov/ZP2+mVvyz6MGh20YrHTZ/O9lVzqED837a7pQAdg7hiYbqjqLqoHSMYvkN8pfP9x64+s5AwIxNo1VuH4FDuDl9B3jeTsotkbVui71yoIPIv8czK17ROGeiDp33D6O1PtwcI9+75VdSOVW3EFAyyUK7Bxzqf5PnzslICaquXPbBreNeQ==
example.com.            3569    IN      NSEC    03777777076578616d706c6503636f6d00000762008008000380
example.com.            3569    IN      RRSIG   NSEC 8 2 3600 20140504223556 20140427202746 6439 example.com. DoeeqzBnxBvtTyd4K4dZbDq5XXKSil5xAmySr1sUnvq01pOpINNKhEY8oro8OvdroK6aFTIQpn0wRDOt9g758jjGrf7vePpg7NGWKwF1rBzhBUvHllkUaBlfeDefW7dBp4UsauiJefaS9/BGG0aKZlBNSM99IVIg7SzqZk1IcOE=

Added dnslib/test/facebook.com-AAAA.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 520a010000010000000000000866616365626f6f6b03636f6d00001c0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21002
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;facebook.com.                  IN      AAAA

;; Got answer:
;; RESPONSE: 520a818000010001000000000866616365626f6f6b03636f6d00001c0001c00c001c00010000022100102a0328802110df07faceb00c00000001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21002
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;facebook.com.                  IN      AAAA
;; ANSWER SECTION:
facebook.com.           545     IN      AAAA    2a03:2880:2110:df07:face:b00c:0:1

Added dnslib/test/google.com-A.































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: e21b0100000100000000000006676f6f676c6503636f6d0000010001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57883
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      A

;; Got answer:
;; RESPONSE: e21b8180000100100000000006676f6f676c6503636f6d0000010001c00c000100010000004e00043efca9b7c00c000100010000004e00043efca9a7c00c000100010000004e00043efca9b1c00c000100010000004e00043efca9b6c00c000100010000004e00043efca99dc00c000100010000004e00043efca9a2c00c000100010000004e00043efca9a8c00c000100010000004e00043efca9acc00c000100010000004e00043efca9adc00c000100010000004e00043efca999c00c000100010000004e00043efca99ec00c000100010000004e00043efca998c00c000100010000004e00043efca994c00c000100010000004e00043efca9bbc00c000100010000004e00043efca9a3c00c000100010000004e00043efca9b2
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57883
;; flags: qr rd ra; QUERY: 1, ANSWER: 16, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      A
;; ANSWER SECTION:
google.com.             78      IN      A       62.252.169.183
google.com.             78      IN      A       62.252.169.167
google.com.             78      IN      A       62.252.169.177
google.com.             78      IN      A       62.252.169.182
google.com.             78      IN      A       62.252.169.157
google.com.             78      IN      A       62.252.169.162
google.com.             78      IN      A       62.252.169.168
google.com.             78      IN      A       62.252.169.172
google.com.             78      IN      A       62.252.169.173
google.com.             78      IN      A       62.252.169.153
google.com.             78      IN      A       62.252.169.158
google.com.             78      IN      A       62.252.169.152
google.com.             78      IN      A       62.252.169.148
google.com.             78      IN      A       62.252.169.187
google.com.             78      IN      A       62.252.169.163
google.com.             78      IN      A       62.252.169.178

Added dnslib/test/google.com-AAAA.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 21590100000100000000000006676f6f676c6503636f6d00001c0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8537
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      AAAA

;; Got answer:
;; RESPONSE: 21598180000100010000000006676f6f676c6503636f6d00001c0001c00c001c00010000009100102a001450400908050000000000001000
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8537
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      AAAA
;; ANSWER SECTION:
google.com.             145     IN      AAAA    2a00:1450:4009:805::1000

Added dnslib/test/google.com-ANY.



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: 27e40100000100000000000006676f6f676c6503636f6d0000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10212
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      ANY

;; Got answer:
;; RESPONSE: 27e481800001000e0000000006676f6f676c6503636f6d0000ff0001c00c000100010000012b0004d83ad54ec00c001c00010000012b00102a0014504009080e000000000000200ec00c000f0001000002570011001e04616c7432056173706d78016cc00cc00c000600010000003b0026036e7331c00c09646e732d61646d696ec00c089e16c70000038400000384000007080000003cc00c010100010001517f00130005697373756573796d616e7465632e636f6dc00c0010000100000e0f002423763d7370663120696e636c7564653a5f7370662e676f6f676c652e636f6d207e616c6cc00c000f0001000002570004000ac05bc00c000200010001517f0002c071c00c000200010001517f0006036e7332c00cc00c000f0001000002570009003204616c7434c05bc00c000200010001517f0006036e7333c00cc00c000f0001000002570009002804616c7433c05bc00c000f0001000002570009001404616c7431c05bc00c000200010001517f0006036e7334c00c
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10212
;; flags: qr rd ra; QUERY: 1, ANSWER: 14, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      ANY
;; ANSWER SECTION:
google.com.             299     IN      A       216.58.213.78
google.com.             299     IN      AAAA    2a00:1450:4009:80e::200e
google.com.             599     IN      MX      30 alt2.aspmx.l.google.com.
google.com.             59      IN      SOA     ns1.google.com. dns-admin.google.com. 144578247 900 900 1800 60
google.com.             86399   IN      CAA     0 issue "symantec.com"
google.com.             3599    IN      TXT     "v=spf1 include:_spf.google.com ~all"
google.com.             599     IN      MX      10 aspmx.l.google.com.
google.com.             86399   IN      NS      ns1.google.com.
google.com.             86399   IN      NS      ns2.google.com.
google.com.             599     IN      MX      50 alt4.aspmx.l.google.com.
google.com.             86399   IN      NS      ns3.google.com.
google.com.             599     IN      MX      40 alt3.aspmx.l.google.com.
google.com.             599     IN      MX      20 alt1.aspmx.l.google.com.
google.com.             86399   IN      NS      ns4.google.com.

Added dnslib/test/google.com-MX.









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
;; Sending:
;; QUERY: c1e20100000100000000000006676f6f676c6503636f6d00000f0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49634
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      MX

;; Got answer:
;; RESPONSE: c1e28180000100050000000006676f6f676c6503636f6d00000f0001c00c000f0001000001fa0011001404616c7431056173706d78016cc00cc00c000f0001000001fa0009002804616c7433c02fc00c000f0001000001fa0009003204616c7434c02fc00c000f0001000001fa0009001e04616c7432c02fc00c000f0001000001fa0004000ac02f
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49634
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      MX
;; ANSWER SECTION:
google.com.             506     IN      MX      20 alt1.aspmx.l.google.com.
google.com.             506     IN      MX      40 alt3.aspmx.l.google.com.
google.com.             506     IN      MX      50 alt4.aspmx.l.google.com.
google.com.             506     IN      MX      30 alt2.aspmx.l.google.com.
google.com.             506     IN      MX      10 aspmx.l.google.com.

Added dnslib/test/google.com-SOA.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 4cce0100000100000000000006676f6f676c6503636f6d0000060001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19662
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      SOA

;; Got answer:
;; RESPONSE: 4cce8180000100010000000006676f6f676c6503636f6d0000060001c00c000600010000545f0026036e7331c00c09646e732d61646d696ec00c780b88a800001c2000000708001275000000012c
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19662
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      SOA
;; ANSWER SECTION:
google.com.             21599   IN      SOA     ns1.google.com. dns-admin.google.com. 2014021800 7200 1800 1209600 300

Added dnslib/test/google.com-TXT.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 0cbe0100000100000000000006676f6f676c6503636f6d0000100001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3262
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      TXT

;; Got answer:
;; RESPONSE: 0cbe8180000100010000000006676f6f676c6503636f6d0000100001c00c0010000100000e0f004c4b763d7370663120696e636c7564653a5f7370662e676f6f676c652e636f6d206970343a3231362e37332e39332e37302f3331206970343a3231362e37332e39332e37322f3331207e616c6c
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3262
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;google.com.                    IN      TXT
;; ANSWER SECTION:
google.com.             3599    IN      TXT     "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"

Added dnslib/test/iana.org-ANY.























































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: 4c14010000010000000000000469616e61036f72670000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19476
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;iana.org.                      IN      ANY

;; Got answer:
;; RESPONSE: 4c1481800001001a000000000469616e61036f72670000ff0001c00c0006000100000e06002a03736e7303646e73056963616e6ec011036e6f63c02a77fd866400001c2000000e100012750000000e10c00c000100010000024e0004c0002b08c00c002e00010000024e009c0001080200000258536b07db53615c818b240469616e61036f72670013c92ac5ea251d2c7f1de4cbda47fffb902b191c74eb46fc61fdebba63721c54fcfe4214937e8aea1039ed9e0f47b5f4b0423eb5b20b1162ab3d9a3a3c3637b2680ae59cfdb32b7ab704007db77fe3bdaf5cee3619cc91d40f29794ab705c80404951f2ccad14578112c16394125c351daf561e552aa12b683a1d44bce62c809c00c00020001000054560005026e73c02ec00c0002000100005456001401620c69616e612d73657276657273036e657400c00c000200010000545600040163c127c00c000200010000545600040161c127c00c002e000100005456009c0002080200015180536b12b653615c818b240469616e61036f72670040b91e127f60ba357111cf7565944d00bb34d7f309c1555753695d85e8984765d8e08c4a0957ae75ee7fb4255241dd2cbefef81ee7e6d0b7dfb4dce78ec8fad19147841879e28d6042fd2edba03cfc4d392346852bb95b83795859ea7f677e593d865edd8c2f14fe2c3a7e4af2e40ee74f6d6e3936a24b944c64569cf538f067c00c002e000100000e06009c0006080200000e10536ac25f53615c818b240469616e61036f726700b3c22997425048c834d360c039c4a0e58cb83797fae52ae3924d86062b8e95f153eaf17d5192b425f21eee59df05c5e094e0bc75daca09f23e95bc696ae699994542f10bfc55282594cec722641e2aa79c4212acfe29d0890df018b954359da66e8dee44a0ae5ce993756da553de94ab5b6472b105d8b1a88c958cdea3931095c00c000f00010000024e000d000a08706563686f726134c02ec00c000f00010000024e000d000a08706563686f726131c02ec00c000f00010000024e000d000a08706563686f726135c02ec00c000f00010000024e000d000a08706563686f726138c02ec00c000f00010000024e000d000a08706563686f726137c02ec00c000f00010000024e000d000a08706563686f726133c02ec00c002e00010000024e009c000f080200000258536b28bd53615c818b240469616e61036f7267008ed9bd529e6b96039bda14a45d2c68016a95200319c80ad3c9a4e887240b58a13e89de16113559f2ef09b0fc5b3c152fd0fd2049780cd51405f4a215ed46e7adfdeb3aa37277096925923a53a9e687230e803d95c82c6fc0190a480b5fb388e92cab300cccb1b29294189137113a9c12279dfbc4627b216ce1e459864672c3adc00c00100001000000320033322449643a2069616e612e6f7267203139333920323031332d31302d32322031383a32373a32395a2064636c6f73736f6e2024c00c002e000100000032009c001008020000003c536b3fa153615c818b240469616e61036f72670071c6b10b7cf9a70a4422cda6dedf3929cf9356bbb7126c19c5b9def7f67a423388b76c7480489c84ec77f22782d4436e6261d2d5daf8bf7a1d45a0e59250ef1d8c3d2b385e449c3b20b975c69918e034b2dbeadb2a335c3c17334a61ed92f47149fea579d615874f91ba64a211240a437e42c0654c6dadc6a5eca305be869443c00c001c00010000024e001020010500008802000000000000000008c00c002e00010000024e009c001c080200000258536b08a853615c818b240469616e61036f72670046f728d39162cb5a566c3b1354ceaf512686603dfcd465340ae9ada9fdac5724f401133da7d2268a0ea61fa39acad1e0e745679ba11d20097816746ae2c688e9a63fcd945dfc00ab30ebba68adee61938927f06a9562d09cc6a35cda4824fd5260392d31fd5d1980425377281c1e3eb8dc7d73f6cdb693fc5ae265327994492ec00c0030000100000e0601080101030803010001bed3b4d1476380436e2fdfb47da3d4ec01fbdd7587cf082ee437e7f02aca7a030e5d19053fa19f78ac2e20831c37bc1589955d47ddbe7b64271d58d1a1cff66a213c7d6c8dbc680cf920eb92a5a17f8a42cdf8d2c9eed78a9f4191ac6ba9f20d090b5fd3a7dc7e94f562dce17d4c07ef6a2bd66b7d1d90dbd432ef4e290284f8d9b44971c17466e68090685b41e404d86b93c0fcd777aae178bc1e42591963777b44e7bdb0b56734bc5333422c6e4182fadb6f7eb8417c1fc8f55a840f9bb4d810f7535112cad19ee52610ebc3f1378cf5415db82507e065ef6180edf1f3ea16e908a150a8e119c5316dee99be6edf2caabfb8023a5852c7f178940d6b3cfb7dc00c0030000100000e0600880100030803010001d7c8cde9f019a8ae616295ec1c83bef6ff35c9b127d08c0e048f70582d6513cf1427bc7c460561afaf976ce6afb0df1aaf2df3099f3da6973df81297e458176a555ce35192b8a1ff7e88f462fbe6f92bef31559bad686a1c59647f8c6803a88a4c5978c8c0806e13e014cc7ec93ffa72d35f55d5c70c675897ed07d29372ddf3c00c0030000100000e0601080101030803010001c1fb8508eeea11f7fe747aba37a397f46a3e174bad479d4e43292d99c1f22c7bb2d7d0add86b50a966f673950e35b4dba3fe3c49cd2cf45c5c32fcb914e797274b95e5501b31d5662f53c7339bbf18289715533e849508eccedfd9f637a6a695b93d0e1e16a5a4af691a7fa587f7ffed83678a37ded44b3c4549c87026541c68b20dcf5ef51e22481586374f72b031a3d562d7668b3233536acd78285dd228384e219e5b6e60f333bd024b613df9b8ecaa88b8ae977f47d2226d7e9090ff89d37c8deb8386910381bc1d546ba8019c44e866cd06ce8ec297822320a2a212225d60622ee7404d65c67d375787bd6b363421ac6cd42d9141c7687de7c5761663a9c00c002e000100000e06011c0030080200000e10536b3d9353615c811a4a0469616e61036f72670023bf2985b868a1e23b9b5e80e38946fddf76f53fbe7f1a06a02eaedd5d116e9e1be716be8afad0d3f886387966e0b7511f1be581fd2c8aba98c5930716ba2eb7d8cec2462ff035acd602c5bf1bfadb215319c787d3a4468af21bbddb63c190fbe4aeed5a9cac17e4e503edabc99e18e6bb47963b5a8eea76e0ce92997fec58cf43e9309ebbd8de026ce122bb0215c96c4d0b5ddf3bab90ed7fbacc29288d103c30f9cb58af015dc21bd5cdc05ef4c1251e504c97c75b1342eff630e37d88331c89a1b71c15207dc284becca44818fc00dedafc4092cb8b90ce3859ee38c2471dbd7818d18a147f67ed7d77f8803766578fb36dc720dbb483174d05191166d871c00c002f000100000e06001c036e733104617574680469616e61036f726700000762018008000380c00c002e000100000e06009c002f080200000e10536b13ae53615c818b240469616e61036f726700a70ee185f024c5efb766a5cfb42b19532f782c7f49ca8415f978d380d60bba97710948dccebc32b6464ff588d00f3539e1778763aa0f218cb48ed64c8671fe419f9a03f36199c7847da11fb7bb0a52fef7f612275eee6d0977fc540d30e99358c7ffe9d69adea8d29895328e39c6b5f1a65801384693e0b0e2b346d35b18e464
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19476
;; flags: qr rd ra; QUERY: 1, ANSWER: 26, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;iana.org.                      IN      ANY
;; ANSWER SECTION:
iana.org.               3590    IN      SOA     sns.dns.icann.org. noc.dns.icann.org. 2013103716 7200 3600 1209600 3600
iana.org.               590     IN      A       192.0.43.8
iana.org.               590     IN      RRSIG   A 8 2 600 20140508042811 20140430202641 35620 iana.org. E8kqxeolHSx/HeTL2kf/+5ArGRx060b8Yf3rumNyHFT8/kIUk36K6hA57Z4PR7X0sEI+tbILEWKrPZo6PDY3smgK5Zz9syt6twQAfbd/472vXO42GcyR1A8peUq3BcgEBJUfLMrRRXgRLBY5QSXDUdr1YeVSqhK2g6HUS85iyAk=
iana.org.               21590   IN      NS      ns.icann.org.
iana.org.               21590   IN      NS      b.iana-servers.net.
iana.org.               21590   IN      NS      c.iana-servers.net.
iana.org.               21590   IN      NS      a.iana-servers.net.
iana.org.               21590   IN      RRSIG   NS 8 2 86400 20140508051430 20140430202641 35620 iana.org. QLkeEn9gujVxEc91ZZRNALs01/MJwVVXU2ldheiYR2XY4IxKCVeude5/tCVSQd0svv74Hufm0LfftNznjsj60ZFHhBh54o1gQv0u26A8/E05I0aFK7lbg3lYWep/Z35ZPYZe3YwvFP4sOn5K8uQO509tbjk2okuUTGRWnPU48Gc=
iana.org.               3590    IN      RRSIG   SOA 8 2 3600 20140507233143 20140430202641 35620 iana.org. s8Ipl0JQSMg002DAOcSg5Yy4N5f65Srjkk2GBiuOlfFT6vF9UZK0JfIe7lnfBcXglOC8ddrKCfI+lbxpauaZmUVC8Qv8VSgllM7HImQeKqecQhKs/inQiQ3wGLlUNZ2mbo3uRKCuXOmTdW2lU96Uq1tkcrEF2LGojJWM3qOTEJU=
iana.org.               590     IN      MX      10 pechora4.icann.org.
iana.org.               590     IN      MX      10 pechora1.icann.org.
iana.org.               590     IN      MX      10 pechora5.icann.org.
iana.org.               590     IN      MX      10 pechora8.icann.org.
iana.org.               590     IN      MX      10 pechora7.icann.org.
iana.org.               590     IN      MX      10 pechora3.icann.org.
iana.org.               590     IN      RRSIG   MX 8 2 600 20140508064829 20140430202641 35620 iana.org. jtm9Up5rlgOb2hSkXSxoAWqVIAMZyArTyaTohyQLWKE+id4WETVZ8u8JsPxbPBUv0P0gSXgM1RQF9KIV7Ubnrf3rOqNydwlpJZI6U6nmhyMOgD2VyCxvwBkKSAtfs4jpLKswDMyxspKUGJE3ETqcEied+8RieyFs4eRZhkZyw60=
iana.org.               50      IN      TXT     "$Id: iana.org 1939 2013-10-22 18:27:29Z dclosson $"
iana.org.               50      IN      RRSIG   TXT 8 2 60 20140508082609 20140430202641 35620 iana.org. ccaxC3z5pwpEIs2m3t85Kc+TVru3EmwZxbne9/Z6QjOIt2x0gEichOx38ieC1ENuYmHS1dr4v3odRaDlklDvHYw9KzheRJw7ILl1xpkY4DSy2+rbKjNcPBczSmHtkvRxSf6ledYVh0+RumSiESQKQ35CwGVMba3GpeyjBb6GlEM=
iana.org.               590     IN      AAAA    2001:500:88:200::8
iana.org.               590     IN      RRSIG   AAAA 8 2 600 20140508043136 20140430202641 35620 iana.org. Rvco05Fiy1pWbDsTVM6vUSaGYD381GU0Cumtqf2sVyT0ARM9p9Imig6mH6OaytHg50Vnm6EdIAl4FnRq4saI6aY/zZRd/ACrMOu6aK3uYZOJJ/BqlWLQnMajXNpIJP1SYDktMf1dGYBCU3coHB4+uNx9c/bNtpP8WuJlMnmUSS4=
iana.org.               3590    IN      DNSKEY  257 3 8 AwEAAb7TtNFHY4BDbi/ftH2j1OwB+911h88ILuQ35/AqynoDDl0ZBT+hn3isLiCDHDe8FYmVXUfdvntkJx1Y0aHP9mohPH1sjbxoDPkg65KloX+KQs340snu14qfQZGsa6nyDQkLX9On3H6U9WLc4X1MB+9qK9ZrfR2Q29Qy704pAoT42bRJccF0ZuaAkGhbQeQE2GuTwPzXd6rheLweQlkZY3d7ROe9sLVnNLxTM0IsbkGC+ttvfrhBfB/I9VqED5u02BD3U1ESytGe5SYQ68PxN4z1QV24JQfgZe9hgO3x8+oW6QihUKjhGcUxbe6Zvm7fLKq/uAI6WFLH8XiUDWs8+30=
iana.org.               3590    IN      DNSKEY  256 3 8 AwEAAdfIzenwGaiuYWKV7ByDvvb/NcmxJ9CMDgSPcFgtZRPPFCe8fEYFYa+vl2zmr7DfGq8t8wmfPaaXPfgSl+RYF2pVXONRkrih/36I9GL75vkr7zFVm61oahxZZH+MaAOoikxZeMjAgG4T4BTMfsk/+nLTX1XVxwxnWJftB9KTct3z
iana.org.               3590    IN      DNSKEY  257 3 8 AwEAAcH7hQju6hH3/nR6ujejl/RqPhdLrUedTkMpLZnB8ix7stfQrdhrUKlm9nOVDjW026P+PEnNLPRcXDL8uRTnlydLleVQGzHVZi9TxzObvxgolxVTPoSVCOzO39n2N6amlbk9Dh4WpaSvaRp/pYf3/+2DZ4o33tRLPEVJyHAmVBxosg3PXvUeIkgVhjdPcrAxo9Vi12aLMjNTas14KF3SKDhOIZ5bbmDzM70CS2E9+bjsqoi4rpd/R9IibX6QkP+J03yN64OGkQOBvB1Ua6gBnEToZs0Gzo7Cl4IjIKKiEiJdYGIu50BNZcZ9N1eHvWs2NCGsbNQtkUHHaH3nxXYWY6k=
iana.org.               3590    IN      RRSIG   DNSKEY 8 2 3600 20140508081723 20140430202641 6730 iana.org. I78phbhooeI7m16A44lG/d929T++fxoGoC6u3V0Rbp4b5xa+ivrQ0/iGOHlm4LdRHxvlgf0sirqYxZMHFrout9jOwkYv8DWs1gLFvxv62yFTGceH06RGivIbvdtjwZD75K7tWpysF+TlA+2ryZ4Y5rtHljtajup24M6SmX/sWM9D6TCeu9jeAmzhIrsCFclsTQtd3zurkO1/uswpKI0QPDD5y1ivAV3CG9XNwF70wSUeUEyXx1sTQu/2MON9iDMciaG3HBUgfcKEvsykSBj8AN7a/ECSy4uQzjhZ7jjCRx29eBjRihR/Z+19d/iAN2ZXj7NtxyDbtIMXTQUZEWbYcQ==
iana.org.               3590    IN      NSEC    036e733104617574680469616e61036f726700000762018008000380
iana.org.               3590    IN      RRSIG   NSEC 8 2 3600 20140508051838 20140430202641 35620 iana.org. pw7hhfAkxe+3ZqXPtCsZUy94LH9JyoQV+XjTgNYLupdxCUjczrwytkZP9YjQDzU54XeHY6oPIYy0jtZMhnH+QZ+aA/NhmceEfaEft7sKUv739hInXu5tCXf8VA0w6ZNYx//p1preqNKYlTKOOca18aZYAThGk+Cw4rNG01sY5GQ=

;;; ERROR: Diff Response differs
;; - iana.org.               3590    IN      NSEC    036e733104617574680469616e61036f726700000762018008000380

Added dnslib/test/in-addr.arpa-PTR.

































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
;; Sending:
;; QUERY: 815d01000001000000000000033130330239310332343902363607696e2d61646472046172706100000c0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33117
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;103.91.249.66.in-addr.arpa.    IN      PTR

;; Got answer:
;; RESPONSE: 815d81800001000100000000033130330239310332343902363607696e2d61646472046172706100000c0001c00c000c00010000542b002d20726174652d6c696d697465642d70726f78792d36362d3234392d39312d31303306676f6f676c6503636f6d00
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33117
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;103.91.249.66.in-addr.arpa.    IN      PTR
;; ANSWER SECTION:
103.91.249.66.in-addr.arpa. 21547   IN      PTR     rate-limited-proxy-66-249-91-103.google.com.

Added dnslib/test/microsoft.com-ANY.





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: b8f001000001000000000000096d6963726f736f667403636f6d0000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47344
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;microsoft.com.                 IN      ANY

;; Got answer:
;; RESPONSE: b8f081800001000b00000000096d6963726f736f667403636f6d0000ff0001c00c0001000100000227000486aab92ec00c0001000100000227000486aabcddc00c0002000100004877000e036e7332046d736674036e657400c00c00020001000048770006036e7333c04fc00c00020001000048770006036e7334c04fc00c00020001000048770006036e7335c04fc00c00020001000048770006036e7331c04fc00c0006000100000227001fc09b066d736e687374c00c780c762a0000012c000002580024ea0000000e10c00c000f000100000227002a000a0d6d6963726f736f66742d636f6d046d61696c0a70726f74656374696f6e076f75746c6f6f6bc016c00c0010000100000227005958466255463644626b452b4177312f77693978674469384b567249495a75733576384c36746249515a6b4772512f7256514b4a6938436a5162427457744536346579344e4a4a776a354a36355049676756594e616264513d3dc00c001000010000022700f9f8763d7370663120696e636c7564653a5f7370662d612e6d6963726f736f66742e636f6d20696e636c7564653a5f7370662d622e6d6963726f736f66742e636f6d20696e636c7564653a5f7370662d632e6d6963726f736f66742e636f6d20696e636c7564653a5f7370662d7373672d612e6d6963726f736f66742e636f6d20696e636c7564653a7370662d612e686f746d61696c2e636f6d206970343a3134372e3234332e3132382e3234206970343a3134372e3234332e3132382e3236206970343a3134372e3234332e3132382e3235206970343a3134372e3234332e312e3437206970343a3134372e3234332e312e3438202d616c6c
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47344
;; flags: qr rd ra; QUERY: 1, ANSWER: 11, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;microsoft.com.                 IN      ANY
;; ANSWER SECTION:
microsoft.com.          551     IN      A       134.170.185.46
microsoft.com.          551     IN      A       134.170.188.221
microsoft.com.          18551   IN      NS      ns2.msft.net.
microsoft.com.          18551   IN      NS      ns3.msft.net.
microsoft.com.          18551   IN      NS      ns4.msft.net.
microsoft.com.          18551   IN      NS      ns5.msft.net.
microsoft.com.          18551   IN      NS      ns1.msft.net.
microsoft.com.          551     IN      SOA     ns1.msft.net. msnhst.microsoft.com. 2014082602 300 600 2419200 3600
microsoft.com.          551     IN      MX      10 microsoft-com.mail.protection.outlook.com.
microsoft.com.          551     IN      TXT     "FbUF6DbkE+Aw1/wi9xgDi8KVrIIZus5v8L6tbIQZkGrQ/rVQKJi8CjQbBtWtE64ey4NJJwj5J65PIggVYNabdQ=="
microsoft.com.          551     IN      TXT     "v=spf1 include:_spf-a.microsoft.com include:_spf-b.microsoft.com include:_spf-c.microsoft.com include:_spf-ssg-a.microsoft.com include:spf-a.hotmail.com ip4:147.243.128.24 ip4:147.243.128.26 ip4:147.243.128.25 ip4:147.243.1.47 ip4:147.243.1.48 -all"

Added dnslib/test/sip2sip.info-ANY.















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
;; Sending:
;; QUERY: 6c3e01000001000000000000077369703273697004696e666f0000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27710
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sip2sip.info.                  IN      ANY

;; Got answer:
;; RESPONSE: 6c3e81800001000800000000077369703273697004696e666f0000ff0001c00c0023000100000df2002900050064017308534950532b44325400055f73697073045f746370077369703273697004696e666f00c00c000200010000010e0012036e73320b646e732d686f7374696e67c014c00c0023000100000df20027001e00640173075349502b44325500045f736970045f756470077369703273697004696e666f00c00c000200010000010e0006036e7331c063c00c0001000100000df200045117e48cc00c0023000100000df20027000a00640173075349502b44325400045f736970045f746370077369703273697004696e666f00c00c000600010000010e002dc0b007646f6d61696e73096a6f62736572766572036f72670077afd6a00000708000001c2000093a8000002a30c00c000200010000010e0006036e7333c063
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27710
;; flags: qr rd ra; QUERY: 1, ANSWER: 8, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sip2sip.info.                  IN      ANY
;; ANSWER SECTION:
sip2sip.info.           3570    IN      NAPTR   5 100 "s" "SIPS+D2T" "" _sips._tcp.sip2sip.info.
sip2sip.info.           270     IN      NS      ns2.dns-hosting.info.
sip2sip.info.           3570    IN      NAPTR   30 100 "s" "SIP+D2U" "" _sip._udp.sip2sip.info.
sip2sip.info.           270     IN      NS      ns1.dns-hosting.info.
sip2sip.info.           3570    IN      A       81.23.228.140
sip2sip.info.           3570    IN      NAPTR   10 100 "s" "SIP+D2T" "" _sip._tcp.sip2sip.info.
sip2sip.info.           270     IN      SOA     ns1.dns-hosting.info. domains.jobserver.org. 2008012448 28800 7200 604800 10800
sip2sip.info.           270     IN      NS      ns3.dns-hosting.info.

Added dnslib/test/sip2sip.info-NAPTR.





































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
;; Sending:
;; QUERY: d78201000001000000000000077369703273697004696e666f0000230001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55170
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sip2sip.info.                  IN      NAPTR

;; Got answer:
;; RESPONSE: d78281800001000300000000077369703273697004696e666f0000230001c00c0023000100000dce0027001e00640173075349502b44325500045f736970045f756470077369703273697004696e666f00c00c0023000100000dce002900050064017308534950532b44325400055f73697073045f746370077369703273697004696e666f00c00c0023000100000dce0027000a00640173075349502b44325400045f736970045f746370077369703273697004696e666f00
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 55170
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sip2sip.info.                  IN      NAPTR
;; ANSWER SECTION:
sip2sip.info.           3534    IN      NAPTR   30 100 "s" "SIP+D2U" "" _sip._udp.sip2sip.info.
sip2sip.info.           3534    IN      NAPTR   5 100 "s" "SIPS+D2T" "" _sips._tcp.sip2sip.info.
sip2sip.info.           3534    IN      NAPTR   10 100 "s" "SIP+D2T" "" _sip._tcp.sip2sip.info.

Added dnslib/test/sipgate.co.uk-ANY.























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; Sending:
;; QUERY: a85701000001000000000000077369706761746502636f02756b0000ff0001
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43095
;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sipgate.co.uk.                 IN      ANY

;; Got answer:
;; RESPONSE: a85781800001000c00000000077369706761746502636f02756b0000ff0001c00c00060001000053950033036e73310b6e65747a717561647261740264650008646e7361646d696ec02f780bd92200002a3000000e1000093a8000012a70c00c00020001000053950002c02bc00c00020001000053950006036e7332c02fc00c001000010000377500cecd763d737066312061206d7820613a6d61696c2d696e2e6e65747a717561647261742e646520613a6d7830312e736970676174652e6e657420613a6d7830322e736970676174652e6e657420613a72362d312e6e65747a717561647261742e6e657420613a72362d332e6e65747a717561647261742e6e657420613a72362d342e6e65747a717561647261742e6e657420696e636c7564653a6173706d782e676f6f676c656d61696c2e636f6d20696e636c7564653a737570706f72742e7a656e6465736b2e636f6d207e616c6cc00c000f00010000539500160001054153504d58014c06474f4f474c4503434f4d00c00c000f0001000053950009000504414c5431c166c00c000f0001000053950009000504414c5432c166c00c000f0001000053950016000a064153504d58320a474f4f474c454d41494cc175c00c000f000100005395000b000a064153504d5833c1b9c00c000f000100005395000b000a064153504d5834c1b9c00c000f000100005395000b000a064153504d5835c1b9c00c0001000100000d450004d90a4f17
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43095
;; flags: qr rd ra; QUERY: 1, ANSWER: 12, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;sipgate.co.uk.                 IN      ANY
;; ANSWER SECTION:
sipgate.co.uk.          21397   IN      SOA     ns1.netzquadrat.de. dnsadmin.netzquadrat.de. 2014042402 10800 3600 604800 76400
sipgate.co.uk.          21397   IN      NS      ns1.netzquadrat.de.
sipgate.co.uk.          21397   IN      NS      ns2.netzquadrat.de.
sipgate.co.uk.          14197   IN      TXT     "v=spf1 a mx a:mail-in.netzquadrat.de a:mx01.sipgate.net a:mx02.sipgate.net a:r6-1.netzquadrat.net a:r6-3.netzquadrat.net a:r6-4.netzquadrat.net include:aspmx.googlemail.com include:support.zendesk.com ~all"
sipgate.co.uk.          21397   IN      MX      1 ASPMX.L.GOOGLE.COM.
sipgate.co.uk.          21397   IN      MX      5 ALT1.ASPMX.L.GOOGLE.COM.
sipgate.co.uk.          21397   IN      MX      5 ALT2.ASPMX.L.GOOGLE.COM.
sipgate.co.uk.          21397   IN      MX      10 ASPMX2.GOOGLEMAIL.COM.
sipgate.co.uk.          21397   IN      MX      10 ASPMX3.GOOGLEMAIL.COM.
sipgate.co.uk.          21397   IN      MX      10 ASPMX4.GOOGLEMAIL.COM.
sipgate.co.uk.          21397   IN      MX      10 ASPMX5.GOOGLEMAIL.COM.
sipgate.co.uk.          3397    IN      A       217.10.79.23

Added dnslib/test_decode.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
    Test dnslib packet encoding/decoding

    Reads test files from dnslib/test (by default) containing 
    dump of DNS exchange (packet dump & parse output) and test 
    round-trip parsing - specifically:

        - Parse packet data and zone format data and compare
        - Repack parsed packet data and compare with original

    This should test the 'parse', 'fromZone' and 'pack' methods of the
    associated record types.

    The original parsed output is created using dnslib by default so systematic
    encode/decode errors will not be found. By default the test data is
    checked against 'dig' to ensure that it is correct when generated
    using the --new option. 

    By default the module runs in 'unittest' mode (and supports unittest
    --verbose/--failfast options)

    The module can also be run in interactive mode (--interactive) and inspect
    failed tests (--debug) 

    New test data files can be automatically created using the:
    
        --new <domain> <type>

    option. The data is checked against dig output and an error raised if
    this does not match. This is effectively the same as running:

        python -m dnslib.client --query --hex --dig <domain> <type> 

    It is possible to manually generate test data files using dnslib.client
    even if the dig data doesn't match (this is usually due to an unsupported
    RDATA type which dnslib will output in hex rather then parsing contents).
    The roundtrip tests will still work in this case (the unknown RDATA is
    handled as an opaque blob). 

    In some cases the tests will fail as a result of the zone file parser
    being more fragile than the packet parser (especially with broken data)

    Note - unittests are dynamically generated from the test directory contents
    (matched against the --glob parameter) 

"""

from __future__ import print_function

from dnslib.dns import DNSRecord
from dnslib.digparser import DigParser

import argparse,binascii,code,glob,os,os.path,sys,unittest

try:
    from subprocess import getoutput
except ImportError:
    from commands import getoutput

try: 
    input = raw_input
except NameError: 
    pass

class TestContainer(unittest.TestCase):
    pass

def new_test(domain,qtype,address="8.8.8.8",port=53,nodig=False):
    tcp = False
    q = DNSRecord.question(domain,qtype)
    a_pkt = q.send(address,port)
    a = DNSRecord.parse(a_pkt)
    if a.header.tc:
        tcp = True
        a_pkt = q.send(address,port,tcp)
        a = DNSRecord.parse(a_pkt)

    if not nodig:
        dig = getoutput("dig +qr -p %d %s %s @%s" % (
                            port, domain, qtype, address))
        dig_reply = list(iter(DigParser(dig)))
        # DiG might have retried in TCP mode so get last q/a
        q_dig = dig_reply[-2]
        a_dig = dig_reply[-1]

        if q != q_dig or a != a_dig:
            if q != q_dig:
                print(";;; ERROR: Diff Question differs")
                for (d1,d2) in q.diff(q_dig):
                    if d1:
                        print(";; - %s" % d1)
                    if d2:
                        print(";; + %s" % d2)
            if a != a_dig:
                print(";;; ERROR: Diff Response differs")
                for (d1,d2) in a.diff(a_dig):
                    if d1:
                        print(";; - %s" % d1)
                    if d2:
                        print(";; + %s" % d2)
            return

    print("Writing test file: %s-%s" % (domain,qtype))
    with open("%s-%s" % (domain,qtype),"w") as f:
        print(";; Sending:",file=f)
        print(";; QUERY:",binascii.hexlify(q.pack()).decode(),file=f)
        print(q,file=f)
        print(file=f)
        print(";; Got answer:",file=f)
        print(";; RESPONSE:",binascii.hexlify(a_pkt).decode(),file=f)
        print(a,file=f)
        print(file=f)

def check_decode(f,debug=False):
    errors = []

    # Parse the q/a records
    with open(f) as x:
        q,r = DigParser(x)

    # Grab the hex data
    with open(f,'rb') as x:
        for l in x.readlines():
            if l.startswith(b';; QUERY:'):
                qdata = binascii.unhexlify(l.split()[-1])
            elif l.startswith(b';; RESPONSE:'):
                rdata = binascii.unhexlify(l.split()[-1])

    # Parse the hex data
    qparse = DNSRecord.parse(qdata)
    rparse = DNSRecord.parse(rdata)

    # Check records generated from DiG input matches
    # records parsed from packet data
    if q != qparse:
        errors.append(('Question',q.diff(qparse)))
    if r != rparse:
        errors.append(('Reply',r.diff(rparse)))

    # Repack the data 
    qpack = qparse.pack()
    rpack = rparse.pack()

    # Check if repacked question data matches original 
    # We occasionally get issues where original packet did not 
    # compress all labels - in this case we reparse packed
    # record, repack this and compare with the packed data
    if qpack != qdata:
        if len(qpack) < len(qdata):
            # Shorter - possibly compression difference
            if DNSRecord.parse(qpack).pack() != qpack:
                errors.append(('Question Pack',(qdata,qpack)))
        else:
            errors.append(('Question Pack',(qdata,qpack)))
    if rpack != rdata:
        if len(rpack) < len(rdata):
            if DNSRecord.parse(rpack).pack() != rpack:
                errors.append(('Reply Pack',(rdata,rpack)))
        else:
            errors.append(('Reply Pack',(rdata,rpack)))

    if debug:
        if errors:
            print("ERROR\n")
            print_errors(errors)
            print()
            if input(">>> Inspect [y/n]? ").lower().startswith('y'):
                code.interact(local=locals())
            print()
        else:
            print("OK")

    return errors

def print_errors(errors):
    for err,err_data in errors:
        if err == 'Question':
            print("Question error:")
            for (d1,d2) in err_data:
                if d1:
                    print(";; - %s" % d1)
                if d2:
                    print(";; + %s" % d2)
        elif err == 'Reply':
            print("Reply error:")
            for (d1,d2) in err_data:
                if d1:
                    print(";; - %s" % d1)
                if d2:
                    print(";; + %s" % d2)
        elif err == 'Question Pack':
            print("Question pack error")
            print("QDATA:",binascii.hexlify(err_data[0]))
            print(DNSRecord.parse(err_data[0]))
            print("QPACK:",binascii.hexlify(err_data[1]))
            print(DNSRecord.parse(err_data[1]))
        elif err == 'Reply Pack':
            print("Response pack error")
            print("RDATA:",binascii.hexlify(err_data[0]))
            print(DNSRecord.parse(err_data[0]))
            print("RPACK:",binascii.hexlify(err_data[1]))
            print(DNSRecord.parse(err_data[1]))

def test_generator(f):
    def test(self):
        self.assertEqual(check_decode(f),[])
    return test

if __name__ == '__main__':

    testdir = os.path.join(os.path.dirname(__file__),"test")

    p = argparse.ArgumentParser(description="Test Decode")
    p.add_argument("--new","-n",nargs=2,
                    metavar="<domain/type>",
                    help="Create new test case (args: <domain> <type>)")
    p.add_argument("--nodig",action='store_true',default=False,
                    help="Don't test new data against DiG")
    p.add_argument("--unittest",action='store_true',default=True,
                    help="Run unit tests")
    p.add_argument("--verbose",action='store_true',default=False,
                    help="Verbose unit test output")
    p.add_argument("--failfast",action='store_true',default=False,
                    help="Stop unit tests on first failure")
    p.add_argument("--interactive",action='store_true',default=False,
                    help="Run in interactive mode")
    p.add_argument("--debug",action='store_true',default=False,
                    help="Debug errors (interactive mode)")
    p.add_argument("--glob","-g",default="*",
                    help="Glob pattern")
    p.add_argument("--testdir","-t",default=testdir,
                    help="Test dir (%s)" % testdir)
    p.add_argument("--testfile","-f",default=None,
                    help="Test single file")
    args = p.parse_args()

    if args.testfile:
        e = check_decode(args.testfile,args.debug)
        if not args.debug:
            if e:
                print("ERROR\n")
                print_errors(e)
                print()
            else:
                print("OK")
    else:
        os.chdir(args.testdir)
        if args.new:
            new_test(*args.new,nodig=args.nodig)
        elif args.interactive:
            for f in glob.iglob(args.glob):
                if os.path.isfile(f):
                    print("-- %s: " % f,end='')
                    e = check_decode(f,args.debug)
                    if not args.debug:
                        if e:
                            print("ERROR\n")
                            print_errors(e)
                            print()
                        else:
                            print("OK")
        elif args.unittest:
            for f in glob.iglob(args.glob):
                if os.path.isfile(f):
                    test_name = 'test_%s' % f
                    test = test_generator(f)
                    setattr(TestContainer,test_name,test)
            unittest.main(argv=[__name__],
                          verbosity=2 if args.verbose else 1,
                          failfast=args.failfast)



Added dnslib/zoneresolver.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
# -*- coding: utf-8 -*-

from __future__ import print_function

import copy

from dnslib import RR,QTYPE,RCODE
from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger

class ZoneResolver(BaseResolver):
    """
        Simple fixed zone file resolver.
    """

    def __init__(self,zone,glob=False):
        """
            Initialise resolver from zone file. 
            Stores RRs as a list of (label,type,rr) tuples
            If 'glob' is True use glob match against zone file 
        """
        self.zone = [(rr.rname,QTYPE[rr.rtype],rr) for rr in RR.fromZone(zone)]
        self.glob = glob
        self.eq = 'matchGlob' if glob else '__eq__'

    def resolve(self,request,handler):
        """
            Respond to DNS request - parameters are request packet & handler.
            Method is expected to return DNS response
        """
        reply = request.reply()
        qname = request.q.qname
        qtype = QTYPE[request.q.qtype]
        for name,rtype,rr in self.zone:
            # Check if label & type match
            if getattr(qname,self.eq)(name) and (qtype == rtype or 
                                                 qtype == 'ANY' or 
                                                 rtype == 'CNAME'):
                # If we have a glob match fix reply label
                if self.glob:
                    a = copy.copy(rr)
                    a.rname = qname
                    reply.add_answer(a)
                else:
                    reply.add_answer(rr)
                # Check for A/AAAA records associated with reply and
                # add in additional section
                if rtype in ['CNAME','NS','MX','PTR']:
                    for a_name,a_rtype,a_rr in self.zone:
                        if a_name == rr.rdata.label and a_rtype in ['A','AAAA']:
                            reply.add_ar(a_rr)
        if not reply.rr:
            reply.header.rcode = RCODE.NXDOMAIN
        return reply

if __name__ == '__main__':

    import argparse,sys,time

    p = argparse.ArgumentParser(description="Zone DNS Resolver")
    p.add_argument("--zone","-z",required=True,
                        metavar="<zone-file>",
                        help="Zone file ('-' for stdin)")
    p.add_argument("--port","-p",type=int,default=53,
                        metavar="<port>",
                        help="Server port (default:53)")
    p.add_argument("--address","-a",default="",
                        metavar="<address>",
                        help="Listen address (default:all)")
    p.add_argument("--glob",action='store_true',default=False,
                        help="Glob match against zone file (default: false)")
    p.add_argument("--udplen","-u",type=int,default=0,
                    metavar="<udplen>",
                    help="Max UDP packet length (default:0)")
    p.add_argument("--tcp",action='store_true',default=False,
                        help="TCP server (default: UDP only)")
    p.add_argument("--log",default="request,reply,truncated,error",
                    help="Log hooks to enable (default: +request,+reply,+truncated,+error,-recv,-send,-data)")
    p.add_argument("--log-prefix",action='store_true',default=False,
                    help="Log prefix (timestamp/handler/resolver) (default: False)")
    args = p.parse_args()
    
    if args.zone == '-':
        args.zone = sys.stdin
    else:
        args.zone = open(args.zone)

    resolver = ZoneResolver(args.zone,args.glob)
    logger = DNSLogger(args.log,args.log_prefix)

    print("Starting Zone Resolver (%s:%d) [%s]" % (
                        args.address or "*",
                        args.port,
                        "UDP/TCP" if args.tcp else "UDP"))

    for rr in resolver.zone:
        print("    | ",rr[2].toZone(),sep="")
    print()

    if args.udplen:
        DNSHandler.udplen = args.udplen

    udp_server = DNSServer(resolver,
                           port=args.port,
                           address=args.address,
                           logger=logger)
    udp_server.start_thread()

    if args.tcp:
        tcp_server = DNSServer(resolver,
                               port=args.port,
                               address=args.address,
                               tcp=True,
                               logger=logger)
        tcp_server.start_thread()

    while udp_server.isAlive():
        time.sleep(1)