3 # This script demostrates how one can use pyOpenSSL to speak SSL over an HTTP
5 # The challenge here is to start talking SSL over an already connected socket
7 # Author: Mihai Ibanescu <misa@redhat.com>
9 # $Id: proxy.py,v 1.2 2004/07/22 12:01:25 martin Exp $
11 import sys, socket, string
12 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)"
21 # Command-line processing
22 if len(sys.argv) != 3:
25 server, proxy = sys.argv[1:3]
27 run(split_host(server, 443), split_host(proxy, 8080))
29 def split_host(hostname, default_port=80):
30 a = string.split(hostname, ':', 1)
32 a.append(default_port)
33 return a[0], int(a[1])
36 # Connects to the server, through the proxy
37 def run(server, proxy):
38 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41 except socket.error, e:
42 print "Unable to connect to %s:%s %s" % (proxy[0], proxy[1], str(e))
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))
49 ctx = SSL.Context(SSL.SSLv23_METHOD)
50 conn = SSL.Connection(ctx, s)
53 conn.set_connect_state()
57 conn.send("HEAD / HTTP/1.0\n\n")
58 print "Sever response:"
62 buff = conn.recv(4096)
63 except SSL.ZeroReturnError:
69 if __name__ == '__main__':