handledns.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/python3
  2. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  3. #
  4. # Permission to use, copy, modify, and/or distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  9. # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  10. # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  12. # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  13. # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  14. # PERFORMANCE OF THIS SOFTWARE.
  15. import errno
  16. import sys
  17. import select
  18. import socket
  19. import struct
  20. import time
  21. from pydnspp import *
  22. RECV_BUFSIZE = 65536
  23. def _wait_for(ir, iw, ix, expiration):
  24. done = False
  25. while not done:
  26. if expiration is None:
  27. timeout = None
  28. else:
  29. timeout = expiration - time.time()
  30. if timeout <= 0.0:
  31. raise socket.timeout
  32. try:
  33. if timeout is None:
  34. (r,w,x) = select.select(ir,iw,ix)
  35. else:
  36. (r,w,x) = select.select(ir,iw,ix,timeout)
  37. except select.error as e:
  38. if e.args[0] != errno.EINTR:
  39. raise e
  40. else:
  41. done = True
  42. if len(r) == 0 and len(w) == 0 and len(x) == 0:
  43. raise socket.timeout
  44. def _wait_for_readable(s,expiration):
  45. _wait_for([s],[],[s],expiration)
  46. def _compute_expiration(timeout):
  47. if timeout is None:
  48. return None
  49. else:
  50. return time.time() + timeout
  51. def _send_udp(q, where, timeout=None, port=53, source=None, source_port=0):
  52. """ Return the response obtained after sending a query via UDP.
  53. Refered to dnspython source code. """
  54. qwire = MessageRenderer()
  55. q.to_wire(qwire)
  56. if source is not None:
  57. source = (source, source_port)
  58. udpCliSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
  59. expiration = _compute_expiration(timeout)
  60. if source is not None:
  61. udpCliSock.bind(source)
  62. dest = (where, port)
  63. udpCliSock.sendto(qwire.get_data(), dest)
  64. while True:
  65. _wait_for_readable(udpCliSock, expiration)
  66. rwire, r_addr = udpCliSock.recvfrom(RECV_BUFSIZE)
  67. if dest[0] == r_addr[0] and dest[1:] == r_addr[1:]:
  68. break
  69. else:
  70. sys.stderr.write('Got a respose from: %s instead of %s\n' % (r_addr, dest))
  71. udpCliSock.close()
  72. resp = Message(Message.PARSE)
  73. resp.from_wire(rwire)
  74. return resp
  75. def _connect(s, address):
  76. try:
  77. s.connect(address)
  78. except socket.error as msg:
  79. (exctype,value) = sys.exc_info()[:2]
  80. if value.errno != errno.EINPROGRESS and \
  81. value.errno != errno.EWOULDBLOCK and \
  82. value.errno != errno.EALREADY:
  83. raise value
  84. def _net_read(sock, count, expiration):
  85. """ Read the specified number of bytes from sock. Keep trying until we
  86. either get the desired amount, or we hit EOF.
  87. A Timeout exception will be raised if the operation is not completed
  88. by the expiration time.
  89. """
  90. msgdata = b''
  91. while count > 0:
  92. _wait_for_readable(sock, expiration)
  93. data = sock.recv(count)
  94. if not data:
  95. return None
  96. count -= len(data)
  97. msgdata += data
  98. return msgdata
  99. def _net_write(sock, data, expiration):
  100. """ Write the specified data to the socket.
  101. A Timeout exception will be raised if the operation is not completed
  102. by the expiration time.
  103. """
  104. current = 0
  105. l = len(data)
  106. while current < 1:
  107. _wait_for_writable(sock, expiration)
  108. current += sock.send(data[current:])
  109. def _send_tcp(q, dest, timeout=None, dest_port=53, source=None, source_port=0):
  110. """ Return the response obtained after sending a query via TCP.
  111. Refered to dnspython source code """
  112. qwire = MessageRenderer()
  113. q.to_wire(qwire)
  114. if source is not None:
  115. source = (source, source_port)
  116. dest = (dest, dest_port)
  117. tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  118. expiration = _compute_expiration(timeout)
  119. tcpCliSock.setblocking(False)
  120. if source is not None:
  121. tcpCliSock.bind(source)
  122. _connect(tcpCliSock, dest)
  123. wire_s = qwire.get_data()
  124. l = len(wire_s)
  125. tcpmsg = struct.pack("!H", l) + wire_s
  126. _net_write(tcpCliSock, tcpmsg, expiration)
  127. ldata = _net_read(tcpCliSock, 2, expiration)
  128. (l,) = struct.unpack("!H", ldata)
  129. res_wire = _net_read(tcpCliSock, l, expiration)
  130. tcpCliSock.close()
  131. resp = Message(Message.PARSE)
  132. resp.from_wire(res_wire)
  133. return resp
  134. def send_req(query, server, port=53, timeout=5):
  135. """ Return the response message obtained after
  136. sending the query.
  137. @param query: the query readed from input file
  138. @type query: dict
  139. @param server: the testee server ip address
  140. @type server: string
  141. @param port: the testee server listening port. The default is 53.
  142. @type port: int
  143. @param timeout: the number of seconds to wait before the query times out.
  144. The default is 5.
  145. @type timeout: float
  146. """
  147. qname = query["qname"]
  148. qtype = query["qtype"]
  149. qclass = query["qclass"]
  150. edns = query["edns"]
  151. dnssec = query["dnssec"]
  152. qheader = query['header']
  153. protocol = query['protocol']
  154. msg = Message(Message.RENDER)
  155. msg.set_qid(int(qheader['id']))
  156. msg.set_opcode(Opcode.QUERY)
  157. msg.set_rcode(Rcode(int(qheader['rcode'])))
  158. if qheader['qr'] == 1:
  159. msg.set_header_flag(Message.HEADERFLAG_QR)
  160. if qheader['aa'] == 1:
  161. msg.set_header_flag(Message.HEADERFLAG_AA)
  162. if qheader['tc'] == 1:
  163. msg.set_header_flag(Message.HEADERFLAG_TC)
  164. if qheader['rd'] == 1:
  165. msg.set_header_flag(Message.HEADERFLAG_RD)
  166. if qheader['ra'] == 1:
  167. msg.set_header_flag(Message.HEADERFLAG_RA)
  168. if qheader['ad'] == 1:
  169. msg.set_header_flag(Message.HEADERFLAG_AD)
  170. if qheader['cd'] == 1:
  171. msg.set_header_flag(Message.HEADERFLAG_CD)
  172. try:
  173. msg.add_question(Question(Name(qname), \
  174. RRClass(qclass), RRType(qtype)))
  175. except InvalidRRType as e:
  176. sys.stderr.write('Unrecognized RR queryeter string: %s\n' % qtype)
  177. return None
  178. if edns == 1 or dnssec == 1:
  179. edns_conf = EDNS()
  180. payload = query['payload']
  181. edns_conf.set_udp_size(payload)
  182. if dnssec == 1:
  183. edns_conf.set_dnssec_awareness(True)
  184. else:
  185. edns_conf.set_dnssec_awareness(False)
  186. msg.set_edns(edns_conf)
  187. port = int(port)
  188. if protocol == 'udp':
  189. resp = _send_udp(msg, server, timeout, port)
  190. else:
  191. resp = _send_tcp(msg, server, timeout, port)
  192. return resp
  193. def main():
  194. query = {}
  195. query['qname'] = "A.example.com"
  196. query['qtype'] = "ANY"
  197. query['qclass'] = "IN"
  198. query["edns"] = 1
  199. query["dnssec"] = 1
  200. query["protocol"] = 'tcp'
  201. query["payload"] = 4096
  202. query['header'] = {}
  203. query['header']['id'] = 0
  204. query['header']['qr'] = 0
  205. query['header']['opcode'] = 0
  206. query['header']['aa'] = 0
  207. query['header']['tc'] = 0
  208. query['header']['rd'] = 1
  209. query['header']['ra'] = 0
  210. query['header']['z'] = 0
  211. query['header']['ad'] = 0
  212. query['header']['cd'] = 0
  213. query['header']['rcode'] = 0
  214. query['header']['qdcount'] = 0
  215. query['header']['ancount'] = 0
  216. query['header']['nscount'] = 0
  217. query['header']['arcount'] = 0
  218. resp = send_req(query, "218.241.108.124", "4040")
  219. if resp == None:
  220. print('timeout')
  221. exit(1)
  222. print('qid -----')
  223. print(resp.get_qid())
  224. rrset = resp.get_section(Message.SECTION_ANSWER)[0]
  225. print('name-----')
  226. print(rrset.get_name())
  227. print('type')
  228. print(rrset.get_type())
  229. print('class-----')
  230. print(rrset.get_class())
  231. print(rrset.get_ttl())
  232. rdata = rrset.get_rdata()
  233. print(rdata[0].to_text())
  234. if __name__ == "__main__":
  235. main()