Jean-Paul Calderone | 897bc25 | 2008-02-18 20:50:23 -0500 | [diff] [blame^] | 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 | |
| 11 | import sys, socket, string |
| 12 | from OpenSSL import SSL |
| 13 | |
| 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 | |
| 20 | def main(): |
| 21 | # Command-line processing |
| 22 | if len(sys.argv) != 3: |
| 23 | usage(-1) |
| 24 | |
| 25 | server, proxy = sys.argv[1:3] |
| 26 | |
| 27 | run(split_host(server, 443), split_host(proxy, 8080)) |
| 28 | |
| 29 | def split_host(hostname, default_port=80): |
| 30 | a = string.split(hostname, ':', 1) |
| 31 | if len(a) == 1: |
| 32 | a.append(default_port) |
| 33 | return a[0], int(a[1]) |
| 34 | |
| 35 | |
| 36 | # Connects to the server, through the proxy |
| 37 | def run(server, proxy): |
| 38 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 39 | try: |
| 40 | s.connect(proxy) |
| 41 | except socket.error, e: |
| 42 | print "Unable to connect to %s:%s %s" % (proxy[0], proxy[1], str(e)) |
| 43 | sys.exit(-1) |
| 44 | |
| 45 | # Use the CONNECT method to get a connection to the actual server |
| 46 | s.send("CONNECT %s:%s HTTP/1.0\n\n" % (server[0], server[1])) |
| 47 | print "Proxy response: %s" % string.strip(s.recv(1024)) |
| 48 | |
| 49 | ctx = SSL.Context(SSL.SSLv23_METHOD) |
| 50 | conn = SSL.Connection(ctx, s) |
| 51 | |
| 52 | # Go to client mode |
| 53 | conn.set_connect_state() |
| 54 | |
| 55 | # start using HTTP |
| 56 | |
| 57 | conn.send("HEAD / HTTP/1.0\n\n") |
| 58 | print "Sever response:" |
| 59 | print "-" * 40 |
| 60 | while 1: |
| 61 | try: |
| 62 | buff = conn.recv(4096) |
| 63 | except SSL.ZeroReturnError: |
| 64 | # we're done |
| 65 | break |
| 66 | |
| 67 | print buff, |
| 68 | |
| 69 | if __name__ == '__main__': |
| 70 | main() |