Advertisement
imKobz

SSHNODE SOCKSPROXY

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