blob: cde99fc0831a4a69c23a6c89afa9ccf643d2371e [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
Antoine Pitroub5218772010-05-21 09:56:06 +000065from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1
Victor Stinner99c8b162011-05-24 12:05:19 +020066from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Guido van Rossum5b8b1552007-11-16 00:06:11 +000067from _ssl import (
68 SSL_ERROR_ZERO_RETURN,
69 SSL_ERROR_WANT_READ,
70 SSL_ERROR_WANT_WRITE,
71 SSL_ERROR_WANT_X509_LOOKUP,
72 SSL_ERROR_SYSCALL,
73 SSL_ERROR_SSL,
74 SSL_ERROR_WANT_CONNECT,
75 SSL_ERROR_EOF,
76 SSL_ERROR_INVALID_ERROR_CODE,
77 )
Antoine Pitroud5323212010-10-22 18:19:07 +000078from _ssl import HAS_SNI
Victor Stinner3de49192011-05-09 00:42:58 +020079from _ssl import (PROTOCOL_SSLv3, PROTOCOL_SSLv23,
80 PROTOCOL_TLSv1)
Antoine Pitroub9ac25d2011-07-08 18:47:06 +020081from _ssl import _OPENSSL_API_VERSION
82
Victor Stinner3de49192011-05-09 00:42:58 +020083_PROTOCOL_NAMES = {
84 PROTOCOL_TLSv1: "TLSv1",
85 PROTOCOL_SSLv23: "SSLv23",
86 PROTOCOL_SSLv3: "SSLv3",
87}
88try:
89 from _ssl import PROTOCOL_SSLv2
90except ImportError:
91 pass
92else:
93 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +000094
Thomas Wouters47b49bf2007-08-30 22:15:33 +000095from socket import getnameinfo as _getnameinfo
Bill Janssen6e027db2007-11-15 22:23:56 +000096from socket import error as socket_error
Antoine Pitrou15399c32011-04-28 19:23:55 +020097from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +000099import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000100import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000101
Thomas Woutersed03b412007-08-28 21:37:11 +0000102
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000103class CertificateError(ValueError):
104 pass
105
106
107def _dnsname_to_pat(dn):
108 pats = []
109 for frag in dn.split(r'.'):
110 if frag == '*':
111 # When '*' is a fragment by itself, it matches a non-empty dotless
112 # fragment.
113 pats.append('[^.]+')
114 else:
115 # Otherwise, '*' matches any dotless fragment.
116 frag = re.escape(frag)
117 pats.append(frag.replace(r'\*', '[^.]*'))
118 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
119
120
121def match_hostname(cert, hostname):
122 """Verify that *cert* (in decoded format as returned by
123 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
124 are mostly followed, but IP addresses are not accepted for *hostname*.
125
126 CertificateError is raised on failure. On success, the function
127 returns nothing.
128 """
129 if not cert:
130 raise ValueError("empty or no certificate")
131 dnsnames = []
132 san = cert.get('subjectAltName', ())
133 for key, value in san:
134 if key == 'DNS':
135 if _dnsname_to_pat(value).match(hostname):
136 return
137 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200138 if not dnsnames:
139 # The subject is only checked when there is no dNSName entry
140 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000141 for sub in cert.get('subject', ()):
142 for key, value in sub:
143 # XXX according to RFC 2818, the most specific Common Name
144 # must be used.
145 if key == 'commonName':
146 if _dnsname_to_pat(value).match(hostname):
147 return
148 dnsnames.append(value)
149 if len(dnsnames) > 1:
150 raise CertificateError("hostname %r "
151 "doesn't match either of %s"
152 % (hostname, ', '.join(map(repr, dnsnames))))
153 elif len(dnsnames) == 1:
154 raise CertificateError("hostname %r "
155 "doesn't match %r"
156 % (hostname, dnsnames[0]))
157 else:
158 raise CertificateError("no appropriate commonName or "
159 "subjectAltName fields were found")
160
161
Antoine Pitrou152efa22010-05-16 18:19:27 +0000162class SSLContext(_SSLContext):
163 """An SSLContext holds various SSL-related configuration options and
164 data, such as certificates and possibly a private key."""
165
166 __slots__ = ('protocol',)
167
168 def __new__(cls, protocol, *args, **kwargs):
169 return _SSLContext.__new__(cls, protocol)
170
171 def __init__(self, protocol):
172 self.protocol = protocol
173
174 def wrap_socket(self, sock, server_side=False,
175 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000176 suppress_ragged_eofs=True,
177 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000178 return SSLSocket(sock=sock, server_side=server_side,
179 do_handshake_on_connect=do_handshake_on_connect,
180 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000181 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000182 _context=self)
183
184
185class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000186 """This class implements a subtype of socket.socket that wraps
187 the underlying OS socket in an SSL context when necessary, and
188 provides read and write methods over that channel."""
189
Bill Janssen6e027db2007-11-15 22:23:56 +0000190 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000191 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000192 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
193 do_handshake_on_connect=True,
194 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000195 suppress_ragged_eofs=True, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000196 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000198
Antoine Pitrou152efa22010-05-16 18:19:27 +0000199 if _context:
200 self.context = _context
201 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000202 if server_side and not certfile:
203 raise ValueError("certfile must be specified for server-side "
204 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000205 if keyfile and not certfile:
206 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207 if certfile and not keyfile:
208 keyfile = certfile
209 self.context = SSLContext(ssl_version)
210 self.context.verify_mode = cert_reqs
211 if ca_certs:
212 self.context.load_verify_locations(ca_certs)
213 if certfile:
214 self.context.load_cert_chain(certfile, keyfile)
215 if ciphers:
216 self.context.set_ciphers(ciphers)
217 self.keyfile = keyfile
218 self.certfile = certfile
219 self.cert_reqs = cert_reqs
220 self.ssl_version = ssl_version
221 self.ca_certs = ca_certs
222 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000223 if server_side and server_hostname:
224 raise ValueError("server_hostname can only be specified "
225 "in client mode")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000226 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000227 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228 self.do_handshake_on_connect = do_handshake_on_connect
229 self.suppress_ragged_eofs = suppress_ragged_eofs
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000230 connected = False
Bill Janssen6e027db2007-11-15 22:23:56 +0000231 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000232 socket.__init__(self,
233 family=sock.family,
234 type=sock.type,
235 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000236 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000237 self.settimeout(sock.gettimeout())
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000238 # see if it's connected
239 try:
240 sock.getpeername()
241 except socket_error as e:
242 if e.errno != errno.ENOTCONN:
243 raise
244 else:
245 connected = True
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000246 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000247 elif fileno is not None:
248 socket.__init__(self, fileno=fileno)
249 else:
250 socket.__init__(self, family=family, type=type, proto=proto)
251
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000252 self._closed = False
253 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000254 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000255 if connected:
256 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000257 try:
Antoine Pitroud5323212010-10-22 18:19:07 +0000258 self._sslobj = self.context._wrap_socket(self, server_side,
259 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000260 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000261 timeout = self.gettimeout()
262 if timeout == 0.0:
263 # non-blocking
264 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000265 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000266
Bill Janssen6e027db2007-11-15 22:23:56 +0000267 except socket_error as x:
268 self.close()
269 raise x
270
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000271 def dup(self):
272 raise NotImplemented("Can't dup() %s instances" %
273 self.__class__.__name__)
274
Bill Janssen6e027db2007-11-15 22:23:56 +0000275 def _checkClosed(self, msg=None):
276 # raise an exception here if you wish to check for spurious closes
277 pass
278
Bill Janssen54cc54c2007-12-14 22:08:56 +0000279 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000280 """Read up to LEN bytes and return them.
281 Return zero-length string on EOF."""
282
Bill Janssen6e027db2007-11-15 22:23:56 +0000283 self._checkClosed()
284 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000285 if buffer is not None:
286 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000287 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000288 v = self._sslobj.read(len or 1024)
289 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000290 except SSLError as x:
291 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000292 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000293 return 0
294 else:
295 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000296 else:
297 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000298
299 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000300 """Write DATA to the underlying SSL channel. Returns
301 number of bytes of DATA actually transmitted."""
302
Bill Janssen6e027db2007-11-15 22:23:56 +0000303 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000304 return self._sslobj.write(data)
305
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000306 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000307 """Returns a formatted version of the data in the
308 certificate provided by the other end of the SSL channel.
309 Return None if no certificate was provided, {} if a
310 certificate was provided, but not validated."""
311
Bill Janssen6e027db2007-11-15 22:23:56 +0000312 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000313 return self._sslobj.peer_certificate(binary_form)
314
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000315 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000316 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000317 if not self._sslobj:
318 return None
319 else:
320 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000321
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000322 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000323 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000324 if self._sslobj:
325 if flags != 0:
326 raise ValueError(
327 "non-zero flags not allowed in calls to send() on %s" %
328 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000329 while True:
330 try:
331 v = self._sslobj.write(data)
332 except SSLError as x:
333 if x.args[0] == SSL_ERROR_WANT_READ:
334 return 0
335 elif x.args[0] == SSL_ERROR_WANT_WRITE:
336 return 0
337 else:
338 raise
339 else:
340 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 else:
342 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000343
Antoine Pitroua468adc2010-09-14 14:43:44 +0000344 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000345 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000346 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000347 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000349 elif addr is None:
350 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000351 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000352 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000353
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000354 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000355 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000356 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000357 if flags != 0:
358 raise ValueError(
359 "non-zero flags not allowed in calls to sendall() on %s" %
360 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000361 amount = len(data)
362 count = 0
363 while (count < amount):
364 v = self.send(data[count:])
365 count += v
366 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000367 else:
368 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000369
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000370 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000371 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000372 if self._sslobj:
373 if flags != 0:
374 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000375 "non-zero flags not allowed in calls to recv() on %s" %
376 self.__class__)
377 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000378 else:
379 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000380
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000381 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000382 self._checkClosed()
383 if buffer and (nbytes is None):
384 nbytes = len(buffer)
385 elif nbytes is None:
386 nbytes = 1024
387 if self._sslobj:
388 if flags != 0:
389 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000390 "non-zero flags not allowed in calls to recv_into() on %s" %
391 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000392 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000393 else:
394 return socket.recv_into(self, buffer, nbytes, flags)
395
Antoine Pitroua468adc2010-09-14 14:43:44 +0000396 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000397 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000398 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000399 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000400 self.__class__)
401 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000402 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000403
Bill Janssen58afe4c2008-09-08 16:45:19 +0000404 def recvfrom_into(self, buffer, nbytes=None, flags=0):
405 self._checkClosed()
406 if self._sslobj:
407 raise ValueError("recvfrom_into not allowed on instances of %s" %
408 self.__class__)
409 else:
410 return socket.recvfrom_into(self, buffer, nbytes, flags)
411
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000412 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000413 self._checkClosed()
414 if self._sslobj:
415 return self._sslobj.pending()
416 else:
417 return 0
418
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000419 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000420 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000422 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000423
Ezio Melottidc55e672010-01-18 09:15:14 +0000424 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000425 if self._sslobj:
426 s = self._sslobj.shutdown()
427 self._sslobj = None
428 return s
429 else:
430 raise ValueError("No SSL wrapper around " + str(self))
431
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000432 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433 self._sslobj = None
Bill Janssen6e027db2007-11-15 22:23:56 +0000434 # self._closed = True
Bill Janssen54cc54c2007-12-14 22:08:56 +0000435 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000436
Bill Janssen48dc27c2007-12-05 03:38:10 +0000437 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000438 """Perform a TLS/SSL handshake."""
439
Bill Janssen48dc27c2007-12-05 03:38:10 +0000440 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000441 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000442 if timeout == 0.0 and block:
443 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000444 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000445 finally:
446 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000447
Antoine Pitroub4410db2011-05-18 18:51:06 +0200448 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000449 if self.server_side:
450 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000451 # Here we assume that the socket is client-side, and not
452 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000453 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000455 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000456 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200457 if connect_ex:
458 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000459 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200460 rc = None
461 socket.connect(self, addr)
462 if not rc:
463 if self.do_handshake_on_connect:
464 self.do_handshake()
465 self._connected = True
466 return rc
467 except socket_error:
468 self._sslobj = None
469 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000470
471 def connect(self, addr):
472 """Connects to remote ADDR, and then wraps the connection in
473 an SSL channel."""
474 self._real_connect(addr, False)
475
476 def connect_ex(self, addr):
477 """Connects to remote ADDR, and then wraps the connection in
478 an SSL channel."""
479 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000480
481 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000482 """Accepts a new connection from a remote client, and returns
483 a tuple containing that new connection wrapped with a server-side
484 SSL channel, and the address of the remote client."""
485
486 newsock, addr = socket.accept(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000487 return (SSLSocket(sock=newsock,
488 keyfile=self.keyfile, certfile=self.certfile,
489 server_side=True,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000490 cert_reqs=self.cert_reqs,
491 ssl_version=self.ssl_version,
Bill Janssen6e027db2007-11-15 22:23:56 +0000492 ca_certs=self.ca_certs,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000493 ciphers=self.ciphers,
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000494 do_handshake_on_connect=
495 self.do_handshake_on_connect),
Bill Janssen6e027db2007-11-15 22:23:56 +0000496 addr)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Guido van Rossume6650f92007-12-06 19:05:55 +0000498 def __del__(self):
Bill Janssen54cc54c2007-12-14 22:08:56 +0000499 # sys.stderr.write("__del__ on %s\n" % repr(self))
Guido van Rossume6650f92007-12-06 19:05:55 +0000500 self._real_close()
501
Bill Janssen54cc54c2007-12-14 22:08:56 +0000502
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503def wrap_socket(sock, keyfile=None, certfile=None,
504 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000505 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000506 do_handshake_on_connect=True,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000507 suppress_ragged_eofs=True, ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Bill Janssen6e027db2007-11-15 22:23:56 +0000509 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000511 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000512 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000513 suppress_ragged_eofs=suppress_ragged_eofs,
514 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Thomas Woutersed03b412007-08-28 21:37:11 +0000516# some utility functions
517
518def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000519 """Takes a date-time string in standard ASN1_print form
520 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
521 a Python time value in seconds past the epoch."""
522
Thomas Woutersed03b412007-08-28 21:37:11 +0000523 import time
524 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
525
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000526PEM_HEADER = "-----BEGIN CERTIFICATE-----"
527PEM_FOOTER = "-----END CERTIFICATE-----"
528
529def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530 """Takes a certificate in binary DER format and returns the
531 PEM version of it as a string."""
532
Bill Janssen6e027db2007-11-15 22:23:56 +0000533 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
534 return (PEM_HEADER + '\n' +
535 textwrap.fill(f, 64) + '\n' +
536 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
538def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539 """Takes a certificate in ASCII PEM format and returns the
540 DER-encoded version of it as a byte sequence"""
541
542 if not pem_cert_string.startswith(PEM_HEADER):
543 raise ValueError("Invalid PEM encoding; must start with %s"
544 % PEM_HEADER)
545 if not pem_cert_string.strip().endswith(PEM_FOOTER):
546 raise ValueError("Invalid PEM encoding; must end with %s"
547 % PEM_FOOTER)
548 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000549 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000551def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552 """Retrieve the certificate from the server at the specified address,
553 and return it as a PEM-encoded string.
554 If 'ca_certs' is specified, validate the server cert against it.
555 If 'ssl_version' is specified, use it in the connection attempt."""
556
557 host, port = addr
558 if (ca_certs is not None):
559 cert_reqs = CERT_REQUIRED
560 else:
561 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200562 s = create_connection(addr)
563 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565 dercert = s.getpeercert(True)
566 s.close()
567 return DER_cert_to_PEM_cert(dercert)
568
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000569def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200570 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')