blob: f2537698d303dff3a06f244bbd4d23f172bea4a8 [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
Christian Heimes598894f2016-09-05 23:19:05 +020054PROTOCOL_TLS
Christian Heimes5fe668c2016-09-12 00:01:11 +020055PROTOCOL_TLS_CLIENT
56PROTOCOL_TLS_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010058PROTOCOL_TLSv1_1
59PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010060
61The following constants identify various SSL alert message descriptions as per
62http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
63
64ALERT_DESCRIPTION_CLOSE_NOTIFY
65ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
66ALERT_DESCRIPTION_BAD_RECORD_MAC
67ALERT_DESCRIPTION_RECORD_OVERFLOW
68ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
69ALERT_DESCRIPTION_HANDSHAKE_FAILURE
70ALERT_DESCRIPTION_BAD_CERTIFICATE
71ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
72ALERT_DESCRIPTION_CERTIFICATE_REVOKED
73ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
74ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
75ALERT_DESCRIPTION_ILLEGAL_PARAMETER
76ALERT_DESCRIPTION_UNKNOWN_CA
77ALERT_DESCRIPTION_ACCESS_DENIED
78ALERT_DESCRIPTION_DECODE_ERROR
79ALERT_DESCRIPTION_DECRYPT_ERROR
80ALERT_DESCRIPTION_PROTOCOL_VERSION
81ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
82ALERT_DESCRIPTION_INTERNAL_ERROR
83ALERT_DESCRIPTION_USER_CANCELLED
84ALERT_DESCRIPTION_NO_RENEGOTIATION
85ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
86ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
87ALERT_DESCRIPTION_UNRECOGNIZED_NAME
88ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
89ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
90ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000091"""
92
Antoine Pitrouc481bfb2015-02-15 18:12:20 +010093import ipaddress
Antoine Pitrou59fdd672010-10-08 10:37:08 +000094import re
Christian Heimes46bebee2013-06-09 19:03:31 +020095import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020096import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010097from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020098from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +000099
100import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000101
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000102from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200103from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200104from _ssl import (
105 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700106 SSLSyscallError, SSLEOFError, SSLCertVerificationError
Antoine Pitrou41032a62011-10-27 23:56:55 +0200107 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100109from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
110try:
111 from _ssl import RAND_egd
112except ImportError:
113 # LibreSSL does not provide RAND_egd
114 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100115
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100116
Christian Heimescb5b68a2017-09-07 18:07:00 -0700117from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
Christian Heimes892d66e2018-01-29 14:10:18 +0100118from _ssl import _DEFAULT_CIPHERS
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200119from _ssl import _OPENSSL_API_VERSION
120
Christian Heimes3aeacad2016-09-10 00:19:35 +0200121
Ethan Furman24e837f2015-03-18 17:27:57 -0700122_IntEnum._convert(
Christian Heimes3aeacad2016-09-10 00:19:35 +0200123 '_SSLMethod', __name__,
124 lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
125 source=_ssl)
126
127_IntFlag._convert(
128 'Options', __name__,
129 lambda name: name.startswith('OP_'),
130 source=_ssl)
131
132_IntEnum._convert(
133 'AlertDescription', __name__,
134 lambda name: name.startswith('ALERT_DESCRIPTION_'),
135 source=_ssl)
136
137_IntEnum._convert(
138 'SSLErrorNumber', __name__,
139 lambda name: name.startswith('SSL_ERROR_'),
140 source=_ssl)
141
142_IntFlag._convert(
143 'VerifyFlags', __name__,
144 lambda name: name.startswith('VERIFY_'),
145 source=_ssl)
146
147_IntEnum._convert(
148 'VerifyMode', __name__,
149 lambda name: name.startswith('CERT_'),
150 source=_ssl)
151
Christian Heimes598894f2016-09-05 23:19:05 +0200152PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200153_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
154
Christian Heimes3aeacad2016-09-10 00:19:35 +0200155_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
156
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100157
Christian Heimes46bebee2013-06-09 19:03:31 +0200158if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100159 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200160
Antoine Pitrou15399c32011-04-28 19:23:55 +0200161from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100162from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000164import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700165import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000166
Andrew Svetlov0832af62012-12-18 23:10:48 +0200167
168socket_error = OSError # keep that public name in module namespace
169
Antoine Pitroud6494802011-07-21 01:11:30 +0200170if _ssl.HAS_TLS_UNIQUE:
171 CHANNEL_BINDING_TYPES = ['tls-unique']
172else:
173 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000174
Christian Heimes61d478c2018-01-27 15:51:38 +0100175HAS_NEVER_CHECK_COMMON_NAME = hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT')
176
Christian Heimes03d13c02016-09-06 20:06:47 +0200177
Christian Heimes892d66e2018-01-29 14:10:18 +0100178_RESTRICTED_SERVER_CIPHERS = _DEFAULT_CIPHERS
Christian Heimes4c05b472013-11-23 15:58:30 +0100179
Christian Heimes61d478c2018-01-27 15:51:38 +0100180CertificateError = SSLCertVerificationError
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000181
182
Mandeep Singhede2ac92017-11-27 04:01:27 +0530183def _dnsname_match(dn, hostname):
Georg Brandl72c98d32013-10-27 07:16:53 +0100184 """Matching according to RFC 6125, section 6.4.3
185
186 http://tools.ietf.org/html/rfc6125#section-6.4.3
187 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000188 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100189 if not dn:
190 return False
191
192 leftmost, *remainder = dn.split(r'.')
193
194 wildcards = leftmost.count('*')
Mandeep Singhede2ac92017-11-27 04:01:27 +0530195 if wildcards == 1 and len(leftmost) > 1:
196 # Only match wildcard in leftmost segment.
197 raise CertificateError(
198 "wildcard can only be present in the leftmost segment: " + repr(dn))
199
200 if wildcards > 1:
Georg Brandl72c98d32013-10-27 07:16:53 +0100201 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300202 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100203 # policy among SSL implementations showed it to be a
204 # reasonable choice.
205 raise CertificateError(
206 "too many wildcards in certificate DNS name: " + repr(dn))
207
208 # speed up common case w/o wildcards
209 if not wildcards:
210 return dn.lower() == hostname.lower()
211
212 # RFC 6125, section 6.4.3, subitem 1.
213 # The client SHOULD NOT attempt to match a presented identifier in which
214 # the wildcard character comprises a label other than the left-most label.
215 if leftmost == '*':
216 # When '*' is a fragment by itself, it matches a non-empty dotless
217 # fragment.
218 pats.append('[^.]+')
219 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
220 # RFC 6125, section 6.4.3, subitem 3.
221 # The client SHOULD NOT attempt to match a presented identifier
222 # where the wildcard character is embedded within an A-label or
223 # U-label of an internationalized domain name.
224 pats.append(re.escape(leftmost))
225 else:
226 # Otherwise, '*' matches any dotless string, e.g. www*
227 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
228
229 # add the remaining fragments, ignore any wildcards
230 for frag in remainder:
231 pats.append(re.escape(frag))
232
233 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
234 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000235
236
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100237def _ipaddress_match(ipname, host_ip):
238 """Exact matching of IP addresses.
239
240 RFC 6125 explicitly doesn't define an algorithm for this
241 (section 1.7.2 - "Out of Scope").
242 """
243 # OpenSSL may add a trailing newline to a subjectAltName's IP address
244 ip = ipaddress.ip_address(ipname.rstrip())
245 return ip == host_ip
246
247
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000248def match_hostname(cert, hostname):
249 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100250 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
251 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000252
253 CertificateError is raised on failure. On success, the function
254 returns nothing.
255 """
256 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100257 raise ValueError("empty or no certificate, match_hostname needs a "
258 "SSL socket or SSL context with either "
259 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100260 try:
261 host_ip = ipaddress.ip_address(hostname)
262 except ValueError:
263 # Not an IP address (common case)
264 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000265 dnsnames = []
266 san = cert.get('subjectAltName', ())
267 for key, value in san:
268 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100269 if host_ip is None and _dnsname_match(value, hostname):
270 return
271 dnsnames.append(value)
272 elif key == 'IP Address':
273 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000274 return
275 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200276 if not dnsnames:
277 # The subject is only checked when there is no dNSName entry
278 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000279 for sub in cert.get('subject', ()):
280 for key, value in sub:
281 # XXX according to RFC 2818, the most specific Common Name
282 # must be used.
283 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100284 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000285 return
286 dnsnames.append(value)
287 if len(dnsnames) > 1:
288 raise CertificateError("hostname %r "
289 "doesn't match either of %s"
290 % (hostname, ', '.join(map(repr, dnsnames))))
291 elif len(dnsnames) == 1:
292 raise CertificateError("hostname %r "
293 "doesn't match %r"
294 % (hostname, dnsnames[0]))
295 else:
296 raise CertificateError("no appropriate commonName or "
297 "subjectAltName fields were found")
298
299
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100300DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200301 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
302 "openssl_capath")
303
304def get_default_verify_paths():
305 """Return paths to default cafile and capath.
306 """
307 parts = _ssl.get_default_verify_paths()
308
309 # environment vars shadow paths
310 cafile = os.environ.get(parts[0], parts[1])
311 capath = os.environ.get(parts[2], parts[3])
312
313 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
314 capath if os.path.isdir(capath) else None,
315 *parts)
316
317
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100318class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
319 """ASN.1 object identifier lookup
320 """
321 __slots__ = ()
322
323 def __new__(cls, oid):
324 return super().__new__(cls, *_txt2obj(oid, name=False))
325
326 @classmethod
327 def fromnid(cls, nid):
328 """Create _ASN1Object from OpenSSL numeric ID
329 """
330 return super().__new__(cls, *_nid2obj(nid))
331
332 @classmethod
333 def fromname(cls, name):
334 """Create _ASN1Object from short name, long name or OID
335 """
336 return super().__new__(cls, *_txt2obj(name, name=True))
337
338
Christian Heimes72d28502013-11-23 13:56:58 +0100339class Purpose(_ASN1Object, _Enum):
340 """SSLContext purpose flags with X509v3 Extended Key Usage objects
341 """
342 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
343 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
344
345
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346class SSLContext(_SSLContext):
347 """An SSLContext holds various SSL-related configuration options and
348 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100349 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350
Christian Heimes4df60f12017-09-15 20:26:05 +0200351 sslsocket_class = None # SSLSocket is assigned later.
352 sslobject_class = None # SSLObject is assigned later.
353
Christian Heimes598894f2016-09-05 23:19:05 +0200354 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100355 self = _SSLContext.__new__(cls, protocol)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100356 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000357
Christian Heimes11a14932018-02-24 02:35:08 +0100358 def _encode_hostname(self, hostname):
359 if hostname is None:
360 return None
361 elif isinstance(hostname, str):
362 return hostname.encode('idna').decode('ascii')
363 else:
364 return hostname.decode('ascii')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000365
366 def wrap_socket(self, sock, server_side=False,
367 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000368 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200369 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100370 # SSLSocket class handles server_hostname encoding before it calls
371 # ctx._wrap_socket()
Christian Heimes4df60f12017-09-15 20:26:05 +0200372 return self.sslsocket_class(
373 sock=sock,
374 server_side=server_side,
375 do_handshake_on_connect=do_handshake_on_connect,
376 suppress_ragged_eofs=suppress_ragged_eofs,
377 server_hostname=server_hostname,
378 _context=self,
379 _session=session
380 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200382 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200383 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100384 # Need to encode server_hostname here because _wrap_bio() can only
385 # handle ASCII str.
386 sslobj = self._wrap_bio(
387 incoming, outgoing, server_side=server_side,
388 server_hostname=self._encode_hostname(server_hostname)
389 )
Christian Heimes4df60f12017-09-15 20:26:05 +0200390 return self.sslobject_class(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200391
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100392 def set_npn_protocols(self, npn_protocols):
393 protos = bytearray()
394 for protocol in npn_protocols:
395 b = bytes(protocol, 'ascii')
396 if len(b) == 0 or len(b) > 255:
397 raise SSLError('NPN protocols must be 1 to 255 in length')
398 protos.append(len(b))
399 protos.extend(b)
400
401 self._set_npn_protocols(protos)
402
Christian Heimes11a14932018-02-24 02:35:08 +0100403 def set_servername_callback(self, server_name_callback):
404 if server_name_callback is None:
405 self.sni_callback = None
406 else:
407 if not callable(server_name_callback):
408 raise TypeError("not a callable object")
409
410 def shim_cb(sslobj, servername, sslctx):
411 servername = self._encode_hostname(servername)
412 return server_name_callback(sslobj, servername, sslctx)
413
414 self.sni_callback = shim_cb
415
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416 def set_alpn_protocols(self, alpn_protocols):
417 protos = bytearray()
418 for protocol in alpn_protocols:
419 b = bytes(protocol, 'ascii')
420 if len(b) == 0 or len(b) > 255:
421 raise SSLError('ALPN protocols must be 1 to 255 in length')
422 protos.append(len(b))
423 protos.extend(b)
424
425 self._set_alpn_protocols(protos)
426
Christian Heimes72d28502013-11-23 13:56:58 +0100427 def _load_windows_store_certs(self, storename, purpose):
428 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700429 try:
430 for cert, encoding, trust in enum_certificates(storename):
431 # CA certs are never PKCS#7 encoded
432 if encoding == "x509_asn":
433 if trust is True or purpose.oid in trust:
434 certs.extend(cert)
435 except PermissionError:
436 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700437 if certs:
438 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100439 return certs
440
441 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
442 if not isinstance(purpose, _ASN1Object):
443 raise TypeError(purpose)
444 if sys.platform == "win32":
445 for storename in self._windows_cert_stores:
446 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400447 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100448
Christian Heimes3aeacad2016-09-10 00:19:35 +0200449 @property
450 def options(self):
451 return Options(super().options)
452
453 @options.setter
454 def options(self, value):
455 super(SSLContext, SSLContext).options.__set__(self, value)
456
Christian Heimes61d478c2018-01-27 15:51:38 +0100457 if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
458 @property
459 def hostname_checks_common_name(self):
460 ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
461 return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
462
463 @hostname_checks_common_name.setter
464 def hostname_checks_common_name(self, value):
465 if value:
466 self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
467 else:
468 self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
469 else:
470 @property
471 def hostname_checks_common_name(self):
472 return True
473
Christian Heimes3aeacad2016-09-10 00:19:35 +0200474 @property
Christian Heimes11a14932018-02-24 02:35:08 +0100475 def protocol(self):
476 return _SSLMethod(super().protocol)
477
478 @property
Christian Heimes3aeacad2016-09-10 00:19:35 +0200479 def verify_flags(self):
480 return VerifyFlags(super().verify_flags)
481
482 @verify_flags.setter
483 def verify_flags(self, value):
484 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
485
486 @property
487 def verify_mode(self):
488 value = super().verify_mode
489 try:
490 return VerifyMode(value)
491 except ValueError:
492 return value
493
494 @verify_mode.setter
495 def verify_mode(self, value):
496 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
497
Antoine Pitrou152efa22010-05-16 18:19:27 +0000498
Christian Heimes4c05b472013-11-23 15:58:30 +0100499def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
500 capath=None, cadata=None):
501 """Create a SSLContext object with default settings.
502
503 NOTE: The protocol and settings may change anytime without prior
504 deprecation. The values represent a fair balance between maximum
505 compatibility and security.
506 """
507 if not isinstance(purpose, _ASN1Object):
508 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400509
Christian Heimes358cfd42016-09-10 22:43:48 +0200510 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
511 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
512 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200513 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400514
Christian Heimes4c05b472013-11-23 15:58:30 +0100515 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400516 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100517 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100518 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400519
Christian Heimes4c05b472013-11-23 15:58:30 +0100520 if cafile or capath or cadata:
521 context.load_verify_locations(cafile, capath, cadata)
522 elif context.verify_mode != CERT_NONE:
523 # no explicit cafile, capath or cadata but the verify mode is
524 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
525 # root CA certificates for the given purpose. This may fail silently.
526 context.load_default_certs(purpose)
527 return context
528
Christian Heimesa170fa12017-09-15 20:27:30 +0200529def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100530 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100531 certfile=None, keyfile=None,
532 cafile=None, capath=None, cadata=None):
533 """Create a SSLContext object for Python stdlib modules
534
535 All Python stdlib modules shall use this function to create SSLContext
536 objects in order to keep common settings in one place. The configuration
537 is less restrict than create_default_context()'s to increase backward
538 compatibility.
539 """
540 if not isinstance(purpose, _ASN1Object):
541 raise TypeError(purpose)
542
Christian Heimes358cfd42016-09-10 22:43:48 +0200543 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
544 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
545 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100546 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100547
Christian Heimesa170fa12017-09-15 20:27:30 +0200548 if not check_hostname:
549 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100550 if cert_reqs is not None:
551 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200552 if check_hostname:
553 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100554
555 if keyfile and not certfile:
556 raise ValueError("certfile must be specified")
557 if certfile or keyfile:
558 context.load_cert_chain(certfile, keyfile)
559
560 # load CA root certs
561 if cafile or capath or cadata:
562 context.load_verify_locations(cafile, capath, cadata)
563 elif context.verify_mode != CERT_NONE:
564 # no explicit cafile, capath or cadata but the verify mode is
565 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
566 # root CA certificates for the given purpose. This may fail silently.
567 context.load_default_certs(purpose)
568
569 return context
570
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500571# Used by http.client if no context is explicitly passed.
572_create_default_https_context = create_default_context
573
574
575# Backwards compatibility alias, even though it's not a public name.
576_create_stdlib_context = _create_unverified_context
577
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200578
579class SSLObject:
580 """This class implements an interface on top of a low-level SSL object as
581 implemented by OpenSSL. This object captures the state of an SSL connection
582 but does not provide any network IO itself. IO needs to be performed
583 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
584
585 This class does not have a public constructor. Instances are returned by
586 ``SSLContext.wrap_bio``. This class is typically used by framework authors
587 that want to implement asynchronous IO for SSL through memory buffers.
588
589 When compared to ``SSLSocket``, this object lacks the following features:
590
591 * Any form of network IO incluging methods such as ``recv`` and ``send``.
592 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
593 """
594
Christian Heimes99a65702016-09-10 23:44:53 +0200595 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 self._sslobj = sslobj
597 # Note: _sslobj takes a weak reference to owner
598 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200599 if session is not None:
600 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200601
602 @property
603 def context(self):
604 """The SSLContext that is currently in use."""
605 return self._sslobj.context
606
607 @context.setter
608 def context(self, ctx):
609 self._sslobj.context = ctx
610
611 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200612 def session(self):
613 """The SSLSession for client socket."""
614 return self._sslobj.session
615
616 @session.setter
617 def session(self, session):
618 self._sslobj.session = session
619
620 @property
621 def session_reused(self):
622 """Was the client session reused during handshake"""
623 return self._sslobj.session_reused
624
625 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200626 def server_side(self):
627 """Whether this is a server-side socket."""
628 return self._sslobj.server_side
629
630 @property
631 def server_hostname(self):
632 """The currently set server hostname (for SNI), or ``None`` if no
633 server hostame is set."""
634 return self._sslobj.server_hostname
635
Martin Panterf6b1d662016-03-28 00:22:09 +0000636 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200637 """Read up to 'len' bytes from the SSL object and return them.
638
639 If 'buffer' is provided, read into this buffer and return the number of
640 bytes read.
641 """
642 if buffer is not None:
643 v = self._sslobj.read(len, buffer)
644 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000645 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200646 return v
647
648 def write(self, data):
649 """Write 'data' to the SSL object and return the number of bytes
650 written.
651
652 The 'data' argument must support the buffer interface.
653 """
654 return self._sslobj.write(data)
655
656 def getpeercert(self, binary_form=False):
657 """Returns a formatted version of the data in the certificate provided
658 by the other end of the SSL channel.
659
660 Return None if no certificate was provided, {} if a certificate was
661 provided, but not validated.
662 """
663 return self._sslobj.peer_certificate(binary_form)
664
665 def selected_npn_protocol(self):
666 """Return the currently selected NPN protocol as a string, or ``None``
667 if a next protocol was not negotiated or if NPN is not supported by one
668 of the peers."""
669 if _ssl.HAS_NPN:
670 return self._sslobj.selected_npn_protocol()
671
Benjamin Petersoncca27322015-01-23 16:35:37 -0500672 def selected_alpn_protocol(self):
673 """Return the currently selected ALPN protocol as a string, or ``None``
674 if a next protocol was not negotiated or if ALPN is not supported by one
675 of the peers."""
676 if _ssl.HAS_ALPN:
677 return self._sslobj.selected_alpn_protocol()
678
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200679 def cipher(self):
680 """Return the currently selected cipher as a 3-tuple ``(name,
681 ssl_version, secret_bits)``."""
682 return self._sslobj.cipher()
683
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600684 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500685 """Return a list of ciphers shared by the client during the handshake or
686 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600687 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600688 return self._sslobj.shared_ciphers()
689
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200690 def compression(self):
691 """Return the current compression algorithm in use, or ``None`` if
692 compression was not negotiated or not supported by one of the peers."""
693 return self._sslobj.compression()
694
695 def pending(self):
696 """Return the number of bytes that can be read immediately."""
697 return self._sslobj.pending()
698
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200699 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200700 """Start the SSL/TLS handshake."""
701 self._sslobj.do_handshake()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200702
703 def unwrap(self):
704 """Start the SSL shutdown handshake."""
705 return self._sslobj.shutdown()
706
707 def get_channel_binding(self, cb_type="tls-unique"):
708 """Get channel binding data for current connection. Raise ValueError
709 if the requested `cb_type` is not supported. Return bytes of the data
710 or None if the data is not available (e.g. before the handshake)."""
711 if cb_type not in CHANNEL_BINDING_TYPES:
712 raise ValueError("Unsupported channel binding type")
713 if cb_type != "tls-unique":
714 raise NotImplementedError(
715 "{0} channel binding type not implemented"
716 .format(cb_type))
717 return self._sslobj.tls_unique_cb()
718
719 def version(self):
720 """Return a string identifying the protocol version used by the
721 current SSL channel. """
722 return self._sslobj.version()
723
724
Antoine Pitrou152efa22010-05-16 18:19:27 +0000725class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000726 """This class implements a subtype of socket.socket that wraps
727 the underlying OS socket in an SSL context when necessary, and
728 provides read and write methods over that channel."""
729
Bill Janssen6e027db2007-11-15 22:23:56 +0000730 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000731 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200732 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000733 do_handshake_on_connect=True,
734 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100735 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000736 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200737 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000738
Antoine Pitrou152efa22010-05-16 18:19:27 +0000739 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100740 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000741 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000742 if server_side and not certfile:
743 raise ValueError("certfile must be specified for server-side "
744 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000745 if keyfile and not certfile:
746 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000747 if certfile and not keyfile:
748 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100749 self._context = SSLContext(ssl_version)
750 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000751 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100752 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000753 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100754 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100755 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000757 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100758 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000759 self.keyfile = keyfile
760 self.certfile = certfile
761 self.cert_reqs = cert_reqs
762 self.ssl_version = ssl_version
763 self.ca_certs = ca_certs
764 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100765 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
766 # mixed in.
767 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
768 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200769 if server_side:
770 if server_hostname:
771 raise ValueError("server_hostname can only be specified "
772 "in client mode")
773 if _session is not None:
774 raise ValueError("session can only be specified in "
775 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100776 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600777 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200778 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000779 self.server_side = server_side
Christian Heimes11a14932018-02-24 02:35:08 +0100780 self.server_hostname = self._context._encode_hostname(server_hostname)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000781 self.do_handshake_on_connect = do_handshake_on_connect
782 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000783 if sock is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100784 super().__init__(family=sock.family,
785 type=sock.type,
786 proto=sock.proto,
787 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000788 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000789 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000790 elif fileno is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100791 super().__init__(fileno=fileno)
Bill Janssen6e027db2007-11-15 22:23:56 +0000792 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100793 super().__init__(family=family, type=type, proto=proto)
Bill Janssen6e027db2007-11-15 22:23:56 +0000794
Antoine Pitrou242db722013-05-01 20:52:07 +0200795 # See if we are connected
796 try:
797 self.getpeername()
798 except OSError as e:
799 if e.errno != errno.ENOTCONN:
800 raise
801 connected = False
802 else:
803 connected = True
804
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000805 self._closed = False
806 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000807 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000808 if connected:
809 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000810 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200811 sslobj = self._context._wrap_socket(self, server_side,
Christian Heimes11a14932018-02-24 02:35:08 +0100812 self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200813 self._sslobj = SSLObject(sslobj, owner=self,
814 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000815 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000816 timeout = self.gettimeout()
817 if timeout == 0.0:
818 # non-blocking
819 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000820 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000821
Christian Heimes1aa9a752013-12-02 02:41:19 +0100822 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000823 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100824 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200825
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100826 @property
827 def context(self):
828 return self._context
829
830 @context.setter
831 def context(self, ctx):
832 self._context = ctx
833 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000834
Christian Heimes99a65702016-09-10 23:44:53 +0200835 @property
836 def session(self):
837 """The SSLSession for client socket."""
838 if self._sslobj is not None:
839 return self._sslobj.session
840
841 @session.setter
842 def session(self, session):
843 self._session = session
844 if self._sslobj is not None:
845 self._sslobj.session = session
846
847 @property
848 def session_reused(self):
849 """Was the client session reused during handshake"""
850 if self._sslobj is not None:
851 return self._sslobj.session_reused
852
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000853 def dup(self):
854 raise NotImplemented("Can't dup() %s instances" %
855 self.__class__.__name__)
856
Bill Janssen6e027db2007-11-15 22:23:56 +0000857 def _checkClosed(self, msg=None):
858 # raise an exception here if you wish to check for spurious closes
859 pass
860
Antoine Pitrou242db722013-05-01 20:52:07 +0200861 def _check_connected(self):
862 if not self._connected:
863 # getpeername() will raise ENOTCONN if the socket is really
864 # not connected; note that we can be connected even without
865 # _connected being set, e.g. if connect() first returned
866 # EAGAIN.
867 self.getpeername()
868
Martin Panterf6b1d662016-03-28 00:22:09 +0000869 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000870 """Read up to LEN bytes and return them.
871 Return zero-length string on EOF."""
872
Bill Janssen6e027db2007-11-15 22:23:56 +0000873 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200874 if not self._sslobj:
875 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000876 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200877 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000878 except SSLError as x:
879 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000880 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000881 return 0
882 else:
883 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000884 else:
885 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000886
887 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000888 """Write DATA to the underlying SSL channel. Returns
889 number of bytes of DATA actually transmitted."""
890
Bill Janssen6e027db2007-11-15 22:23:56 +0000891 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200892 if not self._sslobj:
893 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000894 return self._sslobj.write(data)
895
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000897 """Returns a formatted version of the data in the
898 certificate provided by the other end of the SSL channel.
899 Return None if no certificate was provided, {} if a
900 certificate was provided, but not validated."""
901
Bill Janssen6e027db2007-11-15 22:23:56 +0000902 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200903 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100906 def selected_npn_protocol(self):
907 self._checkClosed()
908 if not self._sslobj or not _ssl.HAS_NPN:
909 return None
910 else:
911 return self._sslobj.selected_npn_protocol()
912
Benjamin Petersoncca27322015-01-23 16:35:37 -0500913 def selected_alpn_protocol(self):
914 self._checkClosed()
915 if not self._sslobj or not _ssl.HAS_ALPN:
916 return None
917 else:
918 return self._sslobj.selected_alpn_protocol()
919
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000920 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000921 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922 if not self._sslobj:
923 return None
924 else:
925 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000926
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600927 def shared_ciphers(self):
928 self._checkClosed()
929 if not self._sslobj:
930 return None
931 return self._sslobj.shared_ciphers()
932
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100933 def compression(self):
934 self._checkClosed()
935 if not self._sslobj:
936 return None
937 else:
938 return self._sslobj.compression()
939
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000940 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000941 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000942 if self._sslobj:
943 if flags != 0:
944 raise ValueError(
945 "non-zero flags not allowed in calls to send() on %s" %
946 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200947 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000948 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100949 return super().send(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000950
Antoine Pitroua468adc2010-09-14 14:43:44 +0000951 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000952 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000953 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000954 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000955 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000956 elif addr is None:
Mads Jensen746cc752018-01-27 13:34:28 +0100957 return super().sendto(data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000958 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100959 return super().sendto(data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000960
Nick Coghlan513886a2011-08-28 00:00:27 +1000961 def sendmsg(self, *args, **kwargs):
962 # Ensure programs don't send data unencrypted if they try to
963 # use this method.
964 raise NotImplementedError("sendmsg not allowed on instances of %s" %
965 self.__class__)
966
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000967 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000968 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000969 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000970 if flags != 0:
971 raise ValueError(
972 "non-zero flags not allowed in calls to sendall() on %s" %
973 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000974 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700975 with memoryview(data) as view, view.cast("B") as byte_view:
976 amount = len(byte_view)
977 while count < amount:
978 v = self.send(byte_view[count:])
979 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000980 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100981 return super().sendall(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200983 def sendfile(self, file, offset=0, count=None):
984 """Send a file, possibly by using os.sendfile() if this is a
985 clear-text socket. Return the total number of bytes sent.
986 """
987 if self._sslobj is None:
988 # os.sendfile() works with plain sockets only
989 return super().sendfile(file, offset, count)
990 else:
991 return self._sendfile_use_send(file, offset, count)
992
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000993 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000994 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000995 if self._sslobj:
996 if flags != 0:
997 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000998 "non-zero flags not allowed in calls to recv() on %s" %
999 self.__class__)
1000 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001001 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001002 return super().recv(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001003
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001004 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001005 self._checkClosed()
1006 if buffer and (nbytes is None):
1007 nbytes = len(buffer)
1008 elif nbytes is None:
1009 nbytes = 1024
1010 if self._sslobj:
1011 if flags != 0:
1012 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001013 "non-zero flags not allowed in calls to recv_into() on %s" %
1014 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001015 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001016 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001017 return super().recv_into(buffer, nbytes, flags)
Bill Janssen6e027db2007-11-15 22:23:56 +00001018
Antoine Pitroua468adc2010-09-14 14:43:44 +00001019 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001020 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001021 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001022 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001023 self.__class__)
1024 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001025 return super().recvfrom(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001026
Bill Janssen58afe4c2008-09-08 16:45:19 +00001027 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1028 self._checkClosed()
1029 if self._sslobj:
1030 raise ValueError("recvfrom_into not allowed on instances of %s" %
1031 self.__class__)
1032 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001033 return super().recvfrom_into(buffer, nbytes, flags)
Bill Janssen58afe4c2008-09-08 16:45:19 +00001034
Nick Coghlan513886a2011-08-28 00:00:27 +10001035 def recvmsg(self, *args, **kwargs):
1036 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1037 self.__class__)
1038
1039 def recvmsg_into(self, *args, **kwargs):
1040 raise NotImplementedError("recvmsg_into not allowed on instances of "
1041 "%s" % self.__class__)
1042
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001043 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001044 self._checkClosed()
1045 if self._sslobj:
1046 return self._sslobj.pending()
1047 else:
1048 return 0
1049
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001050 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001051 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001053 super().shutdown(how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001054
Ezio Melottidc55e672010-01-18 09:15:14 +00001055 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001056 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001057 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001058 self._sslobj = None
1059 return s
1060 else:
1061 raise ValueError("No SSL wrapper around " + str(self))
1062
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001063 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001065 super()._real_close()
Bill Janssen6e027db2007-11-15 22:23:56 +00001066
Bill Janssen48dc27c2007-12-05 03:38:10 +00001067 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001068 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001069 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001070 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001071 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001072 if timeout == 0.0 and block:
1073 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001074 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001075 finally:
1076 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001077
Antoine Pitroub4410db2011-05-18 18:51:06 +02001078 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001079 if self.server_side:
1080 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001081 # Here we assume that the socket is client-side, and not
1082 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001083 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001085 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001086 self._sslobj = SSLObject(sslobj, owner=self,
1087 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001088 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001089 if connect_ex:
Mads Jensen746cc752018-01-27 13:34:28 +01001090 rc = super().connect_ex(addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001091 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001092 rc = None
Mads Jensen746cc752018-01-27 13:34:28 +01001093 super().connect(addr)
Antoine Pitroub4410db2011-05-18 18:51:06 +02001094 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001095 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001096 if self.do_handshake_on_connect:
1097 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001098 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001099 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001100 self._sslobj = None
1101 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001102
1103 def connect(self, addr):
1104 """Connects to remote ADDR, and then wraps the connection in
1105 an SSL channel."""
1106 self._real_connect(addr, False)
1107
1108 def connect_ex(self, addr):
1109 """Connects to remote ADDR, and then wraps the connection in
1110 an SSL channel."""
1111 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001112
1113 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001114 """Accepts a new connection from a remote client, and returns
1115 a tuple containing that new connection wrapped with a server-side
1116 SSL channel, and the address of the remote client."""
1117
Mads Jensen746cc752018-01-27 13:34:28 +01001118 newsock, addr = super().accept()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001119 newsock = self.context.wrap_socket(newsock,
1120 do_handshake_on_connect=self.do_handshake_on_connect,
1121 suppress_ragged_eofs=self.suppress_ragged_eofs,
1122 server_side=True)
1123 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124
Antoine Pitroud6494802011-07-21 01:11:30 +02001125 def get_channel_binding(self, cb_type="tls-unique"):
1126 """Get channel binding data for current connection. Raise ValueError
1127 if the requested `cb_type` is not supported. Return bytes of the data
1128 or None if the data is not available (e.g. before the handshake).
1129 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001130 if self._sslobj is None:
1131 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001132 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001133
Antoine Pitrou47e40422014-09-04 21:00:10 +02001134 def version(self):
1135 """
1136 Return a string identifying the protocol version used by the
1137 current SSL channel, or None if there is no established channel.
1138 """
1139 if self._sslobj is None:
1140 return None
1141 return self._sslobj.version()
1142
Bill Janssen54cc54c2007-12-14 22:08:56 +00001143
Christian Heimes4df60f12017-09-15 20:26:05 +02001144# Python does not support forward declaration of types.
1145SSLContext.sslsocket_class = SSLSocket
1146SSLContext.sslobject_class = SSLObject
1147
1148
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149def wrap_socket(sock, keyfile=None, certfile=None,
1150 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001151 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001152 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001153 suppress_ragged_eofs=True,
1154 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001155 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001156 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001157 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001158 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001159 suppress_ragged_eofs=suppress_ragged_eofs,
1160 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161
Thomas Woutersed03b412007-08-28 21:37:11 +00001162# some utility functions
1163
1164def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001165 """Return the time in seconds since the Epoch, given the timestring
1166 representing the "notBefore" or "notAfter" date from a certificate
1167 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001168
Antoine Pitrouc695c952014-04-28 20:57:36 +02001169 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1170
1171 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1172 UTC should be specified as GMT (see ASN1_TIME_print())
1173 """
1174 from time import strptime
1175 from calendar import timegm
1176
1177 months = (
1178 "Jan","Feb","Mar","Apr","May","Jun",
1179 "Jul","Aug","Sep","Oct","Nov","Dec"
1180 )
1181 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1182 try:
1183 month_number = months.index(cert_time[:3].title()) + 1
1184 except ValueError:
1185 raise ValueError('time data %r does not match '
1186 'format "%%b%s"' % (cert_time, time_format))
1187 else:
1188 # found valid month
1189 tt = strptime(cert_time[3:], time_format)
1190 # return an integer, the previous mktime()-based implementation
1191 # returned a float (fractional seconds are always zero here).
1192 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001193
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1195PEM_FOOTER = "-----END CERTIFICATE-----"
1196
1197def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198 """Takes a certificate in binary DER format and returns the
1199 PEM version of it as a string."""
1200
Bill Janssen6e027db2007-11-15 22:23:56 +00001201 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001202 ss = [PEM_HEADER]
1203 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1204 ss.append(PEM_FOOTER + '\n')
1205 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206
1207def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208 """Takes a certificate in ASCII PEM format and returns the
1209 DER-encoded version of it as a byte sequence"""
1210
1211 if not pem_cert_string.startswith(PEM_HEADER):
1212 raise ValueError("Invalid PEM encoding; must start with %s"
1213 % PEM_HEADER)
1214 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1215 raise ValueError("Invalid PEM encoding; must end with %s"
1216 % PEM_FOOTER)
1217 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001218 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219
Christian Heimes598894f2016-09-05 23:19:05 +02001220def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221 """Retrieve the certificate from the server at the specified address,
1222 and return it as a PEM-encoded string.
1223 If 'ca_certs' is specified, validate the server cert against it.
1224 If 'ssl_version' is specified, use it in the connection attempt."""
1225
1226 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001227 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228 cert_reqs = CERT_REQUIRED
1229 else:
1230 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001231 context = _create_stdlib_context(ssl_version,
1232 cert_reqs=cert_reqs,
1233 cafile=ca_certs)
1234 with create_connection(addr) as sock:
1235 with context.wrap_socket(sock) as sslsock:
1236 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237 return DER_cert_to_PEM_cert(dercert)
1238
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001239def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001240 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')