proxy.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. #
  3. # This script demonstrates 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
  11. import socket
  12. import string
  13. from OpenSSL import SSL
  14. def usage(exit_code=0):
  15. print "Usage: %s server[:port] proxy[:port]" % sys.argv[0]
  16. print " Connects SSL to the specified server (port 443 by default)"
  17. print " using the specified proxy (port 8080 by default)"
  18. sys.exit(exit_code)
  19. def main():
  20. # Command-line processing
  21. if len(sys.argv) != 3:
  22. usage(-1)
  23. server, proxy = sys.argv[1:3]
  24. run(split_host(server, 443), split_host(proxy, 8080))
  25. def split_host(hostname, default_port=80):
  26. a = string.split(hostname, ':', 1)
  27. if len(a) == 1:
  28. a.append(default_port)
  29. return a[0], int(a[1])
  30. # Connects to the server, through the proxy
  31. def run(server, proxy):
  32. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  33. try:
  34. s.connect(proxy)
  35. except socket.error, e:
  36. print "Unable to connect to %s:%s %s" % (proxy[0], proxy[1], str(e))
  37. sys.exit(-1)
  38. # Use the CONNECT method to get a connection to the actual server
  39. s.send("CONNECT %s:%s HTTP/1.0\n\n" % (server[0], server[1]))
  40. print "Proxy response: %s" % string.strip(s.recv(1024))
  41. ctx = SSL.Context(SSL.SSLv23_METHOD)
  42. conn = SSL.Connection(ctx, s)
  43. # Go to client mode
  44. conn.set_connect_state()
  45. # start using HTTP
  46. conn.send("HEAD / HTTP/1.0\n\n")
  47. print "Sever response:"
  48. print "-" * 40
  49. while 1:
  50. try:
  51. buff = conn.recv(4096)
  52. except SSL.ZeroReturnError:
  53. # we're done
  54. break
  55. print buff,
  56. if __name__ == '__main__':
  57. main()