wsproxy.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!/usr/bin/python
  2. '''
  3. A WebSocket to TCP socket proxy with support for "wss://" encryption.
  4. Copyright 2010 Joel Martin
  5. Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
  6. You can make a cert/key with openssl using:
  7. openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
  8. as taken from http://docs.python.org/dev/library/ssl.html#certificates
  9. '''
  10. import socket, optparse, time
  11. from select import select
  12. from websocket import *
  13. buffer_size = 65536
  14. rec = None
  15. traffic_legend = """
  16. Traffic Legend:
  17. } - Client receive
  18. }. - Client receive partial
  19. { - Target receive
  20. > - Target send
  21. >. - Target send partial
  22. < - Client send
  23. <. - Client send partial
  24. """
  25. def do_proxy(client, target):
  26. """ Proxy WebSocket to normal socket. """
  27. global rec
  28. cqueue = []
  29. cpartial = ""
  30. tqueue = []
  31. rlist = [client, target]
  32. tstart = int(time.time()*1000)
  33. while True:
  34. wlist = []
  35. tdelta = int(time.time()*1000) - tstart
  36. if tqueue: wlist.append(target)
  37. if cqueue: wlist.append(client)
  38. ins, outs, excepts = select(rlist, wlist, [], 1)
  39. if excepts: raise Exception("Socket exception")
  40. if target in outs:
  41. dat = tqueue.pop(0)
  42. sent = target.send(dat)
  43. if sent == len(dat):
  44. traffic(">")
  45. else:
  46. tqueue.insert(0, dat[sent:])
  47. traffic(".>")
  48. ##if rec: rec.write("Target send: %s\n" % map(ord, dat))
  49. if client in outs:
  50. dat = cqueue.pop(0)
  51. sent = client.send(dat)
  52. if sent == len(dat):
  53. traffic("<")
  54. ##if rec: rec.write("Client send: %s ...\n" % repr(dat[0:80]))
  55. if rec: rec.write("%s,\n" % repr("{%s{" % tdelta + dat[1:-1]))
  56. else:
  57. cqueue.insert(0, dat[sent:])
  58. traffic("<.")
  59. ##if rec: rec.write("Client send partial: %s\n" % repr(dat[0:send]))
  60. if target in ins:
  61. buf = target.recv(buffer_size)
  62. if len(buf) == 0: raise EClose("Target closed")
  63. cqueue.append(encode(buf))
  64. traffic("{")
  65. ##if rec: rec.write("Target recv (%d): %s\n" % (len(buf), map(ord, buf)))
  66. if client in ins:
  67. buf = client.recv(buffer_size)
  68. if len(buf) == 0: raise EClose("Client closed")
  69. if buf == '\xff\x00':
  70. raise EClose("Client sent orderly close frame")
  71. elif buf[-1] == '\xff':
  72. if buf.count('\xff') > 1:
  73. traffic(str(buf.count('\xff')))
  74. traffic("}")
  75. ##if rec: rec.write("Client recv (%d): %s\n" % (len(buf), repr(buf)))
  76. if rec: rec.write("%s,\n" % (repr("}%s}" % tdelta + buf[1:-1])))
  77. if cpartial:
  78. tqueue.extend(decode(cpartial + buf))
  79. cpartial = ""
  80. else:
  81. tqueue.extend(decode(buf))
  82. else:
  83. traffic(".}")
  84. ##if rec: rec.write("Client recv partial (%d): %s\n" % (len(buf), repr(buf)))
  85. cpartial = cpartial + buf
  86. def proxy_handler(client):
  87. global target_host, target_port, options, rec
  88. if settings['record']:
  89. handler_msg("opening record file: %s" % settings['record'])
  90. rec = open(settings['record'], 'w+')
  91. rec.write("var VNC_frame_data = [\n")
  92. handler_msg("connecting to: %s:%s" % (target_host, target_port))
  93. tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  94. tsock.connect((target_host, target_port))
  95. if settings['verbose'] and not settings['daemon']:
  96. print traffic_legend
  97. try:
  98. do_proxy(client, tsock)
  99. except:
  100. if tsock: tsock.close()
  101. if rec:
  102. rec.write("'EOF']\n")
  103. rec.close()
  104. raise
  105. if __name__ == '__main__':
  106. usage = "%prog [--record FILE]"
  107. usage += " [source_addr:]source_port target_addr:target_port"
  108. parser = optparse.OptionParser(usage=usage)
  109. parser.add_option("--verbose", "-v", action="store_true",
  110. help="verbose messages and per frame traffic")
  111. parser.add_option("--record",
  112. help="record session to a file", metavar="FILE")
  113. parser.add_option("--foreground", "-f",
  114. dest="daemon", default=True, action="store_false",
  115. help="stay in foreground, do not daemonize")
  116. parser.add_option("--ssl-only", action="store_true",
  117. help="disallow non-encrypted connections")
  118. parser.add_option("--cert", default="self.pem",
  119. help="SSL certificate")
  120. (options, args) = parser.parse_args()
  121. if len(args) > 2: parser.error("Too many arguments")
  122. if len(args) < 2: parser.error("Too few arguments")
  123. if args[0].count(':') > 0:
  124. host,port = args[0].split(':')
  125. else:
  126. host,port = '',args[0]
  127. if args[1].count(':') > 0:
  128. target_host,target_port = args[1].split(':')
  129. else:
  130. parser.error("Error parsing target")
  131. try: port = int(port)
  132. except: parser.error("Error parsing listen port")
  133. try: target_port = int(target_port)
  134. except: parser.error("Error parsing target port")
  135. if options.ssl_only and not os.path.exists(options.cert):
  136. parser.error("SSL only and %s not found" % options.cert)
  137. settings['verbose'] = options.verbose
  138. settings['listen_host'] = host
  139. settings['listen_port'] = port
  140. settings['handler'] = proxy_handler
  141. settings['cert'] = os.path.abspath(options.cert)
  142. settings['ssl_only'] = options.ssl_only
  143. settings['daemon'] = options.daemon
  144. if options.record:
  145. settings['record'] = os.path.abspath(options.record)
  146. start_server()