wsproxy.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/python
  2. '''
  3. A WebSocket to TCP socket proxy with support for "wss://" encryption.
  4. You can make a cert/key with openssl using:
  5. openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
  6. as taken from http://docs.python.org/dev/library/ssl.html#certificates
  7. '''
  8. import sys, os, socket, ssl, time, traceback, re
  9. from base64 import b64encode, b64decode
  10. from select import select
  11. buffer_size = 65536
  12. send_seq = 0
  13. client_settings = {}
  14. server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
  15. Upgrade: WebSocket\r
  16. Connection: Upgrade\r
  17. WebSocket-Origin: %s\r
  18. WebSocket-Location: %s://%s%s\r
  19. WebSocket-Protocol: sample\r
  20. \r
  21. """
  22. policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
  23. traffic_legend = """
  24. Traffic Legend:
  25. } - Client receive
  26. }. - Client receive partial
  27. { - Target receive
  28. > - Target send
  29. >. - Target send partial
  30. < - Client send
  31. <. - Client send partial
  32. """
  33. def traffic(token="."):
  34. sys.stdout.write(token)
  35. sys.stdout.flush()
  36. def decode(buf):
  37. """ Parse out WebSocket packets. """
  38. if buf.count('\xff') > 1:
  39. traffic(str(buf.count('\xff')))
  40. return [b64decode(d[1:]) for d in buf.split('\xff')]
  41. else:
  42. return [b64decode(buf[1:-1])]
  43. def proxy(client, target):
  44. """ Proxy WebSocket to normal socket. """
  45. global send_seq
  46. cqueue = []
  47. cpartial = ""
  48. tqueue = []
  49. socks = [client, target]
  50. while True:
  51. ins, outs, excepts = select(socks, socks, socks, 1)
  52. if excepts: raise Exception("Socket exception")
  53. if tqueue and target in outs:
  54. #print "Target send: %s" % repr(tqueue[0])
  55. ##log.write("Target send: %s\n" % map(ord, tqueue[0]))
  56. dat = tqueue.pop(0)
  57. sent = target.send(dat)
  58. if sent == len(dat):
  59. traffic(">")
  60. else:
  61. tqueue.insert(0, dat[sent:])
  62. traffic(">.")
  63. if cqueue and client in outs:
  64. dat = cqueue.pop(0)
  65. sent = client.send(dat)
  66. if sent == len(dat):
  67. traffic("<")
  68. ##log.write("Client send: %s\n" % repr(dat))
  69. else:
  70. cqueue.insert(0, dat[sent:])
  71. traffic("<.")
  72. ##log.write("Client send partial: %s\n" % repr(dat[0:send]))
  73. if target in ins:
  74. buf = target.recv(buffer_size)
  75. if len(buf) == 0: raise Exception("Target closed")
  76. ##log.write("Target recv (%d): %s\n" % (len(buf), map(ord, buf)))
  77. if client_settings.get("b64encode"):
  78. buf = b64encode(buf)
  79. if client_settings.get("seq_num"):
  80. cqueue.append("\x00%d:%s\xff" % (send_seq, buf))
  81. send_seq += 1
  82. else:
  83. cqueue.append("\x00%s\xff" % buf)
  84. traffic("{")
  85. if client in ins:
  86. buf = client.recv(buffer_size)
  87. if len(buf) == 0: raise Exception("Client closed")
  88. if buf[-1] == "\xff":
  89. traffic("}")
  90. ##log.write("Client recv (%d): %s\n" % (len(buf), repr(buf)))
  91. if cpartial:
  92. tqueue.extend(decode(cpartial + buf))
  93. cpartial = ""
  94. else:
  95. tqueue.extend(decode(buf))
  96. else:
  97. traffic("}.")
  98. ##log.write("Client recv partial (%d): %s\n" % (len(buf), repr(buf)))
  99. cpartial = cpartial + buf
  100. def do_handshake(sock):
  101. global client_settings
  102. # Peek, but don't read the data
  103. handshake = sock.recv(1024, socket.MSG_PEEK)
  104. #print "Handshake [%s]" % repr(handshake)
  105. if handshake.startswith("<policy-file-request/>"):
  106. handshake = sock.recv(1024)
  107. print "Sending flash policy response"
  108. sock.send(policy_response)
  109. sock.close()
  110. return False
  111. elif handshake.startswith("\x16"):
  112. retsock = ssl.wrap_socket(
  113. sock,
  114. server_side=True,
  115. certfile='self.pem',
  116. ssl_version=ssl.PROTOCOL_TLSv1)
  117. scheme = "wss"
  118. print "Using SSL/TLS"
  119. else:
  120. retsock = sock
  121. scheme = "ws"
  122. print "Using plain (not SSL) socket"
  123. handshake = retsock.recv(4096)
  124. req_lines = handshake.split("\r\n")
  125. _, path, _ = req_lines[0].split(" ")
  126. _, origin = req_lines[4].split(" ")
  127. _, host = req_lines[3].split(" ")
  128. # Parse settings from the path
  129. cvars = path.partition('?')[2].partition('#')[0].split('&')
  130. for cvar in [c for c in cvars if c]:
  131. name, _, value = cvar.partition('=')
  132. client_settings[name] = value and value or True
  133. print "client_settings:", client_settings
  134. retsock.send(server_handshake % (origin, scheme, host, path))
  135. return retsock
  136. def start_server(listen_port, target_host, target_port):
  137. global send_seq
  138. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  139. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  140. lsock.bind(('', listen_port))
  141. lsock.listen(100)
  142. print traffic_legend
  143. while True:
  144. try:
  145. csock = tsock = None
  146. print 'waiting for connection on port %s' % listen_port
  147. startsock, address = lsock.accept()
  148. print 'Got client connection from %s' % address[0]
  149. csock = do_handshake(startsock)
  150. if not csock: continue
  151. print "Connecting to: %s:%s" % (target_host, target_port)
  152. tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  153. tsock.connect((target_host, target_port))
  154. send_seq = 0
  155. proxy(csock, tsock)
  156. except Exception:
  157. print "Ignoring exception:"
  158. print traceback.format_exc()
  159. if csock: csock.close()
  160. if tsock: tsock.close()
  161. if __name__ == '__main__':
  162. ##log = open("ws.log", 'w')
  163. try:
  164. if len(sys.argv) != 4: raise
  165. listen_port = int(sys.argv[1])
  166. target_host = sys.argv[2]
  167. target_port = int(sys.argv[3])
  168. except:
  169. print "Usage: <listen_port> <target_host> <target_port>"
  170. sys.exit(1)
  171. start_server(listen_port, target_host, target_port)