Guest User

Original

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