Advertisement
Guest User

Untitled

a guest
May 25th, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.66 KB | None | 0 0
  1. # Author: Nicolas VERDIER (contact@n1nj4.eu)
  2. # This file is part of pr0cks.
  3. #
  4. # pr0cks is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # pr0cks is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with pr0cks. If not, see <http://www.gnu.org/licenses/>.
  16.  
  17. import sys
  18. import StringIO
  19. import time
  20. import struct
  21. import os
  22. import asyncore
  23. import socket
  24. import socks
  25. import argparse
  26. import traceback
  27. import logging
  28. logging.basicConfig(stream=sys.stderr, level=logging.WARNING)
  29. import binascii
  30. from collections import OrderedDict
  31.  
  32. dnslib_imported=False
  33. dns_cache=OrderedDict()
  34. DNS_CACHE_SIZE=1000
  35.  
  36. def display(msg):
  37. msg=msg.strip()
  38. if msg.startswith("[-]"):
  39. print "\033[31m[-]\033[0m"+msg[3:]
  40. elif msg.startswith("[+]"):
  41. print "\033[32m[+]\033[0m"+msg[3:]
  42. elif msg.startswith("[i]"):
  43. print "\033[1;30m[i]\033[0m"+msg[3:]
  44. else:
  45. print msg
  46.  
  47. try:
  48. from dnslib import DNSRecord, QTYPE
  49. from dnslib.server import DNSServer,DNSHandler,BaseResolver,DNSLogger
  50. class ProxyResolver(BaseResolver):
  51. def __init__(self,address,port):
  52. self.address = address
  53. self.port = port
  54.  
  55. def resolve(self,request,handler):
  56. if handler.protocol == 'udp':
  57. proxy_r = request.send(self.address,self.port)
  58. else:
  59. proxy_r = request.send(self.address,self.port,tcp=True)
  60. reply = DNSRecord.parse(proxy_r)
  61. return reply
  62.  
  63. class PassthroughDNSHandler(DNSHandler):
  64. def get_reply(self,data):
  65. global dns_cache
  66. global args
  67. host,port = self.server.resolver.address,self.server.resolver.port
  68. request = DNSRecord.parse(data)
  69.  
  70.  
  71. domain=str(request.q.qname)
  72. qtype=str(QTYPE.get(request.q.qtype))
  73. index=domain+"/"+qtype
  74. if not args.no_cache and index in dns_cache:
  75. if time.time()<dns_cache[index][0]:
  76. if args is not None and args.verbose:
  77. try:
  78. display("[i] %s served value from cache: %s"%(index, ', '.join([x.rdata for x in dns_cache[index][1]])))
  79. except:
  80. pass
  81. rep=request.reply()
  82. rep.add_answer(*dns_cache[index][1])
  83. return rep.pack()
  84. if args is not None and args.verbose:
  85. display("[i] domain %s requested using TCP server %s"%(domain, args.dns_server))
  86. data = struct.pack("!H",len(data)) + data
  87. response = send_tcp(data,host,port)
  88. response = response[2:]
  89. reply = DNSRecord.parse(response)
  90. if args.verbose:
  91. try:
  92. display("[i] %s %s resolve to %s"%(domain, qtype, ', '.join([x.rdata for x in reply.rr])))
  93. except:
  94. pass
  95. ttl=3600
  96. try:
  97. ttl=reply.rr[0].ttl
  98. except Exception:
  99. try:
  100. ttl=reply.rr.ttl
  101. except Exception:
  102. pass
  103. dns_cache[index]=(int(time.time())+ttl, reply.rr)
  104. if len(dns_cache)>DNS_CACHE_SIZE:
  105. dns_cache.popitem(last=False)
  106. return response
  107.  
  108. def send_tcp(data,host,port):
  109. """
  110. Helper function to send/receive DNS TCP request
  111. (in/out packets will have prepended TCP length header)
  112. """
  113. sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  114. sock.settimeout(5)
  115. sock.connect((host,port))
  116. sock.sendall(data)
  117. response = sock.recv(8192)
  118. length = struct.unpack("!H",bytes(response[:2]))[0]
  119. while len(response) - 2 < length:
  120. response += sock.recv(8192)
  121. sock.close()
  122. return response
  123. dnslib_imported=True
  124. except ImportError:
  125. display("[-] WARNING: The following dependency is needed to proxify DNS through tcp: pip install dnslib")
  126.  
  127. args=None
  128. if __name__=='__main__':
  129. parser = argparse.ArgumentParser(prog='procks', description="Transparent SOCKS5/SOCKS4/HTTP_CONNECT Proxy")
  130. parser.add_argument('-n', '--nat', action='store_true', help="set bind address to 0.0.0.0 to make pr0cks work from a netfilter FORWARD rule instead of OUTPUT")
  131. parser.add_argument('--enjoysoft', action='store_true', help="set bind address to 192.168.0.31")
  132. parser.add_argument('-v', '--verbose', action="store_true", help="print all the connections requested through the proxy")
  133. parser.add_argument('-c', '--no-cache', action="store_true", help="don't cache dns requests")
  134. parser.add_argument('--dns-port', default=1053, type=int, help="dns port to listen on (default 1053)")
  135. parser.add_argument('--dns-server', default="8.8.8.8:53", help="ip:port of the DNS server to forward all DNS requests to using TCP through the proxy (default 8.8.8.8:53)")#208.67.222.222:53
  136. args=parser.parse_args()
  137.  
  138. bind_address="127.0.0.1"
  139. if args.nat:
  140. bind_address="0.0.0.0"
  141. if args.enjoysoft:
  142. bind_address="192.168.0.31"
  143. if dnslib_imported:
  144. try:
  145. dns_srv, dns_port=args.dns_server.split(':',1)
  146. dns_port=int(dns_port)
  147. except Exception as e:
  148. display("[-] %s"%e)
  149. display("[-] Invalid dns server : %s"%args.dns_server)
  150. exit(1)
  151. resolver = ProxyResolver(dns_srv,dns_port)
  152. handler = PassthroughDNSHandler # if args.passthrough else DNSHandler
  153. logger = DNSLogger("request,reply,truncated,error", False)
  154. udp_server = DNSServer(resolver,
  155. port=args.dns_port,
  156. address=bind_address,
  157. logger=logger,
  158. handler=handler)
  159. udp_server.start_thread()
  160. display("[+] DNS server started on %s:%s forwarding all DNS trafic to %s:%s using TCP"%(bind_address, args.dns_port, dns_srv, dns_port))
  161.  
  162. except KeyboardInterrupt:
  163. sys.stdout.write("\n")
  164. sys.exit(0)
  165. except Exception as e:
  166. sys.stderr.write(traceback.format_exc())
  167. sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement