Italiano English
Edit History Actions

fakeDNS.py

   1 
   2 # Fake dns multithread
   3 
   4 from SocketServer import *
   5 
   6 FAKEADDRESS="111.111.111.111"
   7 PORT=53 #udp
   8 
   9 class DNSQuery:
  10   #da http://preachermm.blogspot.com/2006/04/servidor-fake-dns-en-python.html (single thread)
  11   def __init__(self, data):
  12     self.data=data
  13     self.dominio=''
  14     tipo = (ord(data[2]) >> 3) & 15   # Opcode bits
  15     if tipo == 0:                     # Standard query
  16       ini=12
  17       lon=ord(data[ini])
  18       while lon != 0:
  19         self.dominio+=data[ini+1:ini+lon+1]+'.'
  20         ini+=lon+1
  21         lon=ord(data[ini])
  22 
  23   def respuesta(self, ip):
  24     packet=''
  25     if self.dominio:
  26       packet+=self.data[:2] + "\x81\x80"
  27       packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00'   # Questions and Answers Counts
  28       packet+=self.data[12:]                                         # Original Domain Name Question
  29       packet+='\xc0\x0c'                                             # Pointer to domain name
  30       packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'             # Response type, ttl and resource data length -> 4 bytes
  31       packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) # 4bytes of IP
  32     return packet
  33 #DNSQuery
  34 
  35 class DNSRequestHandler (DatagramRequestHandler):
  36         def handle(self):
  37                 DNSRequest=self.rfile.read()
  38                 q=DNSQuery(DNSRequest)
  39                 DNSDatagram=q.respuesta(FAKEADDRESS)
  40                 self.wfile.write(DNSDatagram)
  41 #DNSRequestHandler
  42 
  43 #crea una classe di server udp threadizzato
  44 class FakeDNSServer (ThreadingMixIn, UDPServer): pass
  45 
  46 dummyDNS=FakeDNSServer(('',PORT),DNSRequestHandler)
  47 
  48 #per prevenire attacchi, l'unico modo x fermare il server e' killarlo (SIGTERM, SIGKILL) o premere ctrl-C
  49 going=True
  50 while going:
  51         try:
  52                 dummyDNS.serve_forever()
  53         except KeyboardInterrupt:
  54                 going=False
  55         except:
  56                 pass