summaryrefslogtreecommitdiffstats
path: root/DNS/Base.py
blob: 8f8a72ad8699144280f8bb2217eb5fd5deaee523 (plain)
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
# -*- coding: utf-8 -*-

"""
$Id$

This file is part of the py3dns project.
Homepage: https://launchpad.net/py3dns

This code is covered by the standard Python License. See LICENSE for details.

Changes for Python3 port © 2011-14 Scott Kitterman <scott@kitterman.com>

    Base functionality. Request and Response classes, that sort of thing.
"""

import socket, string, types, time, select
import errno
from . import Type,Class,Opcode
import asyncore
#
# This random generator is used for transaction ids and port selection.  This
# is important to prevent spurious results from lost packets, and malicious
# cache poisoning.  This doesn't matter if you are behind a caching nameserver
# or your app is a primary DNS server only. To install your own generator,
# replace DNS.Base.random.  SystemRandom uses /dev/urandom or similar source.  
#
try:
  from random import SystemRandom
  random = SystemRandom()
except:
  import random

class DNSError(Exception): pass
class ArgumentError(DNSError): pass
class SocketError(DNSError): pass
class TimeoutError(DNSError): pass

class ServerError(DNSError):
    def __init__(self, message, rcode):
        DNSError.__init__(self, message, rcode)
        self.message = message
        self.rcode = rcode

class IncompleteReplyError(DNSError): pass

# Lib uses some of the above exception classes, so import after defining.
from . import Lib

defaults= { 'protocol':'udp', 'port':53, 'opcode':Opcode.QUERY,
            'qtype':Type.A, 'rd':1, 'timing':1, 'timeout': 30, 'server_rotate': 0,
            'server': [] }

def ParseResolvConf(resolv_path="/etc/resolv.conf"):
    "parses the /etc/resolv.conf file and sets defaults for name servers"
    with open(resolv_path, 'r') as stream:
        return ParseResolvConfFromIterable(stream)

def ParseResolvConfFromIterable(lines):
    "parses a resolv.conf formatted stream and sets defaults for name servers"
    global defaults
    for line in lines:
        line = line.strip()
        if not line or line[0]==';' or line[0]=='#':
            continue
        fields=line.split()
        if len(fields) < 2: 
            continue
        if fields[0]=='domain' and len(fields) > 1:
            defaults['domain']=fields[1]
        if fields[0]=='search':
            pass
        if fields[0]=='options':
            pass
        if fields[0]=='sortlist':
            pass
        if fields[0]=='nameserver':
            defaults['server'].append(fields[1])

def _DiscoverNameServers():
    import sys
    if sys.platform in ('win32', 'nt'):
        from . import win32dns
        defaults['server']=win32dns.RegistryResolve()
    elif sys.platform == 'darwin':
        ParseOSXSysConfig()
    else:
        return ParseResolvConf()

def DiscoverNameServers():
    """Don't call, only here for backward compatability.  We do discovery for
    you automatically.
    """
    pass

class DnsRequest:
    """ high level Request object """
    def __init__(self,*name,**args):
        self.donefunc=None
        self.py3async=None
        self.defaults = {}
        self.argparse(name,args)
        self.defaults = self.args
        self.tid = 0
        self.resulttype = ''
        if len(self.defaults['server']) == 0:
            raise DNSError('No working name servers discovered')

    def argparse(self,name,args):
        if not name and 'name' in self.defaults:
            args['name'] = self.defaults['name']
        if type(name) is bytes or type(name) is str:
            args['name']=name
        else:
            if len(name) == 1:
                if name[0]:
                    args['name']=name[0]
        if defaults['server_rotate'] and \
                type(defaults['server']) == types.ListType:
            defaults['server'] = defaults['server'][1:]+defaults['server'][:1]
        for i in list(defaults.keys()):
            if i not in args:
                if i in self.defaults:
                    args[i]=self.defaults[i]
                else:
                    args[i]=defaults[i]
        if type(args['server']) == bytes or type(args['server']) == str:
            args['server'] = [args['server']]
        self.args=args

    def socketInit(self,a,b):
        self.s = socket.socket(a,b)

    def processUDPReply(self):
        if self.timeout > 0:
            r,w,e = select.select([self.s],[],[],self.timeout)
            if not len(r):
                raise TimeoutError('Timeout')
        (self.reply, self.from_address) = self.s.recvfrom(65535)
        self.time_finish=time.time()
        self.args['server']=self.ns
        return self.processReply()

    def _readall(self,f,count):
      res = f.read(count)
      while len(res) < count:
        if self.timeout > 0:
            # should we restart timeout everytime we get a dribble of data?
            rem = self.time_start + self.timeout - time.time()
            if rem <= 0: raise DNSError('Timeout')
            self.s.settimeout(rem)
        buf = f.read(count - len(res))
        if not buf:
          raise DNSError('incomplete reply - %d of %d read' % (len(res),count))
        res += buf
      return res

    def processTCPReply(self):
        if self.timeout > 0:
            self.s.settimeout(self.timeout)
        else:
            self.s.settimeout(None)
        f = self.s.makefile('rb')
        try:
            header = self._readall(f,2)
            count = Lib.unpack16bit(header)
            self.reply = self._readall(f,count)
        finally:
            f.close()
        self.time_finish=time.time()
        self.args['server']=self.ns
        return self.processReply()

    def processReply(self):
        self.args['elapsed']=(self.time_finish-self.time_start)*1000
        if not self.resulttype:
            u = Lib.Munpacker(self.reply)
        elif self.resulttype == 'default':
            u = Lib.MunpackerDefault(self.reply)
        elif self.resulttype == 'binary':
            u = Lib.MunpackerBinary(self.reply)
        elif self.resulttype == 'text':
            u = Lib.MunpackerText(self.reply)
        elif self.resulttype == 'integer':
            u = Lib.MunpackerInteger(self.reply)
        else:
            raise SyntaxError('Unknown resulttype: ' + self.resulttype)
        r=Lib.DnsResult(u,self.args)
        r.args=self.args
        #self.args=None  # mark this DnsRequest object as used.
        return r
        #### TODO TODO TODO ####
#        if protocol == 'tcp' and qtype == Type.AXFR:
#            while 1:
#                header = f.read(2)
#                if len(header) < 2:
#                    print '========== EOF =========='
#                    break
#                count = Lib.unpack16bit(header)
#                if not count:
#                    print '========== ZERO COUNT =========='
#                    break
#                print '========== NEXT =========='
#                reply = f.read(count)
#                if len(reply) != count:
#                    print '*** Incomplete reply ***'
#                    break
#                u = Lib.Munpacker(reply)
#                Lib.dumpM(u)

    def getSource(self):
        "Pick random source port to avoid DNS cache poisoning attack."
        while True:
            try:
                source_port = random.randint(1024,65535)
                self.s.bind(('', source_port))
                break
            except socket.error as msg: 
                # errno.EADDRINUSE, 'Address already in use'
                if msg.errno != errno.EADDRINUSE: raise

    def conn(self):
        self.getSource()
        self.s.connect((self.ns,self.port))

    def qry(self,*name,**args):
        '''
        Request function for the DnsRequest class.  In addition to standard
        DNS args, the special pydns arg 'resulttype' can optionally be passed.
        Valid resulttypes are 'default', 'text', 'decimal', and 'binary'.

        Defaults are configured to be compatible with pydns:
        AAAA: decimal
        Others: text
        '''
        " needs a refactoring "
        self.argparse(name,args)
        #if not self.args:
        #    raise ArgumentError, 'reinitialize request before reuse'
        protocol = self.args['protocol']
        self.port = self.args['port']
        self.tid = random.randint(0,65535)
        self.timeout = self.args['timeout'];
        opcode = self.args['opcode']
        rd = self.args['rd']
        server=self.args['server']
        if 'resulttype' in self.args:
            self.resulttype = self.args['resulttype']
        else:
            self.resulttype = 'default'
        if type(self.args['qtype']) == bytes or type(self.args['qtype']) == str:
            try:
                qtype = getattr(Type, str(self.args['qtype'].upper()))
            except AttributeError:
                raise ArgumentError('unknown query type')
        else:
            qtype = self.args['qtype']
        if 'name' not in self.args:
            print((self.args))
            raise ArgumentError('nothing to lookup')
        qname = self.args['name']
        if qtype == Type.AXFR and protocol != 'tcp':
            print('Query type AXFR, protocol forced to TCP')
            protocol = 'tcp'
        #print('QTYPE %d(%s)' % (qtype, Type.typestr(qtype)))
        m = Lib.Mpacker()
        # jesus. keywords and default args would be good. TODO.
        m.addHeader(self.tid,
              0, opcode, 0, 0, rd, 0, 0, 0,
              1, 0, 0, 0)
        m.addQuestion(qname, qtype, Class.IN)
        self.request = m.getbuf()
        try:
            if protocol == 'udp':
                self.sendUDPRequest(server)
            else:
                self.sendTCPRequest(server)
        except socket.error as reason:
            raise SocketError(reason)
        if self.py3async:
            return None
        else:
            return self.response

    def req(self,*name,**args):
        " needs a refactoring "
        self.argparse(name,args)
        #if not self.args:
        #    raise ArgumentError, 'reinitialize request before reuse'
        try:
            if self.args['resulttype']:
                raise ArgumentError('Restulttype {0} set with DNS.req, use DNS.qry to specify result type.'.format(self.args['resulttype']))
        except:
            # resulttype isn't set and that's what we want for DNS.req
            pass
        protocol = self.args['protocol']
        self.port = self.args['port']
        self.tid = random.randint(0,65535)
        self.timeout = self.args['timeout'];
        opcode = self.args['opcode']
        rd = self.args['rd']
        server=self.args['server']
        if type(self.args['qtype']) == bytes or type(self.args['qtype']) == str:
            try:
                qtype = getattr(Type, str(self.args['qtype'].upper()))
            except AttributeError:
                raise ArgumentError('unknown query type')
        else:
            qtype = self.args['qtype']
        if 'name' not in self.args:
            print((self.args))
            raise ArgumentError('nothing to lookup')
        qname = self.args['name']
        if qtype == Type.AXFR and protocol != 'tcp':
            print('Query type AXFR, protocol forced to TCP')
            protocol = 'tcp'
        #print('QTYPE %d(%s)' % (qtype, Type.typestr(qtype)))
        m = Lib.Mpacker()
        # jesus. keywords and default args would be good. TODO.
        m.addHeader(self.tid,
              0, opcode, 0, 0, rd, 0, 0, 0,
              1, 0, 0, 0)
        m.addQuestion(qname, qtype, Class.IN)
        self.request = m.getbuf()
        try:
            if protocol == 'udp':
                self.sendUDPRequest(server)
            else:
                self.sendTCPRequest(server)
        except socket.error as reason:
            raise SocketError(reason)
        if self.py3async:
            return None
        else:
            return self.response

    def sendUDPRequest(self, server):
        "refactor me"
        first_socket_error = None
        self.response=None
        for self.ns in server:
            try:
                if self.ns.count(':'):
                    if hasattr(socket,'has_ipv6') and socket.has_ipv6:
                        self.socketInit(socket.AF_INET6, socket.SOCK_DGRAM)
                    else: continue
                else:
                    self.socketInit(socket.AF_INET, socket.SOCK_DGRAM)
                try:
                    # TODO. Handle timeouts &c correctly (RFC)
                    self.time_start=time.time()
                    self.conn()
                    if not self.py3async:
                        self.s.send(self.request)
                        r=self.processUDPReply()
                        # Since we bind to the source port and connect to the
                        # destination port, we don't need to check that here,
                        # but do make sure it's actually a DNS request that the
                        # packet is in reply to.
                        while r.header['id'] != self.tid        \
                                or self.from_address[1] != self.port:
                            r=self.processUDPReply()
                        self.response = r
                        # FIXME: check waiting async queries
                finally:
                    if not self.py3async:
                        self.s.close()
            except socket.error as e:
                # Keep trying more nameservers, but preserve the first error
                # that occurred so it can be reraised in case none of the
                # servers worked:
                first_socket_error = first_socket_error or e
                continue
            except TimeoutError as t:
                first_socket_error = first_socket_error or t
                continue
            if self.response:
                break
        if not self.response and first_socket_error:
            raise first_socket_error

    def sendTCPRequest(self, server):
        " do the work of sending a TCP request "
        first_socket_error = None
        self.response=None
        for self.ns in server:
            #print "trying tcp",self.ns
            try:
                if self.ns.count(':'):
                    if hasattr(socket,'has_ipv6') and socket.has_ipv6:
                        self.socketInit(socket.AF_INET6, socket.SOCK_STREAM)
                    else: continue
                else:
                    self.socketInit(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    # TODO. Handle timeouts &c correctly (RFC)
                    self.time_start=time.time()
                    self.conn()
                    buf = Lib.pack16bit(len(self.request))+self.request
                    # Keep server from making sendall hang
                    self.s.setblocking(0)
                    # FIXME: throws WOULDBLOCK if request too large to fit in
                    # system buffer
                    self.s.sendall(buf)
                    # SHUT_WR breaks blocking IO with google DNS (8.8.8.8)
                    #self.s.shutdown(socket.SHUT_WR)
                    r=self.processTCPReply()
                    if r.header['id'] == self.tid:
                        self.response = r
                        break
                finally:
                    self.s.close()
            except socket.error as e:
                first_socket_error = first_socket_error or e
                continue
            except TimeoutError as t:
                first_socket_error = first_socket_error or t
                continue
            if self.response:
                break
        if not self.response and first_socket_error:
            raise first_socket_error

#class DnsAsyncRequest(DnsRequest):
class DnsAsyncRequest(DnsRequest,asyncore.dispatcher_with_send):
    " an asynchronous request object. out of date, probably broken "
    def __init__(self,*name,**args):
        DnsRequest.__init__(self, *name, **args)
        # XXX todo
        if 'done' in args and args['done']:
            self.donefunc=args['done']
        else:
            self.donefunc=self.showResult
        #self.realinit(name,args) # XXX todo
        self.py3async=1
    def conn(self):
        self.getSource()
        self.connect((self.ns,self.port))
        self.time_start=time.time()
        if 'start' in self.args and self.args['start']:
            asyncore.dispatcher.go(self)
    def socketInit(self,a,b):
        self.create_socket(a,b)
        asyncore.dispatcher.__init__(self)
        self.s=self
    def handle_read(self):
        if self.args['protocol'] == 'udp':
            self.response=self.processUDPReply()
            if self.donefunc:
                self.donefunc(*(self,))
    def handle_connect(self):
        self.send(self.request)
    def handle_write(self):
        pass
    def showResult(self,*s):
        self.response.show()

def ParseOSXSysConfig():
    "Retrieves the current Mac OS X resolver settings using the scutil(8) command."
    import os, re
    scutil = os.popen('/usr/sbin/scutil --dns', 'r')
    res_re = re.compile('^\s+nameserver[]0-9[]*\s*\:\s*(\S+)$')
    sets = [ ]
    currentset = None
    while True:
        l = scutil.readline()
        if not l:
            break
        l = l.rstrip()
        if len(l) < 1 or l[0] not in string.whitespace:
            currentset = None
            continue
        m = res_re.match(l)
        if m:
            if currentset is None:
                currentset = [ ]
                sets.append(currentset)
            currentset.append(m.group(1))
    scutil.close()
    # Someday: Figure out if we should do something other than simply concatenate the sets.
    for currentset in sets:
        defaults['server'].extend(currentset)