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