wsproxy.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 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 sys, socket, ssl, optparse
  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. while True:
  33. wlist = []
  34. if tqueue: wlist.append(target)
  35. if cqueue: wlist.append(client)
  36. ins, outs, excepts = select(rlist, wlist, [], 1)
  37. if excepts: raise Exception("Socket exception")
  38. if target in outs:
  39. dat = tqueue.pop(0)
  40. sent = target.send(dat)
  41. if sent == len(dat):
  42. traffic(">")
  43. else:
  44. tqueue.insert(0, dat[sent:])
  45. traffic(".>")
  46. ##if rec: rec.write("Target send: %s\n" % map(ord, dat))
  47. if client in outs:
  48. dat = cqueue.pop(0)
  49. sent = client.send(dat)
  50. if sent == len(dat):
  51. traffic("<")
  52. ##if rec: rec.write("Client send: %s ...\n" % repr(dat[0:80]))
  53. if rec: rec.write("%s,\n" % repr(">" + dat[1:-1]))
  54. else:
  55. cqueue.insert(0, dat[sent:])
  56. traffic("<.")
  57. ##if rec: rec.write("Client send partial: %s\n" % repr(dat[0:send]))
  58. if target in ins:
  59. buf = target.recv(buffer_size)
  60. if len(buf) == 0: raise Exception("Target closed")
  61. cqueue.append(encode(buf))
  62. traffic("{")
  63. ##if rec: rec.write("Target recv (%d): %s\n" % (len(buf), map(ord, buf)))
  64. if client in ins:
  65. buf = client.recv(buffer_size)
  66. if len(buf) == 0: raise Exception("Client closed")
  67. if buf[-1] == '\xff':
  68. if buf.count('\xff') > 1:
  69. traffic(str(buf.count('\xff')))
  70. traffic("}")
  71. ##if rec: rec.write("Client recv (%d): %s\n" % (len(buf), repr(buf)))
  72. if rec: rec.write("%s,\n" % repr(buf[1:-1]))
  73. if cpartial:
  74. tqueue.extend(decode(cpartial + buf))
  75. cpartial = ""
  76. else:
  77. tqueue.extend(decode(buf))
  78. else:
  79. traffic(".}")
  80. ##if rec: rec.write("Client recv partial (%d): %s\n" % (len(buf), repr(buf)))
  81. cpartial = cpartial + buf
  82. def proxy_handler(client):
  83. global target_host, target_port, options, rec
  84. if settings['record']:
  85. print "Opening record file: %s" % settings['record']
  86. rec = open(settings['record'], 'w')
  87. print "Connecting to: %s:%s" % (target_host, target_port)
  88. tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  89. tsock.connect((target_host, target_port))
  90. print traffic_legend
  91. try:
  92. do_proxy(client, tsock)
  93. except:
  94. if tsock: tsock.close()
  95. if rec: rec.close()
  96. raise
  97. if __name__ == '__main__':
  98. usage = "%prog [--record FILE]"
  99. usage += " [source_addr:]source_port target_addr:target_port"
  100. parser = optparse.OptionParser(usage=usage)
  101. parser.add_option("--record",
  102. help="record session to a file", metavar="FILE")
  103. parser.add_option("--foreground", "-f",
  104. dest="daemon", default=True, action="store_false",
  105. help="stay in foreground, do not daemonize")
  106. parser.add_option("--ssl-only", action="store_true",
  107. help="disallow non-encrypted connections")
  108. parser.add_option("--cert", default="self.pem",
  109. help="SSL certificate")
  110. (options, args) = parser.parse_args()
  111. if len(args) > 2: parser.error("Too many arguments")
  112. if len(args) < 2: parser.error("Too few arguments")
  113. if args[0].count(':') > 0:
  114. host,port = args[0].split(':')
  115. else:
  116. host,port = '',args[0]
  117. if args[1].count(':') > 0:
  118. target_host,target_port = args[1].split(':')
  119. else:
  120. parser.error("Error parsing target")
  121. try: port = int(port)
  122. except: parser.error("Error parsing listen port")
  123. try: target_port = int(target_port)
  124. except: parser.error("Error parsing target port")
  125. settings['listen_host'] = host
  126. settings['listen_port'] = port
  127. settings['handler'] = proxy_handler
  128. settings['cert'] = os.path.abspath(options.cert)
  129. settings['ssl_only'] = options.ssl_only
  130. settings['daemon'] = options.daemon
  131. settings['record'] = os.path.abspath(options.record)
  132. start_server()