blob: d78d96d160e7ee56033ddc8dcad7ccf408b23211 [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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010055PROTOCOL_TLSv1_1
56PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010057
58The following constants identify various SSL alert message descriptions as per
59http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
60
61ALERT_DESCRIPTION_CLOSE_NOTIFY
62ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
63ALERT_DESCRIPTION_BAD_RECORD_MAC
64ALERT_DESCRIPTION_RECORD_OVERFLOW
65ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
66ALERT_DESCRIPTION_HANDSHAKE_FAILURE
67ALERT_DESCRIPTION_BAD_CERTIFICATE
68ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
69ALERT_DESCRIPTION_CERTIFICATE_REVOKED
70ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
71ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
72ALERT_DESCRIPTION_ILLEGAL_PARAMETER
73ALERT_DESCRIPTION_UNKNOWN_CA
74ALERT_DESCRIPTION_ACCESS_DENIED
75ALERT_DESCRIPTION_DECODE_ERROR
76ALERT_DESCRIPTION_DECRYPT_ERROR
77ALERT_DESCRIPTION_PROTOCOL_VERSION
78ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
79ALERT_DESCRIPTION_INTERNAL_ERROR
80ALERT_DESCRIPTION_USER_CANCELLED
81ALERT_DESCRIPTION_NO_RENEGOTIATION
82ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
83ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
84ALERT_DESCRIPTION_UNRECOGNIZED_NAME
85ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
86ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
87ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000088"""
89
Christian Heimes05e8be12008-02-23 18:30:17 +000090import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000091import re
Christian Heimes46bebee2013-06-09 19:03:31 +020092import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020093import os
94import collections
Thomas Woutersed03b412007-08-28 21:37:11 +000095
96import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000097
Antoine Pitrou04f6a322010-04-05 21:40:07 +000098from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitrou41032a62011-10-27 23:56:55 +020099from _ssl import _SSLContext
100from _ssl import (
101 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
102 SSLSyscallError, SSLEOFError,
103 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000104from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Victor Stinner99c8b162011-05-24 12:05:19 +0200105from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100106
107def _import_symbols(prefix):
108 for n in dir(_ssl):
109 if n.startswith(prefix):
110 globals()[n] = getattr(_ssl, n)
111
112_import_symbols('OP_')
113_import_symbols('ALERT_DESCRIPTION_')
114_import_symbols('SSL_ERROR_')
115
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100116from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100117
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100118from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200119from _ssl import _OPENSSL_API_VERSION
120
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100121
Victor Stinner3de49192011-05-09 00:42:58 +0200122_PROTOCOL_NAMES = {
123 PROTOCOL_TLSv1: "TLSv1",
124 PROTOCOL_SSLv23: "SSLv23",
125 PROTOCOL_SSLv3: "SSLv3",
126}
127try:
128 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100129 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400130except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100131 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200132else:
133 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135try:
136 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400137except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100138 pass
139else:
140 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
141 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
142
Christian Heimes46bebee2013-06-09 19:03:31 +0200143if sys.platform == "win32":
144 from _ssl import enum_cert_store, X509_ASN_ENCODING, PKCS_7_ASN_ENCODING
145
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000146from socket import getnameinfo as _getnameinfo
Antoine Pitrou15399c32011-04-28 19:23:55 +0200147from socket import socket, AF_INET, SOCK_STREAM, create_connection
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148import base64 # for DER-to-PEM translation
Bill Janssen54cc54c2007-12-14 22:08:56 +0000149import traceback
Antoine Pitroude8cf322010-04-26 17:29:05 +0000150import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000151
Andrew Svetlov0832af62012-12-18 23:10:48 +0200152
153socket_error = OSError # keep that public name in module namespace
154
Antoine Pitroud6494802011-07-21 01:11:30 +0200155if _ssl.HAS_TLS_UNIQUE:
156 CHANNEL_BINDING_TYPES = ['tls-unique']
157else:
158 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000159
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100160# Disable weak or insecure ciphers by default
161# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
162_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
163
Thomas Woutersed03b412007-08-28 21:37:11 +0000164
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000165class CertificateError(ValueError):
166 pass
167
168
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200169def _dnsname_to_pat(dn, max_wildcards=1):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000170 pats = []
171 for frag in dn.split(r'.'):
Antoine Pitrou636f93c2013-05-18 17:56:42 +0200172 if frag.count('*') > max_wildcards:
173 # Issue #17980: avoid denials of service by refusing more
174 # than one wildcard per fragment. A survery of established
175 # policy among SSL implementations showed it to be a
176 # reasonable choice.
177 raise CertificateError(
178 "too many wildcards in certificate DNS name: " + repr(dn))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000179 if frag == '*':
180 # When '*' is a fragment by itself, it matches a non-empty dotless
181 # fragment.
182 pats.append('[^.]+')
183 else:
184 # Otherwise, '*' matches any dotless fragment.
185 frag = re.escape(frag)
186 pats.append(frag.replace(r'\*', '[^.]*'))
187 return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
188
189
190def match_hostname(cert, hostname):
191 """Verify that *cert* (in decoded format as returned by
192 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
193 are mostly followed, but IP addresses are not accepted for *hostname*.
194
195 CertificateError is raised on failure. On success, the function
196 returns nothing.
197 """
198 if not cert:
199 raise ValueError("empty or no certificate")
200 dnsnames = []
201 san = cert.get('subjectAltName', ())
202 for key, value in san:
203 if key == 'DNS':
204 if _dnsname_to_pat(value).match(hostname):
205 return
206 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200207 if not dnsnames:
208 # The subject is only checked when there is no dNSName entry
209 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000210 for sub in cert.get('subject', ()):
211 for key, value in sub:
212 # XXX according to RFC 2818, the most specific Common Name
213 # must be used.
214 if key == 'commonName':
215 if _dnsname_to_pat(value).match(hostname):
216 return
217 dnsnames.append(value)
218 if len(dnsnames) > 1:
219 raise CertificateError("hostname %r "
220 "doesn't match either of %s"
221 % (hostname, ', '.join(map(repr, dnsnames))))
222 elif len(dnsnames) == 1:
223 raise CertificateError("hostname %r "
224 "doesn't match %r"
225 % (hostname, dnsnames[0]))
226 else:
227 raise CertificateError("no appropriate commonName or "
228 "subjectAltName fields were found")
229
230
Christian Heimes6d7ad132013-06-09 18:02:55 +0200231DefaultVerifyPaths = collections.namedtuple("DefaultVerifyPaths",
232 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
233 "openssl_capath")
234
235def get_default_verify_paths():
236 """Return paths to default cafile and capath.
237 """
238 parts = _ssl.get_default_verify_paths()
239
240 # environment vars shadow paths
241 cafile = os.environ.get(parts[0], parts[1])
242 capath = os.environ.get(parts[2], parts[3])
243
244 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
245 capath if os.path.isdir(capath) else None,
246 *parts)
247
248
Antoine Pitrou152efa22010-05-16 18:19:27 +0000249class SSLContext(_SSLContext):
250 """An SSLContext holds various SSL-related configuration options and
251 data, such as certificates and possibly a private key."""
252
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100253 __slots__ = ('protocol', '__weakref__')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000254
255 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100256 self = _SSLContext.__new__(cls, protocol)
257 if protocol != _SSLv2_IF_EXISTS:
258 self.set_ciphers(_DEFAULT_CIPHERS)
259 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000260
261 def __init__(self, protocol):
262 self.protocol = protocol
263
264 def wrap_socket(self, sock, server_side=False,
265 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000266 suppress_ragged_eofs=True,
267 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000268 return SSLSocket(sock=sock, server_side=server_side,
269 do_handshake_on_connect=do_handshake_on_connect,
270 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000271 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000272 _context=self)
273
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100274 def set_npn_protocols(self, npn_protocols):
275 protos = bytearray()
276 for protocol in npn_protocols:
277 b = bytes(protocol, 'ascii')
278 if len(b) == 0 or len(b) > 255:
279 raise SSLError('NPN protocols must be 1 to 255 in length')
280 protos.append(len(b))
281 protos.extend(b)
282
283 self._set_npn_protocols(protos)
284
Antoine Pitrou152efa22010-05-16 18:19:27 +0000285
286class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000287 """This class implements a subtype of socket.socket that wraps
288 the underlying OS socket in an SSL context when necessary, and
289 provides read and write methods over that channel."""
290
Bill Janssen6e027db2007-11-15 22:23:56 +0000291 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000292 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000293 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
294 do_handshake_on_connect=True,
295 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100296 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000297 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000298 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000299
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100301 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000302 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000303 if server_side and not certfile:
304 raise ValueError("certfile must be specified for server-side "
305 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000306 if keyfile and not certfile:
307 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000308 if certfile and not keyfile:
309 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100310 self._context = SSLContext(ssl_version)
311 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100313 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000314 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100315 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100316 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100317 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000318 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100319 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000320 self.keyfile = keyfile
321 self.certfile = certfile
322 self.cert_reqs = cert_reqs
323 self.ssl_version = ssl_version
324 self.ca_certs = ca_certs
325 self.ciphers = ciphers
Antoine Pitroud5323212010-10-22 18:19:07 +0000326 if server_side and server_hostname:
327 raise ValueError("server_hostname can only be specified "
328 "in client mode")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000329 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000330 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000331 self.do_handshake_on_connect = do_handshake_on_connect
332 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000333 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000334 socket.__init__(self,
335 family=sock.family,
336 type=sock.type,
337 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000338 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000339 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000340 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000341 elif fileno is not None:
342 socket.__init__(self, fileno=fileno)
343 else:
344 socket.__init__(self, family=family, type=type, proto=proto)
345
Antoine Pitrou242db722013-05-01 20:52:07 +0200346 # See if we are connected
347 try:
348 self.getpeername()
349 except OSError as e:
350 if e.errno != errno.ENOTCONN:
351 raise
352 connected = False
353 else:
354 connected = True
355
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000356 self._closed = False
357 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000358 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000359 if connected:
360 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000361 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100362 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000363 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000364 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000365 timeout = self.gettimeout()
366 if timeout == 0.0:
367 # non-blocking
368 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000369 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000370
Andrew Svetlov0832af62012-12-18 23:10:48 +0200371 except OSError as x:
Bill Janssen6e027db2007-11-15 22:23:56 +0000372 self.close()
373 raise x
Antoine Pitrou242db722013-05-01 20:52:07 +0200374
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100375 @property
376 def context(self):
377 return self._context
378
379 @context.setter
380 def context(self, ctx):
381 self._context = ctx
382 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000383
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000384 def dup(self):
385 raise NotImplemented("Can't dup() %s instances" %
386 self.__class__.__name__)
387
Bill Janssen6e027db2007-11-15 22:23:56 +0000388 def _checkClosed(self, msg=None):
389 # raise an exception here if you wish to check for spurious closes
390 pass
391
Antoine Pitrou242db722013-05-01 20:52:07 +0200392 def _check_connected(self):
393 if not self._connected:
394 # getpeername() will raise ENOTCONN if the socket is really
395 # not connected; note that we can be connected even without
396 # _connected being set, e.g. if connect() first returned
397 # EAGAIN.
398 self.getpeername()
399
Bill Janssen54cc54c2007-12-14 22:08:56 +0000400 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000401 """Read up to LEN bytes and return them.
402 Return zero-length string on EOF."""
403
Bill Janssen6e027db2007-11-15 22:23:56 +0000404 self._checkClosed()
405 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000406 if buffer is not None:
407 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000408 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000409 v = self._sslobj.read(len or 1024)
410 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000411 except SSLError as x:
412 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000413 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000414 return 0
415 else:
416 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000417 else:
418 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000419
420 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000421 """Write DATA to the underlying SSL channel. Returns
422 number of bytes of DATA actually transmitted."""
423
Bill Janssen6e027db2007-11-15 22:23:56 +0000424 self._checkClosed()
Thomas Woutersed03b412007-08-28 21:37:11 +0000425 return self._sslobj.write(data)
426
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000428 """Returns a formatted version of the data in the
429 certificate provided by the other end of the SSL channel.
430 Return None if no certificate was provided, {} if a
431 certificate was provided, but not validated."""
432
Bill Janssen6e027db2007-11-15 22:23:56 +0000433 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200434 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435 return self._sslobj.peer_certificate(binary_form)
436
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100437 def selected_npn_protocol(self):
438 self._checkClosed()
439 if not self._sslobj or not _ssl.HAS_NPN:
440 return None
441 else:
442 return self._sslobj.selected_npn_protocol()
443
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000444 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000445 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000446 if not self._sslobj:
447 return None
448 else:
449 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000450
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100451 def compression(self):
452 self._checkClosed()
453 if not self._sslobj:
454 return None
455 else:
456 return self._sslobj.compression()
457
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000458 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000459 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000460 if self._sslobj:
461 if flags != 0:
462 raise ValueError(
463 "non-zero flags not allowed in calls to send() on %s" %
464 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200465 try:
466 v = self._sslobj.write(data)
467 except SSLError as x:
468 if x.args[0] == SSL_ERROR_WANT_READ:
469 return 0
470 elif x.args[0] == SSL_ERROR_WANT_WRITE:
471 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000472 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200473 raise
474 else:
475 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000476 else:
477 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000478
Antoine Pitroua468adc2010-09-14 14:43:44 +0000479 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000480 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000481 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000482 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000483 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000484 elif addr is None:
485 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000486 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000487 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000488
Nick Coghlan513886a2011-08-28 00:00:27 +1000489 def sendmsg(self, *args, **kwargs):
490 # Ensure programs don't send data unencrypted if they try to
491 # use this method.
492 raise NotImplementedError("sendmsg not allowed on instances of %s" %
493 self.__class__)
494
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000495 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000496 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000497 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000498 if flags != 0:
499 raise ValueError(
500 "non-zero flags not allowed in calls to sendall() on %s" %
501 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000502 amount = len(data)
503 count = 0
504 while (count < amount):
505 v = self.send(data[count:])
506 count += v
507 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000508 else:
509 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000510
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000511 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000512 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000513 if self._sslobj:
514 if flags != 0:
515 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000516 "non-zero flags not allowed in calls to recv() on %s" %
517 self.__class__)
518 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000519 else:
520 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000521
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000522 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000523 self._checkClosed()
524 if buffer and (nbytes is None):
525 nbytes = len(buffer)
526 elif nbytes is None:
527 nbytes = 1024
528 if self._sslobj:
529 if flags != 0:
530 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000531 "non-zero flags not allowed in calls to recv_into() on %s" %
532 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000533 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000534 else:
535 return socket.recv_into(self, buffer, nbytes, flags)
536
Antoine Pitroua468adc2010-09-14 14:43:44 +0000537 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000538 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000539 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000540 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000541 self.__class__)
542 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000543 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000544
Bill Janssen58afe4c2008-09-08 16:45:19 +0000545 def recvfrom_into(self, buffer, nbytes=None, flags=0):
546 self._checkClosed()
547 if self._sslobj:
548 raise ValueError("recvfrom_into not allowed on instances of %s" %
549 self.__class__)
550 else:
551 return socket.recvfrom_into(self, buffer, nbytes, flags)
552
Nick Coghlan513886a2011-08-28 00:00:27 +1000553 def recvmsg(self, *args, **kwargs):
554 raise NotImplementedError("recvmsg not allowed on instances of %s" %
555 self.__class__)
556
557 def recvmsg_into(self, *args, **kwargs):
558 raise NotImplementedError("recvmsg_into not allowed on instances of "
559 "%s" % self.__class__)
560
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000561 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000562 self._checkClosed()
563 if self._sslobj:
564 return self._sslobj.pending()
565 else:
566 return 0
567
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000568 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000569 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000571 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000572
Ezio Melottidc55e672010-01-18 09:15:14 +0000573 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000574 if self._sslobj:
575 s = self._sslobj.shutdown()
576 self._sslobj = None
577 return s
578 else:
579 raise ValueError("No SSL wrapper around " + str(self))
580
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000581 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000583 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000584
Bill Janssen48dc27c2007-12-05 03:38:10 +0000585 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000586 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200587 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000588 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000589 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000590 if timeout == 0.0 and block:
591 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000592 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000593 finally:
594 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000595
Antoine Pitroub4410db2011-05-18 18:51:06 +0200596 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000597 if self.server_side:
598 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000599 # Here we assume that the socket is client-side, and not
600 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000601 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000603 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000604 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200605 if connect_ex:
606 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000607 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200608 rc = None
609 socket.connect(self, addr)
610 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200611 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200612 if self.do_handshake_on_connect:
613 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200614 return rc
Andrew Svetlov0832af62012-12-18 23:10:48 +0200615 except OSError:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200616 self._sslobj = None
617 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000618
619 def connect(self, addr):
620 """Connects to remote ADDR, and then wraps the connection in
621 an SSL channel."""
622 self._real_connect(addr, False)
623
624 def connect_ex(self, addr):
625 """Connects to remote ADDR, and then wraps the connection in
626 an SSL channel."""
627 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000628
629 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000630 """Accepts a new connection from a remote client, and returns
631 a tuple containing that new connection wrapped with a server-side
632 SSL channel, and the address of the remote client."""
633
634 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100635 newsock = self.context.wrap_socket(newsock,
636 do_handshake_on_connect=self.do_handshake_on_connect,
637 suppress_ragged_eofs=self.suppress_ragged_eofs,
638 server_side=True)
639 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Antoine Pitroud6494802011-07-21 01:11:30 +0200641 def get_channel_binding(self, cb_type="tls-unique"):
642 """Get channel binding data for current connection. Raise ValueError
643 if the requested `cb_type` is not supported. Return bytes of the data
644 or None if the data is not available (e.g. before the handshake).
645 """
646 if cb_type not in CHANNEL_BINDING_TYPES:
647 raise ValueError("Unsupported channel binding type")
648 if cb_type != "tls-unique":
649 raise NotImplementedError(
650 "{0} channel binding type not implemented"
651 .format(cb_type))
652 if self._sslobj is None:
653 return None
654 return self._sslobj.tls_unique_cb()
655
Bill Janssen54cc54c2007-12-14 22:08:56 +0000656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657def wrap_socket(sock, keyfile=None, certfile=None,
658 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000659 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000660 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100661 suppress_ragged_eofs=True,
662 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Bill Janssen6e027db2007-11-15 22:23:56 +0000664 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000666 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000667 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000668 suppress_ragged_eofs=suppress_ragged_eofs,
669 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Thomas Woutersed03b412007-08-28 21:37:11 +0000671# some utility functions
672
673def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000674 """Takes a date-time string in standard ASN1_print form
675 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
676 a Python time value in seconds past the epoch."""
677
Thomas Woutersed03b412007-08-28 21:37:11 +0000678 import time
679 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
680
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681PEM_HEADER = "-----BEGIN CERTIFICATE-----"
682PEM_FOOTER = "-----END CERTIFICATE-----"
683
684def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685 """Takes a certificate in binary DER format and returns the
686 PEM version of it as a string."""
687
Bill Janssen6e027db2007-11-15 22:23:56 +0000688 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
689 return (PEM_HEADER + '\n' +
690 textwrap.fill(f, 64) + '\n' +
691 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
693def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694 """Takes a certificate in ASCII PEM format and returns the
695 DER-encoded version of it as a byte sequence"""
696
697 if not pem_cert_string.startswith(PEM_HEADER):
698 raise ValueError("Invalid PEM encoding; must start with %s"
699 % PEM_HEADER)
700 if not pem_cert_string.strip().endswith(PEM_FOOTER):
701 raise ValueError("Invalid PEM encoding; must end with %s"
702 % PEM_FOOTER)
703 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000704 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000706def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707 """Retrieve the certificate from the server at the specified address,
708 and return it as a PEM-encoded string.
709 If 'ca_certs' is specified, validate the server cert against it.
710 If 'ssl_version' is specified, use it in the connection attempt."""
711
712 host, port = addr
713 if (ca_certs is not None):
714 cert_reqs = CERT_REQUIRED
715 else:
716 cert_reqs = CERT_NONE
Antoine Pitrou15399c32011-04-28 19:23:55 +0200717 s = create_connection(addr)
718 s = wrap_socket(s, ssl_version=ssl_version,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719 cert_reqs=cert_reqs, ca_certs=ca_certs)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720 dercert = s.getpeercert(True)
721 s.close()
722 return DER_cert_to_PEM_cert(dercert)
723
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000724def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200725 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')