Debian Codegraph @

doc/source/ssl.rst

raw
1 Using SSL With Eventlet
2 ========================
3
4 Eventlet makes it easy to use non-blocking SSL sockets. If you're using Python 3.7 or later, you're all set, eventlet wraps the built-in ssl module.
5
6 In either case, the ``green`` modules handle SSL sockets transparently, just like their standard counterparts. As an example, :mod:`eventlet.green.urllib2` can be used to fetch https urls in as non-blocking a fashion as you please::
7
8 from eventlet.green.urllib.request import urlopen
9 from eventlet import spawn
10 bodies = [spawn(urlopen, url)
11 for url in ("https://secondlife.com","https://google.com")]
12 for b in bodies:
13 print(b.wait().read())
14
15
16 PyOpenSSL
17 ----------
18
19 :mod:`eventlet.green.OpenSSL` has exactly the same interface as pyOpenSSL_ `(docs) <http://pyopenssl.sourceforge.net/pyOpenSSL.html/>`_, and works in all versions of Python. This module is much more powerful than :func:`socket.ssl`, and may have some advantages over :mod:`ssl`, depending on your needs.
20
21 For testing purpose first create self-signed certificate using following commands ::
22
23 $ openssl genrsa 1024 > server.key
24 $ openssl req -new -x509 -nodes -sha1 -days 365 -key server.key > server.cert
25
26 Keep these Private key and Self-signed certificate in same directory as `server.py` and `client.py` for simplicity sake.
27
28 Here's an example of a server (`server.py`) ::
29
30 from eventlet.green import socket
31 from eventlet.green.OpenSSL import SSL
32
33 # insecure context, only for example purposes
34 context = SSL.Context(SSL.SSLv23_METHOD)
35 # Pass server's private key created
36 context.use_privatekey_file('server.key')
37 # Pass self-signed certificate created
38 context.use_certificate_file('server.cert')
39
40 # create underlying green socket and wrap it in ssl
41 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
42 connection = SSL.Connection(context, sock)
43
44 # configure as server
45 connection.set_accept_state()
46 connection.bind(('127.0.0.1', 8443))
47 connection.listen(50)
48
49 # accept one client connection then close up shop
50 client_conn, addr = connection.accept()
51 print(client_conn.read(100))
52 client_conn.shutdown()
53 client_conn.close()
54 connection.close()
55
56 Here's an example of a client (`client.py`) ::
57
58 import socket
59 # Create socket
60 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
61 # Connect to server
62 s.connect(('127.0.0.1', 8443))
63 sslSocket = socket.ssl(s)
64 print repr(sslSocket.server())
65 print repr(sslSocket.issuer())
66 sslSocket.write('Hello secure socket\n')
67 # Close client
68 s.close()
69
70 Running example::
71
72 In first terminal
73
74 $ python server.py
75
76 In another terminal
77
78 $ python client.py
79
80 .. _pyOpenSSL: https://launchpad.net/pyopenssl