blob: ae8aaefb4b6d695c32c2096990a548cc497c099e [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
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
15
16 cert_time_to_seconds -- convert time string used for certificate
17 notBefore and notAfter functions to integer
18 seconds past the Epoch (the time values
19 returned from time.time())
20
21 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22 by the server running on HOST at port PORT. No
23 validation of the certificate is performed.
24
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
54PROTOCOL_TLSv1
55"""
56
Christian Heimes05e8be12008-02-23 18:30:17 +000057import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000058import re
Thomas Woutersed03b412007-08-28 21:37:11 +000059
60import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061
Antoine Pitrou04f6a322010-04-05 21:40:07 +000062from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou152efa22010-05-16 18:19:27 +000063from _ssl import _SSLContext, SSLError
Thomas Woutersed03b412007-08-28 21:37:11 +000064from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Guido van Rossum5b8b1552007-11-16 00:06:11 +000065from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23,
66 PROTOCOL_TLSv1)
Antoine Pitroub5218772010-05-21 09:56:06 +000067from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000068from _ssl import RAND_status, RAND_egd, RAND_add
Guido van Rossum5b8b1552007-11-16 00:06:11 +000069from _ssl import (
70 SSL_ERROR_ZERO_RETURN,
71 SSL_ERROR_WANT_READ,
72 SSL_ERROR_WANT_WRITE,
73 SSL_ERROR_WANT_X509_LOOKUP,
74 SSL_ERROR_SYSCALL,
75 SSL_ERROR_SSL,
76 SSL_ERROR_WANT_CONNECT,
77 SSL_ERROR_EOF,
78 SSL_ERROR_INVALID_ERROR_CODE,
79 )
Thomas Woutersed03b412007-08-28 21:37:11 +000080
Thomas Wouters47b49bf2007-08-30 22:15:33 +000081from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000082from socket import error as socket_error
Bill Janssen40a0f662008-08-12 16:56:25 +000083from socket import socket, AF_INET, SOCK_STREAM
Thomas Wouters1b7f8912007-09-19 03:06:30 +000084import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000085import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +000086import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +000087
Thomas Woutersed03b412007-08-28 21:37:11 +000088
Antoine Pitrou59fdd672010-10-08 10:37:08 +000089class CertificateError(ValueError):
90 pass
91
92
93def _dnsname_to_pat(dn):
94 pats = []
95 for frag in dn.split(r'.'):
96 if frag == '*':
97 # When '*' is a fragment by itself, it matches a non-empty dotless
98 # fragment.
99 pats.append('[^.]+')
100 else:
101 # Otherwise, '*' matches any dotless fragment.
102 frag = re.escape(frag)
103 pats.append(frag.replace(r'\*', '[^.]*'))
104 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
105
106
107def match_hostname(cert, hostname):
108 """Verify that *cert* (in decoded format as returned by
109 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
110 are mostly followed, but IP addresses are not accepted for *hostname*.
111
112 CertificateError is raised on failure. On success, the function
113 returns nothing.
114 """
115 if not cert:
116 raise ValueError("empty or no certificate")
117 dnsnames = []
118 san = cert.get('subjectAltName', ())
119 for key, value in san:
120 if key == 'DNS':
121 if _dnsname_to_pat(value).match(hostname):
122 return
123 dnsnames.append(value)
124 if not san:
125 # The subject is only checked when subjectAltName is empty
126 for sub in cert.get('subject', ()):
127 for key, value in sub:
128 # XXX according to RFC 2818, the most specific Common Name
129 # must be used.
130 if key == 'commonName':
131 if _dnsname_to_pat(value).match(hostname):
132 return
133 dnsnames.append(value)
134 if len(dnsnames) > 1:
135 raise CertificateError("hostname %r "
136 "doesn't match either of %s"
137 % (hostname, ', '.join(map(repr, dnsnames))))
138 elif len(dnsnames) == 1:
139 raise CertificateError("hostname %r "
140 "doesn't match %r"
141 % (hostname, dnsnames[0]))
142 else:
143 raise CertificateError("no appropriate commonName or "
144 "subjectAltName fields were found")
145
146
Antoine Pitrou152efa22010-05-16 18:19:27 +0000147class SSLContext(_SSLContext):
148 """An SSLContext holds various SSL-related configuration options and
149 data, such as certificates and possibly a private key."""
150
151 __slots__ = ('protocol',)
152
153 def __new__(cls, protocol, *args, **kwargs):
154 return _SSLContext.__new__(cls, protocol)
155
156 def __init__(self, protocol):
157 self.protocol = protocol
158
159 def wrap_socket(self, sock, server_side=False,
160 do_handshake_on_connect=True,
161 suppress_ragged_eofs=True):
162 return SSLSocket(sock=sock, server_side=server_side,
163 do_handshake_on_connect=do_handshake_on_connect,
164 suppress_ragged_eofs=suppress_ragged_eofs,
165 _context=self)
166
167
168class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000169 """This class implements a subtype of socket.socket that wraps
170 the underlying OS socket in an SSL context when necessary, and
171 provides read and write methods over that channel."""
172
Bill Janssen6e027db2007-11-15 22:23:56 +0000173 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000174 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000175 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
176 do_handshake_on_connect=True,
177 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000178 suppress_ragged_eofs=True, ciphers=None,
179 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000180
Antoine Pitrou152efa22010-05-16 18:19:27 +0000181 if _context:
182 self.context = _context
183 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000184 if server_side and not certfile:
185 raise ValueError("certfile must be specified for server-side "
186 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000187 if keyfile and not certfile:
188 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189 if certfile and not keyfile:
190 keyfile = certfile
191 self.context = SSLContext(ssl_version)
192 self.context.verify_mode = cert_reqs
193 if ca_certs:
194 self.context.load_verify_locations(ca_certs)
195 if certfile:
196 self.context.load_cert_chain(certfile, keyfile)
197 if ciphers:
198 self.context.set_ciphers(ciphers)
199 self.keyfile = keyfile
200 self.certfile = certfile
201 self.cert_reqs = cert_reqs
202 self.ssl_version = ssl_version
203 self.ca_certs = ca_certs
204 self.ciphers = ciphers
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000205 self.server_side = server_side
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 self.do_handshake_on_connect = do_handshake_on_connect
207 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000208 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000209 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000210 socket.__init__(self,
211 family=sock.family,
212 type=sock.type,
213 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000214 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000215 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000216 # see if it's connected
217 try:
218 sock.getpeername()
219 except socket_error as e:
220 if e.errno != errno.ENOTCONN:
221 raise
222 else:
223 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000224 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000225 elif fileno is not None:
226 socket.__init__(self, fileno=fileno)
227 else:
228 socket.__init__(self, family=family, type=type, proto=proto)
229
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000230 self._closed = False
231 self._sslobj = None
232 if connected:
233 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000234 try:
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235 self._sslobj = self.context._wrap_socket(self, server_side)
Bill Janssen6e027db2007-11-15 22:23:56 +0000236 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000237 timeout = self.gettimeout()
238 if timeout == 0.0:
239 # non-blocking
240 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000241 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000242
Bill Janssen6e027db2007-11-15 22:23:56 +0000243 except socket_error as x:
244 self.close()
245 raise x
246
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000247 def dup(self):
248 raise NotImplemented("Can't dup() %s instances" %
249 self.__class__.__name__)
250
Bill Janssen6e027db2007-11-15 22:23:56 +0000251 def _checkClosed(self, msg=None):
252 # raise an exception here if you wish to check for spurious closes
253 pass
254
Bill Janssen54cc54c2007-12-14 22:08:56 +0000255 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000256 """Read up to LEN bytes and return them.
257 Return zero-length string on EOF."""
258
Bill Janssen6e027db2007-11-15 22:23:56 +0000259 self._checkClosed()
260 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000261 if buffer is not None:
262 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000263 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000264 v = self._sslobj.read(len or 1024)
265 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000266 except SSLError as x:
267 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000268 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000269 return 0
270 else:
271 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000272 else:
273 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000274
275 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000276 """Write DATA to the underlying SSL channel. Returns
277 number of bytes of DATA actually transmitted."""
278
Bill Janssen6e027db2007-11-15 22:23:56 +0000279 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000280 return self._sslobj.write(data)
281
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000283 """Returns a formatted version of the data in the
284 certificate provided by the other end of the SSL channel.
285 Return None if no certificate was provided, {} if a
286 certificate was provided, but not validated."""
287
Bill Janssen6e027db2007-11-15 22:23:56 +0000288 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000289 return self._sslobj.peer_certificate(binary_form)
290
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000291 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000292 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000293 if not self._sslobj:
294 return None
295 else:
296 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000297
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000298 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000299 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000300 if self._sslobj:
301 if flags != 0:
302 raise ValueError(
303 "non-zero flags not allowed in calls to send() on %s" %
304 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000305 while True:
306 try:
307 v = self._sslobj.write(data)
308 except SSLError as x:
309 if x.args[0] == SSL_ERROR_WANT_READ:
310 return 0
311 elif x.args[0] == SSL_ERROR_WANT_WRITE:
312 return 0
313 else:
314 raise
315 else:
316 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000317 else:
318 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000319
Antoine Pitroua468adc2010-09-14 14:43:44 +0000320 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000321 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000322 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000323 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000324 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000325 elif addr is None:
326 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000327 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000328 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000329
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000330 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000331 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000332 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000333 if flags != 0:
334 raise ValueError(
335 "non-zero flags not allowed in calls to sendall() on %s" %
336 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 amount = len(data)
338 count = 0
339 while (count < amount):
340 v = self.send(data[count:])
341 count += v
342 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000343 else:
344 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000345
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000346 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000347 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 if self._sslobj:
349 if flags != 0:
350 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000351 "non-zero flags not allowed in calls to recv() on %s" %
352 self.__class__)
353 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000354 else:
355 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000356
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000357 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 self._checkClosed()
359 if buffer and (nbytes is None):
360 nbytes = len(buffer)
361 elif nbytes is None:
362 nbytes = 1024
363 if self._sslobj:
364 if flags != 0:
365 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000366 "non-zero flags not allowed in calls to recv_into() on %s" %
367 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000368 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 else:
370 return socket.recv_into(self, buffer, nbytes, flags)
371
Antoine Pitroua468adc2010-09-14 14:43:44 +0000372 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000373 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000374 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000375 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376 self.__class__)
377 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000378 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
Bill Janssen58afe4c2008-09-08 16:45:19 +0000380 def recvfrom_into(self, buffer, nbytes=None, flags=0):
381 self._checkClosed()
382 if self._sslobj:
383 raise ValueError("recvfrom_into not allowed on instances of %s" %
384 self.__class__)
385 else:
386 return socket.recvfrom_into(self, buffer, nbytes, flags)
387
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000388 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 self._checkClosed()
390 if self._sslobj:
391 return self._sslobj.pending()
392 else:
393 return 0
394
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000395 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000396 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000397 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000398 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000399
Ezio Melottidc55e672010-01-18 09:15:14 +0000400 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000401 if self._sslobj:
402 s = self._sslobj.shutdown()
403 self._sslobj = None
404 return s
405 else:
406 raise ValueError("No SSL wrapper around " + str(self))
407
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000408 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000410 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000411 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000412
Bill Janssen48dc27c2007-12-05 03:38:10 +0000413 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000414 """Perform a TLS/SSL handshake."""
415
Bill Janssen48dc27c2007-12-05 03:38:10 +0000416 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000417 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000418 if timeout == 0.0 and block:
419 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000420 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000421 finally:
422 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000423
424 def connect(self, addr):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000425 """Connects to remote ADDR, and then wraps the connection in
426 an SSL channel."""
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000427 if self.server_side:
428 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000429 # Here we assume that the socket is client-side, and not
430 # connected at the time of the call. We connect it, then wrap it.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000431 if self._sslobj:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432 raise ValueError("attempt to connect already-connected SSLSocket!")
Thomas Woutersed03b412007-08-28 21:37:11 +0000433 socket.connect(self, addr)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000434 self._sslobj = self.context._wrap_socket(self, False)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000435 try:
436 if self.do_handshake_on_connect:
437 self.do_handshake()
438 except:
439 self._sslobj = None
440 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000441
442 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000443 """Accepts a new connection from a remote client, and returns
444 a tuple containing that new connection wrapped with a server-side
445 SSL channel, and the address of the remote client."""
446
447 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000448 return (SSLSocket(sock=newsock,
449 keyfile=self.keyfile, certfile=self.certfile,
450 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000451 cert_reqs=self.cert_reqs,
452 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000453 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000454 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000455 do_handshake_on_connect=
456 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000457 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Guido van Rossume6650f92007-12-06 19:05:55 +0000459 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000460 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000461 self._real_close()
462
Bill Janssen54cc54c2007-12-14 22:08:56 +0000463
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464def wrap_socket(sock, keyfile=None, certfile=None,
465 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000466 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000467 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000468 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000469
Bill Janssen6e027db2007-11-15 22:23:56 +0000470 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000472 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000473 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000474 suppress_ragged_eofs=suppress_ragged_eofs,
475 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476
Thomas Woutersed03b412007-08-28 21:37:11 +0000477# some utility functions
478
479def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000480 """Takes a date-time string in standard ASN1_print form
481 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
482 a Python time value in seconds past the epoch."""
483
Thomas Woutersed03b412007-08-28 21:37:11 +0000484 import time
485 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
486
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487PEM_HEADER = "-----BEGIN CERTIFICATE-----"
488PEM_FOOTER = "-----END CERTIFICATE-----"
489
490def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491 """Takes a certificate in binary DER format and returns the
492 PEM version of it as a string."""
493
Bill Janssen6e027db2007-11-15 22:23:56 +0000494 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
495 return (PEM_HEADER + '\n' +
496 textwrap.fill(f, 64) + '\n' +
497 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498
499def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500 """Takes a certificate in ASCII PEM format and returns the
501 DER-encoded version of it as a byte sequence"""
502
503 if not pem_cert_string.startswith(PEM_HEADER):
504 raise ValueError("Invalid PEM encoding; must start with %s"
505 % PEM_HEADER)
506 if not pem_cert_string.strip().endswith(PEM_FOOTER):
507 raise ValueError("Invalid PEM encoding; must end with %s"
508 % PEM_FOOTER)
509 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000510 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000511
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000512def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513 """Retrieve the certificate from the server at the specified address,
514 and return it as a PEM-encoded string.
515 If 'ca_certs' is specified, validate the server cert against it.
516 If 'ssl_version' is specified, use it in the connection attempt."""
517
518 host, port = addr
519 if (ca_certs is not None):
520 cert_reqs = CERT_REQUIRED
521 else:
522 cert_reqs = CERT_NONE
523 s = wrap_socket(socket(), ssl_version=ssl_version,
524 cert_reqs=cert_reqs, ca_certs=ca_certs)
525 s.connect(addr)
526 dercert = s.getpeercert(True)
527 s.close()
528 return DER_cert_to_PEM_cert(dercert)
529
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000530def get_protocol_name(protocol_code):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531 if protocol_code == PROTOCOL_TLSv1:
532 return "TLSv1"
533 elif protocol_code == PROTOCOL_SSLv23:
534 return "SSLv23"
535 elif protocol_code == PROTOCOL_SSLv2:
536 return "SSLv2"
537 elif protocol_code == PROTOCOL_SSLv3:
538 return "SSLv3"
539 else:
540 return "<unknown>"