You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
5.4 KiB

  1. from asyncio import (
  2. CancelledError,
  3. Queue,
  4. create_task,
  5. get_running_loop,
  6. )
  7. from enum import (
  8. IntEnum,
  9. )
  10. import logging
  11. import re
  12. import socket
  13. from aiodnsresolver import (
  14. RESPONSE,
  15. TYPES,
  16. DnsRecordDoesNotExist,
  17. DnsResponseCode,
  18. Message,
  19. Resolver,
  20. ResourceRecord,
  21. pack,
  22. parse,
  23. recvfrom,
  24. )
  25. def get_socket_default():
  26. sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
  27. sock.setblocking(False)
  28. sock.bind(('', 53))
  29. return sock
  30. def get_resolver_default():
  31. return Resolver()
  32. def get_logger_default():
  33. return logging.getLogger('dnsrewriteproxy')
  34. def DnsProxy(
  35. get_resolver=get_resolver_default, get_logger=get_logger_default,
  36. get_socket=get_socket_default, num_workers=1000,
  37. rules=(),
  38. ):
  39. class ERRORS(IntEnum):
  40. FORMERR = 1
  41. SERVFAIL = 2
  42. NXDOMAIN = 3
  43. REFUSED = 5
  44. loop = get_running_loop()
  45. logger = get_logger()
  46. # The "main" task of the server: it receives incoming requests and puts
  47. # them in a queue that is then fetched from and processed by the proxy
  48. # workers
  49. async def server_worker(sock, resolve, stop):
  50. upstream_queue = Queue(maxsize=num_workers)
  51. # We have multiple upstream workers to be able to send multiple
  52. # requests upstream concurrently
  53. upstream_worker_tasks = [
  54. create_task(upstream_worker(sock, resolve, upstream_queue))
  55. for _ in range(0, num_workers)]
  56. try:
  57. while True:
  58. request_data, addr = await recvfrom(loop, [sock], 512)
  59. await upstream_queue.put((request_data, addr))
  60. finally:
  61. # Finish upstream requests
  62. await upstream_queue.join()
  63. for upstream_task in upstream_worker_tasks:
  64. upstream_task.cancel()
  65. for upstream_task in upstream_worker_tasks:
  66. try:
  67. await upstream_task
  68. except CancelledError:
  69. pass
  70. await stop()
  71. async def upstream_worker(sock, resolve, upstream_queue):
  72. while True:
  73. request_data, addr = await upstream_queue.get()
  74. try:
  75. response_data = await get_response_data(resolve, request_data)
  76. # Sendto for non-blocking UDP sockets cannot raise a BlockingIOError
  77. # https://stackoverflow.com/a/59794872/1319998
  78. sock.sendto(response_data, addr)
  79. except Exception:
  80. logger.exception('Processing request from %s', addr)
  81. finally:
  82. upstream_queue.task_done()
  83. async def get_response_data(resolve, request_data):
  84. # This may raise an exception, which is handled at a higher level.
  85. # We can't [and I suspect shouldn't try to] return an error to the
  86. # client, since we're not able to extract the QID, so the client won't
  87. # be able to match it with an outgoing request
  88. query = parse(request_data)
  89. try:
  90. return pack(
  91. error(query, ERRORS.REFUSED) if query.qd[0].qtype != TYPES.A else
  92. (await proxy(resolve, query))
  93. )
  94. except Exception:
  95. logger.exception('Failed to proxy %s', query)
  96. return pack(error(query, ERRORS.SERVFAIL))
  97. async def proxy(resolve, query):
  98. name_bytes = query.qd[0].name
  99. name_str_lower = query.qd[0].name.lower().decode('idna')
  100. for pattern, replace in rules:
  101. rewritten_name_str, num_matches = re.subn(pattern, replace, name_str_lower)
  102. if num_matches:
  103. break
  104. else:
  105. # No break was triggered, i.e. no match
  106. return error(query, ERRORS.REFUSED)
  107. try:
  108. ip_addresses = await resolve(rewritten_name_str, TYPES.A)
  109. except DnsRecordDoesNotExist:
  110. return error(query, ERRORS.NXDOMAIN)
  111. except DnsResponseCode as dns_response_code_error:
  112. return error(query, dns_response_code_error.args[0])
  113. now = loop.time()
  114. def ttl(ip_address):
  115. return int(max(0.0, ip_address.expires_at - now))
  116. reponse_records = tuple(
  117. ResourceRecord(name=name_bytes, qtype=TYPES.A,
  118. qclass=1, ttl=ttl(ip_address), rdata=ip_address.packed)
  119. for ip_address in ip_addresses
  120. )
  121. return Message(
  122. qid=query.qid, qr=RESPONSE, opcode=0, aa=0, tc=0, rd=0, ra=1, z=0, rcode=0,
  123. qd=query.qd, an=reponse_records, ns=(), ar=(),
  124. )
  125. async def start():
  126. # The socket is created synchronously and passed to the server worker,
  127. # so if there is an error creating it, this function will raise an
  128. # exception. If no exeption is raise, we are indeed listening#
  129. sock = get_socket()
  130. # The resolver is also created synchronously, since it can parse
  131. # /etc/hosts or /etc/resolve.conf, and can raise an exception if
  132. # something goes wrong with that
  133. resolve, clear_cache = get_resolver()
  134. async def stop():
  135. sock.close()
  136. await clear_cache()
  137. return create_task(server_worker(sock, resolve, stop))
  138. return start
  139. def error(query, rcode):
  140. return Message(
  141. qid=query.qid, qr=RESPONSE, opcode=0, aa=0, tc=0, rd=0, ra=1, z=0, rcode=rcode,
  142. qd=query.qd, an=(), ns=(), ar=(),
  143. )