blob: 99f625747e73ed40dba8662769ad9cba86154f22 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
4"""\
5This module provides some more Pythonic support for SSL.
6
7Object types:
8
9 sslsocket -- subtype of socket.socket which does SSL over the socket
10
11Exceptions:
12
13 sslerror -- exception raised for I/O errors
14
15Functions:
16
17 cert_time_to_seconds -- convert time string used for certificate
18 notBefore and notAfter functions to integer
19 seconds past the Epoch (the time values
20 returned from time.time())
21
22 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
23 by the server running on HOST at port PORT. No
24 validation of the certificate is performed.
25
26Integer constants:
27
28SSL_ERROR_ZERO_RETURN
29SSL_ERROR_WANT_READ
30SSL_ERROR_WANT_WRITE
31SSL_ERROR_WANT_X509_LOOKUP
32SSL_ERROR_SYSCALL
33SSL_ERROR_SSL
34SSL_ERROR_WANT_CONNECT
35
36SSL_ERROR_EOF
37SSL_ERROR_INVALID_ERROR_CODE
38
39The following group define certificate requirements that one side is
40allowing/requiring from the other side:
41
42CERT_NONE - no certificates from the other side are required (or will
43 be looked at if provided)
44CERT_OPTIONAL - certificates are not required, but if provided will be
45 validated, and if validation fails, the connection will
46 also fail
47CERT_REQUIRED - certificates are required, and will be validated, and
48 if validation fails, the connection will also fail
49
50The following constants identify various SSL protocol variants:
51
52PROTOCOL_SSLv2
53PROTOCOL_SSLv3
54PROTOCOL_SSLv23
55PROTOCOL_TLSv1
56"""
57
58import os, sys
59
60import _ssl # if we can't import it, let the error propagate
61from socket import socket
62from _ssl import sslerror
63from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
64from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
65
66# Root certs:
67#
68# The "ca_certs" argument to sslsocket() expects a file containing one or more
69# certificates that are roots of various certificate signing chains. This file
70# contains the certificates in PEM format (RFC ) where each certificate is
71# encoded in base64 encoding and surrounded with a header and footer:
72# -----BEGIN CERTIFICATE-----
73# ... (CA certificate in base64 encoding) ...
74# -----END CERTIFICATE-----
75# The various certificates in the file are just concatenated together:
76# -----BEGIN CERTIFICATE-----
77# ... (CA certificate in base64 encoding) ...
78# -----END CERTIFICATE-----
79# -----BEGIN CERTIFICATE-----
80# ... (a second CA certificate in base64 encoding) ...
81# -----END CERTIFICATE-----
82#
83# Some "standard" root certificates are available at
84#
85# http://www.thawte.com/roots/ (for Thawte roots)
86# http://www.verisign.com/support/roots.html (for Verisign)
87
88class sslsocket (socket):
89
90 def __init__(self, sock, keyfile=None, certfile=None,
91 server_side=False, cert_reqs=CERT_NONE,
92 ssl_version=PROTOCOL_SSLv23, ca_certs=None):
93 socket.__init__(self, _sock=sock._sock)
94 if certfile and not keyfile:
95 keyfile = certfile
96 if server_side:
97 self._sslobj = _ssl.sslwrap(self._sock, 1, keyfile, certfile,
98 cert_reqs, ssl_version, ca_certs)
99 else:
100 # see if it's connected
101 try:
102 socket.getpeername(self)
103 except:
104 # no, no connection yet
105 self._sslobj = None
106 else:
107 # yes, create the SSL object
108 self._sslobj = _ssl.sslwrap(self._sock, 0, keyfile, certfile,
109 cert_reqs, ssl_version, ca_certs)
110 self.keyfile = keyfile
111 self.certfile = certfile
112 self.cert_reqs = cert_reqs
113 self.ssl_version = ssl_version
114 self.ca_certs = ca_certs
115
116 def read(self, len=1024):
117 return self._sslobj.read(len)
118
119 def write(self, data):
120 return self._sslobj.write(data)
121
122 def getpeercert(self):
123 return self._sslobj.peer_certificate()
124
125 def send (self, data, flags=0):
126 if flags != 0:
127 raise ValueError(
128 "non-zero flags not allowed in calls to send() on %s" %
129 self.__class__)
130 return self._sslobj.write(data)
131
132 def send_to (self, data, addr, flags=0):
133 raise ValueError("send_to not allowed on instances of %s" %
134 self.__class__)
135
136 def sendall (self, data, flags=0):
137 if flags != 0:
138 raise ValueError(
139 "non-zero flags not allowed in calls to sendall() on %s" %
140 self.__class__)
141 return self._sslobj.write(data)
142
143 def recv (self, buflen=1024, flags=0):
144 if flags != 0:
145 raise ValueError(
146 "non-zero flags not allowed in calls to sendall() on %s" %
147 self.__class__)
148 return self._sslobj.read(data, buflen)
149
150 def recv_from (self, addr, buflen=1024, flags=0):
151 raise ValueError("recv_from not allowed on instances of %s" %
152 self.__class__)
153
154 def shutdown(self):
155 if self._sslobj:
156 self._sslobj.shutdown()
157 self._sslobj = None
158 else:
159 socket.shutdown(self)
160
161 def close(self):
162 if self._sslobj:
163 self.shutdown()
164 else:
165 socket.close(self)
166
167 def connect(self, addr):
168 # Here we assume that the socket is client-side, and not
169 # connected at the time of the call. We connect it, then wrap it.
170 if self._sslobj or (self.getsockname()[1] != 0):
171 raise ValueError("attempt to connect already-connected sslsocket!")
172 socket.connect(self, addr)
173 self._sslobj = _ssl.sslwrap(self._sock, 0, self.keyfile, self.certfile,
174 self.cert_reqs, self.ssl_version,
175 self.ca_certs)
176
177 def accept(self):
178 raise ValueError("accept() not supported on an sslsocket")
179
180
181# some utility functions
182
183def cert_time_to_seconds(cert_time):
184 import time
185 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
186
187# a replacement for the old socket.ssl function
188
189def sslwrap_simple (sock, keyfile=None, certfile=None):
190
191 return _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
192 PROTOCOL_SSLv23, None)
193
194# fetch the certificate that the server is providing in PEM form
195
196def fetch_server_certificate (host, port):
197
198 import re, tempfile, os
199
200 def subproc(cmd):
201 from subprocess import Popen, PIPE, STDOUT
202 proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
203 status = proc.wait()
204 output = proc.stdout.read()
205 return status, output
206
207 def strip_to_x509_cert(certfile_contents, outfile=None):
208 m = re.search(r"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
209 r".*[\r]*^[-]+END CERTIFICATE[-]+)$",
210 certfile_contents, re.MULTILINE | re.DOTALL)
211 if not m:
212 return None
213 else:
214 tn = tempfile.mktemp()
215 fp = open(tn, "w")
216 fp.write(m.group(1) + "\n")
217 fp.close()
218 try:
219 tn2 = (outfile or tempfile.mktemp())
220 status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
221 (tn, tn2))
222 if status != 0:
223 raise OperationError(status, tsig, output)
224 fp = open(tn2, 'rb')
225 data = fp.read()
226 fp.close()
227 os.unlink(tn2)
228 return data
229 finally:
230 os.unlink(tn)
231
232 if sys.platform.startswith("win"):
233 tfile = tempfile.mktemp()
234 fp = open(tfile, "w")
235 fp.write("quit\n")
236 fp.close()
237 try:
238 status, output = subproc(
239 'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
240 (host, port, tfile))
241 finally:
242 os.unlink(tfile)
243 else:
244 status, output = subproc(
245 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
246 (host, port))
247 if status != 0:
248 raise OSError(status)
249 certtext = strip_to_x509_cert(output)
250 if not certtext:
251 raise ValueError("Invalid response received from server at %s:%s" %
252 (host, port))
253 return certtext