proxy.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. #
  3. # This script demostrates how one can use pyOpenSSL to speak SSL over an HTTP
  4. # proxy
  5. # The challenge here is to start talking SSL over an already connected socket
  6. #
  7. # Author: Mihai Ibanescu <misa@redhat.com>
  8. #
  9. # $Id: proxy.py,v 1.2 2004/07/22 12:01:25 martin Exp $
  10. import sys, socket, string
  11. from OpenSSL import SSL
  12. def usage(exit_code=0):
  13. print "Usage: %s server[:port] proxy[:port]" % sys.argv[0]
  14. print " Connects SSL to the specified server (port 443 by default)"
  15. print " using the specified proxy (port 8080 by default)"
  16. sys.exit(exit_code)
  17. def main():
  18. # Command-line processing
  19. if len(sys.argv) != 3:
  20. usage(-1)
  21. server, proxy = sys.argv[1:3]
  22. run(split_host(server, 443), split_host(proxy, 8080))
  23. def split_host(hostname, default_port=80):
  24. a = string.split(hostname, ':', 1)
  25. if len(a) == 1:
  26. a.append(default_port)
  27. return a[0], int(a[1])
  28. # Connects to the server, through the proxy
  29. def run(server, proxy):
  30. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  31. try:
  32. s.connect(proxy)
  33. except socket.error, e:
  34. print "Unable to connect to %s:%s %s" % (proxy[0], proxy[1], str(e))
  35. sys.exit(-1)
  36. # Use the CONNECT method to get a connection to the actual server
  37. s.send("CONNECT %s:%s HTTP/1.0\n\n" % (server[0], server[1]))
  38. print "Proxy response: %s" % string.strip(s.recv(1024))
  39. ctx = SSL.Context(SSL.SSLv23_METHOD)
  40. conn = SSL.Connection(ctx, s)
  41. # Go to client mode
  42. conn.set_connect_state()
  43. # start using HTTP
  44. conn.send("HEAD / HTTP/1.0\n\n")
  45. print "Sever response:"
  46. print "-" * 40
  47. while 1:
  48. try:
  49. buff = conn.recv(4096)
  50. except SSL.ZeroReturnError:
  51. # we're done
  52. break
  53. print buff,
  54. if __name__ == '__main__':
  55. main()