Advertisement
imKobz

Untitled

Aug 15th, 2020
1,310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.38 KB | None | 0 0
  1. import socket, threading, thread, select, signal, sys, time, getopt
  2.  
  3. # Python Proxy ou Socks
  4.  
  5. # Porta do Proxy
  6. proxyport = 80
  7.  
  8. # CONFIG
  9. LISTENING_ADDR = '0.0.0.0'
  10. LISTENING_PORT = proxyport
  11.  
  12. PASS = ''
  13.  
  14. # CONST
  15. BUFLEN = 4096 * 4
  16. TIMEOUT = 60
  17. DEFAULT_HOST = '127.0.0.1:22'
  18. RESPONSE = 'HTTP/1.1 200 <font color="green">Secure Proxy</font>\r\n\r\n'
  19. #RESPONSE = 'HTTP/1.1 200 Hello_World!\r\nContent-length: 0\r\n\r\nHTTP/1.1 200 Connection established\r\n\r\n' # lint:ok
  20.  
  21.  
  22. class Server(threading.Thread):
  23. def __init__(self, host, port):
  24. threading.Thread.__init__(self)
  25. self.running = False
  26. self.host = host
  27. self.port = port
  28. self.threads = []
  29. self.threadsLock = threading.Lock()
  30. self.logLock = threading.Lock()
  31.  
  32. def run(self):
  33. self.soc = socket.socket(socket.AF_INET)
  34. self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  35. self.soc.settimeout(2)
  36. self.soc.bind((self.host, self.port))
  37. self.soc.listen(0)
  38. self.running = True
  39.  
  40. try:
  41. while self.running:
  42. try:
  43. c, addr = self.soc.accept()
  44. c.setblocking(1)
  45. except socket.timeout:
  46. continue
  47.  
  48. conn = ConnectionHandler(c, self, addr)
  49. conn.start()
  50. self.addConn(conn)
  51. finally:
  52. self.running = False
  53. self.soc.close()
  54.  
  55. def printLog(self, log):
  56. self.logLock.acquire()
  57. print log
  58. self.logLock.release()
  59.  
  60. def addConn(self, conn):
  61. try:
  62. self.threadsLock.acquire()
  63. if self.running:
  64. self.threads.append(conn)
  65. finally:
  66. self.threadsLock.release()
  67.  
  68. def removeConn(self, conn):
  69. try:
  70. self.threadsLock.acquire()
  71. self.threads.remove(conn)
  72. finally:
  73. self.threadsLock.release()
  74.  
  75. def close(self):
  76. try:
  77. self.running = False
  78. self.threadsLock.acquire()
  79.  
  80. threads = list(self.threads)
  81. for c in threads:
  82. c.close()
  83. finally:
  84. self.threadsLock.release()
  85.  
  86.  
  87. class ConnectionHandler(threading.Thread):
  88. def __init__(self, socClient, server, addr):
  89. threading.Thread.__init__(self)
  90. self.clientClosed = False
  91. self.targetClosed = True
  92. self.client = socClient
  93. self.client_buffer = ''
  94. self.server = server
  95. self.log = 'Connection: ' + str(addr)
  96.  
  97. def close(self):
  98. try:
  99. if not self.clientClosed:
  100. self.client.shutdown(socket.SHUT_RDWR)
  101. self.client.close()
  102. except:
  103. pass
  104. finally:
  105. self.clientClosed = True
  106.  
  107. try:
  108. if not self.targetClosed:
  109. self.target.shutdown(socket.SHUT_RDWR)
  110. self.target.close()
  111. except:
  112. pass
  113. finally:
  114. self.targetClosed = True
  115.  
  116. def run(self):
  117. try:
  118. self.client_buffer = self.client.recv(BUFLEN)
  119.  
  120. hostPort = self.findHeader(self.client_buffer, 'X-Real-Host')
  121.  
  122. if hostPort == '':
  123. hostPort = DEFAULT_HOST
  124.  
  125. split = self.findHeader(self.client_buffer, 'X-Split')
  126.  
  127. if split != '':
  128. self.client.recv(BUFLEN)
  129.  
  130. if hostPort != '':
  131. passwd = self.findHeader(self.client_buffer, 'X-Pass')
  132.  
  133. if len(PASS) != 0 and passwd == PASS:
  134. self.method_CONNECT(hostPort)
  135. elif len(PASS) != 0 and passwd != PASS:
  136. self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n')
  137. elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'):
  138. self.method_CONNECT(hostPort)
  139. else:
  140. self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n')
  141. else:
  142. print '- No X-Real-Host!'
  143. self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n')
  144.  
  145. except Exception as e:
  146. self.log += ' - error: ' + e.strerror
  147. self.server.printLog(self.log)
  148. pass
  149. finally:
  150. self.close()
  151. self.server.removeConn(self)
  152.  
  153. def findHeader(self, head, header):
  154. aux = head.find(header + ': ')
  155.  
  156. if aux == -1:
  157. return ''
  158.  
  159. aux = head.find(':', aux)
  160. head = head[aux+2:]
  161. aux = head.find('\r\n')
  162.  
  163. if aux == -1:
  164. return ''
  165.  
  166. return head[:aux];
  167.  
  168. def connect_target(self, host):
  169. i = host.find(':')
  170. if i != -1:
  171. port = int(host[i+1:])
  172. host = host[:i]
  173. else:
  174. if self.method=='CONNECT':
  175. port = 443
  176. else:
  177. port = 80
  178.  
  179. (soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0]
  180.  
  181. self.target = socket.socket(soc_family, soc_type, proto)
  182. self.targetClosed = False
  183. self.target.connect(address)
  184.  
  185. def method_CONNECT(self, path):
  186. self.log += ' - CONNECT ' + path
  187.  
  188. self.connect_target(path)
  189. self.client.sendall(RESPONSE)
  190. self.client_buffer = ''
  191.  
  192. self.server.printLog(self.log)
  193. self.doCONNECT()
  194.  
  195. def doCONNECT(self):
  196. socs = [self.client, self.target]
  197. count = 0
  198. error = False
  199. while True:
  200. count += 1
  201. (recv, _, err) = select.select(socs, [], socs, 3)
  202. if err:
  203. error = True
  204. if recv:
  205. for in_ in recv:
  206. try:
  207. data = in_.recv(BUFLEN)
  208. if data:
  209. if in_ is self.target:
  210. self.client.send(data)
  211. else:
  212. while data:
  213. byte = self.target.send(data)
  214. data = data[byte:]
  215.  
  216. count = 0
  217. else:
  218. break
  219. except:
  220. error = True
  221. break
  222. if count == TIMEOUT:
  223. error = True
  224.  
  225. if error:
  226. break
  227.  
  228.  
  229. def print_usage():
  230. print 'Usage: proxy.py -p <port>'
  231. print ' proxy.py -b <bindAddr> -p <port>'
  232. print ' proxy.py -b 0.0.0.0 -p 80'
  233.  
  234. def parse_args(argv):
  235. global LISTENING_ADDR
  236. global LISTENING_PORT
  237.  
  238. try:
  239. opts, args = getopt.getopt(argv,"hb:p:",["bind=","port="])
  240. except getopt.GetoptError:
  241. print_usage()
  242. sys.exit(2)
  243. for opt, arg in opts:
  244. if opt == '-h':
  245. print_usage()
  246. sys.exit()
  247. elif opt in ("-b", "--bind"):
  248. LISTENING_ADDR = arg
  249. elif opt in ("-p", "--port"):
  250. LISTENING_PORT = int(arg)
  251.  
  252.  
  253. def main(host=LISTENING_ADDR, port=LISTENING_PORT):
  254. server = Server(LISTENING_ADDR, LISTENING_PORT)
  255. server.start()
  256.  
  257. while True:
  258. try:
  259. time.sleep(2)
  260. except KeyboardInterrupt:
  261. print '\033[31m'+'----PARANDO'+'\033[0;0m'
  262. server.close()
  263. break
  264.  
  265. if __name__ == '__main__':
  266. parse_args(sys.argv[1:])
  267. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement