blob: ecdbb70762839ab3b10805fdd9958cded3301a0d [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
Christian Heimes46bebee2013-06-09 19:03:31 +020093import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020094import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010095from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020096from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +000097
98import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000099
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000100from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200101from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200102from _ssl import (
103 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700104 SSLSyscallError, SSLEOFError, SSLCertVerificationError
Antoine Pitrou41032a62011-10-27 23:56:55 +0200105 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100106from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100107from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
108try:
109 from _ssl import RAND_egd
110except ImportError:
111 # LibreSSL does not provide RAND_egd
112 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100113
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100114
Christian Heimescb5b68a2017-09-07 18:07:00 -0700115from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
Christian Heimes892d66e2018-01-29 14:10:18 +0100116from _ssl import _DEFAULT_CIPHERS
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200117from _ssl import _OPENSSL_API_VERSION
118
Christian Heimes3aeacad2016-09-10 00:19:35 +0200119
Ethan Furman24e837f2015-03-18 17:27:57 -0700120_IntEnum._convert(
Christian Heimes3aeacad2016-09-10 00:19:35 +0200121 '_SSLMethod', __name__,
122 lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
123 source=_ssl)
124
125_IntFlag._convert(
126 'Options', __name__,
127 lambda name: name.startswith('OP_'),
128 source=_ssl)
129
130_IntEnum._convert(
131 'AlertDescription', __name__,
132 lambda name: name.startswith('ALERT_DESCRIPTION_'),
133 source=_ssl)
134
135_IntEnum._convert(
136 'SSLErrorNumber', __name__,
137 lambda name: name.startswith('SSL_ERROR_'),
138 source=_ssl)
139
140_IntFlag._convert(
141 'VerifyFlags', __name__,
142 lambda name: name.startswith('VERIFY_'),
143 source=_ssl)
144
145_IntEnum._convert(
146 'VerifyMode', __name__,
147 lambda name: name.startswith('CERT_'),
148 source=_ssl)
149
Christian Heimes598894f2016-09-05 23:19:05 +0200150PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200151_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
152
Christian Heimes3aeacad2016-09-10 00:19:35 +0200153_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
154
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100155
Christian Heimes46bebee2013-06-09 19:03:31 +0200156if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100157 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200158
Antoine Pitrou15399c32011-04-28 19:23:55 +0200159from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100160from socket import SOL_SOCKET, SO_TYPE
Christian Heimesaef12832018-02-24 14:35:56 +0100161import socket as _socket
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000163import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700164import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000165
Andrew Svetlov0832af62012-12-18 23:10:48 +0200166
167socket_error = OSError # keep that public name in module namespace
168
Antoine Pitroud6494802011-07-21 01:11:30 +0200169if _ssl.HAS_TLS_UNIQUE:
170 CHANNEL_BINDING_TYPES = ['tls-unique']
171else:
172 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000173
Christian Heimes61d478c2018-01-27 15:51:38 +0100174HAS_NEVER_CHECK_COMMON_NAME = hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT')
175
Christian Heimes03d13c02016-09-06 20:06:47 +0200176
Christian Heimes892d66e2018-01-29 14:10:18 +0100177_RESTRICTED_SERVER_CIPHERS = _DEFAULT_CIPHERS
Christian Heimes4c05b472013-11-23 15:58:30 +0100178
Christian Heimes61d478c2018-01-27 15:51:38 +0100179CertificateError = SSLCertVerificationError
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000180
181
Mandeep Singhede2ac92017-11-27 04:01:27 +0530182def _dnsname_match(dn, hostname):
Georg Brandl72c98d32013-10-27 07:16:53 +0100183 """Matching according to RFC 6125, section 6.4.3
184
Christian Heimesaef12832018-02-24 14:35:56 +0100185 - Hostnames are compared lower case.
186 - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE).
187 - Partial wildcards like 'www*.example.org', multiple wildcards, sole
188 wildcard or wildcards in labels other then the left-most label are not
189 supported and a CertificateError is raised.
190 - A wildcard must match at least one character.
Georg Brandl72c98d32013-10-27 07:16:53 +0100191 """
Georg Brandl72c98d32013-10-27 07:16:53 +0100192 if not dn:
193 return False
194
Christian Heimesaef12832018-02-24 14:35:56 +0100195 wildcards = dn.count('*')
Georg Brandl72c98d32013-10-27 07:16:53 +0100196 # speed up common case w/o wildcards
197 if not wildcards:
198 return dn.lower() == hostname.lower()
199
Christian Heimesaef12832018-02-24 14:35:56 +0100200 if wildcards > 1:
201 raise CertificateError(
202 "too many wildcards in certificate DNS name: {!r}.".format(dn))
Georg Brandl72c98d32013-10-27 07:16:53 +0100203
Christian Heimesaef12832018-02-24 14:35:56 +0100204 dn_leftmost, sep, dn_remainder = dn.partition('.')
Georg Brandl72c98d32013-10-27 07:16:53 +0100205
Christian Heimesaef12832018-02-24 14:35:56 +0100206 if '*' in dn_remainder:
207 # Only match wildcard in leftmost segment.
208 raise CertificateError(
209 "wildcard can only be present in the leftmost label: "
210 "{!r}.".format(dn))
211
212 if not sep:
213 # no right side
214 raise CertificateError(
215 "sole wildcard without additional labels are not support: "
216 "{!r}.".format(dn))
217
218 if dn_leftmost != '*':
219 # no partial wildcard matching
220 raise CertificateError(
221 "partial wildcards in leftmost label are not supported: "
222 "{!r}.".format(dn))
223
224 hostname_leftmost, sep, hostname_remainder = hostname.partition('.')
225 if not hostname_leftmost or not sep:
226 # wildcard must match at least one char
227 return False
228 return dn_remainder.lower() == hostname_remainder.lower()
229
230
231def _inet_paton(ipname):
232 """Try to convert an IP address to packed binary form
233
234 Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6
235 support.
236 """
237 # inet_aton() also accepts strings like '1'
238 if ipname.count('.') == 3:
239 try:
240 return _socket.inet_aton(ipname)
241 except OSError:
242 pass
243
244 try:
245 return _socket.inet_pton(_socket.AF_INET6, ipname)
246 except OSError:
247 raise ValueError("{!r} is neither an IPv4 nor an IP6 "
248 "address.".format(ipname))
249 except AttributeError:
250 # AF_INET6 not available
251 pass
252
253 raise ValueError("{!r} is not an IPv4 address.".format(ipname))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000254
255
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100256def _ipaddress_match(ipname, host_ip):
257 """Exact matching of IP addresses.
258
259 RFC 6125 explicitly doesn't define an algorithm for this
260 (section 1.7.2 - "Out of Scope").
261 """
262 # OpenSSL may add a trailing newline to a subjectAltName's IP address
Christian Heimesaef12832018-02-24 14:35:56 +0100263 ip = _inet_paton(ipname.rstrip())
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100264 return ip == host_ip
265
266
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000267def match_hostname(cert, hostname):
268 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100269 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
Christian Heimesaef12832018-02-24 14:35:56 +0100270 rules are followed.
271
272 The function matches IP addresses rather than dNSNames if hostname is a
273 valid ipaddress string. IPv4 addresses are supported on all platforms.
274 IPv6 addresses are supported on platforms with IPv6 support (AF_INET6
275 and inet_pton).
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000276
277 CertificateError is raised on failure. On success, the function
278 returns nothing.
279 """
280 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100281 raise ValueError("empty or no certificate, match_hostname needs a "
282 "SSL socket or SSL context with either "
283 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100284 try:
Christian Heimesaef12832018-02-24 14:35:56 +0100285 host_ip = _inet_paton(hostname)
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100286 except ValueError:
287 # Not an IP address (common case)
288 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000289 dnsnames = []
290 san = cert.get('subjectAltName', ())
291 for key, value in san:
292 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100293 if host_ip is None and _dnsname_match(value, hostname):
294 return
295 dnsnames.append(value)
296 elif key == 'IP Address':
297 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000298 return
299 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200300 if not dnsnames:
301 # The subject is only checked when there is no dNSName entry
302 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000303 for sub in cert.get('subject', ()):
304 for key, value in sub:
305 # XXX according to RFC 2818, the most specific Common Name
306 # must be used.
307 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100308 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000309 return
310 dnsnames.append(value)
311 if len(dnsnames) > 1:
312 raise CertificateError("hostname %r "
313 "doesn't match either of %s"
314 % (hostname, ', '.join(map(repr, dnsnames))))
315 elif len(dnsnames) == 1:
316 raise CertificateError("hostname %r "
317 "doesn't match %r"
318 % (hostname, dnsnames[0]))
319 else:
320 raise CertificateError("no appropriate commonName or "
321 "subjectAltName fields were found")
322
323
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100324DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200325 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
326 "openssl_capath")
327
328def get_default_verify_paths():
329 """Return paths to default cafile and capath.
330 """
331 parts = _ssl.get_default_verify_paths()
332
333 # environment vars shadow paths
334 cafile = os.environ.get(parts[0], parts[1])
335 capath = os.environ.get(parts[2], parts[3])
336
337 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
338 capath if os.path.isdir(capath) else None,
339 *parts)
340
341
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100342class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
343 """ASN.1 object identifier lookup
344 """
345 __slots__ = ()
346
347 def __new__(cls, oid):
348 return super().__new__(cls, *_txt2obj(oid, name=False))
349
350 @classmethod
351 def fromnid(cls, nid):
352 """Create _ASN1Object from OpenSSL numeric ID
353 """
354 return super().__new__(cls, *_nid2obj(nid))
355
356 @classmethod
357 def fromname(cls, name):
358 """Create _ASN1Object from short name, long name or OID
359 """
360 return super().__new__(cls, *_txt2obj(name, name=True))
361
362
Christian Heimes72d28502013-11-23 13:56:58 +0100363class Purpose(_ASN1Object, _Enum):
364 """SSLContext purpose flags with X509v3 Extended Key Usage objects
365 """
366 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
367 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
368
369
Antoine Pitrou152efa22010-05-16 18:19:27 +0000370class SSLContext(_SSLContext):
371 """An SSLContext holds various SSL-related configuration options and
372 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100373 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000374
Christian Heimes4df60f12017-09-15 20:26:05 +0200375 sslsocket_class = None # SSLSocket is assigned later.
376 sslobject_class = None # SSLObject is assigned later.
377
Christian Heimes598894f2016-09-05 23:19:05 +0200378 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100379 self = _SSLContext.__new__(cls, protocol)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100380 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381
Christian Heimes11a14932018-02-24 02:35:08 +0100382 def _encode_hostname(self, hostname):
383 if hostname is None:
384 return None
385 elif isinstance(hostname, str):
386 return hostname.encode('idna').decode('ascii')
387 else:
388 return hostname.decode('ascii')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000389
390 def wrap_socket(self, sock, server_side=False,
391 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000392 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200393 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100394 # SSLSocket class handles server_hostname encoding before it calls
395 # ctx._wrap_socket()
Christian Heimes4df60f12017-09-15 20:26:05 +0200396 return self.sslsocket_class(
397 sock=sock,
398 server_side=server_side,
399 do_handshake_on_connect=do_handshake_on_connect,
400 suppress_ragged_eofs=suppress_ragged_eofs,
401 server_hostname=server_hostname,
402 _context=self,
403 _session=session
404 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000405
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200406 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200407 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100408 # Need to encode server_hostname here because _wrap_bio() can only
409 # handle ASCII str.
410 sslobj = self._wrap_bio(
411 incoming, outgoing, server_side=server_side,
412 server_hostname=self._encode_hostname(server_hostname)
413 )
Christian Heimes4df60f12017-09-15 20:26:05 +0200414 return self.sslobject_class(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200415
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100416 def set_npn_protocols(self, npn_protocols):
417 protos = bytearray()
418 for protocol in npn_protocols:
419 b = bytes(protocol, 'ascii')
420 if len(b) == 0 or len(b) > 255:
421 raise SSLError('NPN protocols must be 1 to 255 in length')
422 protos.append(len(b))
423 protos.extend(b)
424
425 self._set_npn_protocols(protos)
426
Christian Heimes11a14932018-02-24 02:35:08 +0100427 def set_servername_callback(self, server_name_callback):
428 if server_name_callback is None:
429 self.sni_callback = None
430 else:
431 if not callable(server_name_callback):
432 raise TypeError("not a callable object")
433
434 def shim_cb(sslobj, servername, sslctx):
435 servername = self._encode_hostname(servername)
436 return server_name_callback(sslobj, servername, sslctx)
437
438 self.sni_callback = shim_cb
439
Benjamin Petersoncca27322015-01-23 16:35:37 -0500440 def set_alpn_protocols(self, alpn_protocols):
441 protos = bytearray()
442 for protocol in alpn_protocols:
443 b = bytes(protocol, 'ascii')
444 if len(b) == 0 or len(b) > 255:
445 raise SSLError('ALPN protocols must be 1 to 255 in length')
446 protos.append(len(b))
447 protos.extend(b)
448
449 self._set_alpn_protocols(protos)
450
Christian Heimes72d28502013-11-23 13:56:58 +0100451 def _load_windows_store_certs(self, storename, purpose):
452 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700453 try:
454 for cert, encoding, trust in enum_certificates(storename):
455 # CA certs are never PKCS#7 encoded
456 if encoding == "x509_asn":
457 if trust is True or purpose.oid in trust:
458 certs.extend(cert)
459 except PermissionError:
460 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700461 if certs:
462 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100463 return certs
464
465 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
466 if not isinstance(purpose, _ASN1Object):
467 raise TypeError(purpose)
468 if sys.platform == "win32":
469 for storename in self._windows_cert_stores:
470 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400471 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100472
Christian Heimes3aeacad2016-09-10 00:19:35 +0200473 @property
474 def options(self):
475 return Options(super().options)
476
477 @options.setter
478 def options(self, value):
479 super(SSLContext, SSLContext).options.__set__(self, value)
480
Christian Heimes61d478c2018-01-27 15:51:38 +0100481 if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
482 @property
483 def hostname_checks_common_name(self):
484 ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
485 return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
486
487 @hostname_checks_common_name.setter
488 def hostname_checks_common_name(self, value):
489 if value:
490 self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
491 else:
492 self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
493 else:
494 @property
495 def hostname_checks_common_name(self):
496 return True
497
Christian Heimes3aeacad2016-09-10 00:19:35 +0200498 @property
Christian Heimes11a14932018-02-24 02:35:08 +0100499 def protocol(self):
500 return _SSLMethod(super().protocol)
501
502 @property
Christian Heimes3aeacad2016-09-10 00:19:35 +0200503 def verify_flags(self):
504 return VerifyFlags(super().verify_flags)
505
506 @verify_flags.setter
507 def verify_flags(self, value):
508 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
509
510 @property
511 def verify_mode(self):
512 value = super().verify_mode
513 try:
514 return VerifyMode(value)
515 except ValueError:
516 return value
517
518 @verify_mode.setter
519 def verify_mode(self, value):
520 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
521
Antoine Pitrou152efa22010-05-16 18:19:27 +0000522
Christian Heimes4c05b472013-11-23 15:58:30 +0100523def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
524 capath=None, cadata=None):
525 """Create a SSLContext object with default settings.
526
527 NOTE: The protocol and settings may change anytime without prior
528 deprecation. The values represent a fair balance between maximum
529 compatibility and security.
530 """
531 if not isinstance(purpose, _ASN1Object):
532 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400533
Christian Heimes358cfd42016-09-10 22:43:48 +0200534 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
535 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
536 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200537 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400538
Christian Heimes4c05b472013-11-23 15:58:30 +0100539 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400540 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100541 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100542 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400543
Christian Heimes4c05b472013-11-23 15:58:30 +0100544 if cafile or capath or cadata:
545 context.load_verify_locations(cafile, capath, cadata)
546 elif context.verify_mode != CERT_NONE:
547 # no explicit cafile, capath or cadata but the verify mode is
548 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
549 # root CA certificates for the given purpose. This may fail silently.
550 context.load_default_certs(purpose)
551 return context
552
Christian Heimesa170fa12017-09-15 20:27:30 +0200553def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100554 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100555 certfile=None, keyfile=None,
556 cafile=None, capath=None, cadata=None):
557 """Create a SSLContext object for Python stdlib modules
558
559 All Python stdlib modules shall use this function to create SSLContext
560 objects in order to keep common settings in one place. The configuration
561 is less restrict than create_default_context()'s to increase backward
562 compatibility.
563 """
564 if not isinstance(purpose, _ASN1Object):
565 raise TypeError(purpose)
566
Christian Heimes358cfd42016-09-10 22:43:48 +0200567 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
568 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
569 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100570 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100571
Christian Heimesa170fa12017-09-15 20:27:30 +0200572 if not check_hostname:
573 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100574 if cert_reqs is not None:
575 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200576 if check_hostname:
577 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100578
579 if keyfile and not certfile:
580 raise ValueError("certfile must be specified")
581 if certfile or keyfile:
582 context.load_cert_chain(certfile, keyfile)
583
584 # load CA root certs
585 if cafile or capath or cadata:
586 context.load_verify_locations(cafile, capath, cadata)
587 elif context.verify_mode != CERT_NONE:
588 # no explicit cafile, capath or cadata but the verify mode is
589 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
590 # root CA certificates for the given purpose. This may fail silently.
591 context.load_default_certs(purpose)
592
593 return context
594
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500595# Used by http.client if no context is explicitly passed.
596_create_default_https_context = create_default_context
597
598
599# Backwards compatibility alias, even though it's not a public name.
600_create_stdlib_context = _create_unverified_context
601
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200602
603class SSLObject:
604 """This class implements an interface on top of a low-level SSL object as
605 implemented by OpenSSL. This object captures the state of an SSL connection
606 but does not provide any network IO itself. IO needs to be performed
607 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
608
609 This class does not have a public constructor. Instances are returned by
610 ``SSLContext.wrap_bio``. This class is typically used by framework authors
611 that want to implement asynchronous IO for SSL through memory buffers.
612
613 When compared to ``SSLSocket``, this object lacks the following features:
614
615 * Any form of network IO incluging methods such as ``recv`` and ``send``.
616 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
617 """
618
Christian Heimes99a65702016-09-10 23:44:53 +0200619 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200620 self._sslobj = sslobj
621 # Note: _sslobj takes a weak reference to owner
622 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200623 if session is not None:
624 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200625
626 @property
627 def context(self):
628 """The SSLContext that is currently in use."""
629 return self._sslobj.context
630
631 @context.setter
632 def context(self, ctx):
633 self._sslobj.context = ctx
634
635 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200636 def session(self):
637 """The SSLSession for client socket."""
638 return self._sslobj.session
639
640 @session.setter
641 def session(self, session):
642 self._sslobj.session = session
643
644 @property
645 def session_reused(self):
646 """Was the client session reused during handshake"""
647 return self._sslobj.session_reused
648
649 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200650 def server_side(self):
651 """Whether this is a server-side socket."""
652 return self._sslobj.server_side
653
654 @property
655 def server_hostname(self):
656 """The currently set server hostname (for SNI), or ``None`` if no
657 server hostame is set."""
658 return self._sslobj.server_hostname
659
Martin Panterf6b1d662016-03-28 00:22:09 +0000660 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 """Read up to 'len' bytes from the SSL object and return them.
662
663 If 'buffer' is provided, read into this buffer and return the number of
664 bytes read.
665 """
666 if buffer is not None:
667 v = self._sslobj.read(len, buffer)
668 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000669 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200670 return v
671
672 def write(self, data):
673 """Write 'data' to the SSL object and return the number of bytes
674 written.
675
676 The 'data' argument must support the buffer interface.
677 """
678 return self._sslobj.write(data)
679
680 def getpeercert(self, binary_form=False):
681 """Returns a formatted version of the data in the certificate provided
682 by the other end of the SSL channel.
683
684 Return None if no certificate was provided, {} if a certificate was
685 provided, but not validated.
686 """
687 return self._sslobj.peer_certificate(binary_form)
688
689 def selected_npn_protocol(self):
690 """Return the currently selected NPN protocol as a string, or ``None``
691 if a next protocol was not negotiated or if NPN is not supported by one
692 of the peers."""
693 if _ssl.HAS_NPN:
694 return self._sslobj.selected_npn_protocol()
695
Benjamin Petersoncca27322015-01-23 16:35:37 -0500696 def selected_alpn_protocol(self):
697 """Return the currently selected ALPN protocol as a string, or ``None``
698 if a next protocol was not negotiated or if ALPN is not supported by one
699 of the peers."""
700 if _ssl.HAS_ALPN:
701 return self._sslobj.selected_alpn_protocol()
702
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200703 def cipher(self):
704 """Return the currently selected cipher as a 3-tuple ``(name,
705 ssl_version, secret_bits)``."""
706 return self._sslobj.cipher()
707
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600708 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500709 """Return a list of ciphers shared by the client during the handshake or
710 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600711 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600712 return self._sslobj.shared_ciphers()
713
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200714 def compression(self):
715 """Return the current compression algorithm in use, or ``None`` if
716 compression was not negotiated or not supported by one of the peers."""
717 return self._sslobj.compression()
718
719 def pending(self):
720 """Return the number of bytes that can be read immediately."""
721 return self._sslobj.pending()
722
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200723 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200724 """Start the SSL/TLS handshake."""
725 self._sslobj.do_handshake()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200726
727 def unwrap(self):
728 """Start the SSL shutdown handshake."""
729 return self._sslobj.shutdown()
730
731 def get_channel_binding(self, cb_type="tls-unique"):
732 """Get channel binding data for current connection. Raise ValueError
733 if the requested `cb_type` is not supported. Return bytes of the data
734 or None if the data is not available (e.g. before the handshake)."""
735 if cb_type not in CHANNEL_BINDING_TYPES:
736 raise ValueError("Unsupported channel binding type")
737 if cb_type != "tls-unique":
738 raise NotImplementedError(
739 "{0} channel binding type not implemented"
740 .format(cb_type))
741 return self._sslobj.tls_unique_cb()
742
743 def version(self):
744 """Return a string identifying the protocol version used by the
745 current SSL channel. """
746 return self._sslobj.version()
747
748
Antoine Pitrou152efa22010-05-16 18:19:27 +0000749class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000750 """This class implements a subtype of socket.socket that wraps
751 the underlying OS socket in an SSL context when necessary, and
752 provides read and write methods over that channel."""
753
Bill Janssen6e027db2007-11-15 22:23:56 +0000754 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000755 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200756 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000757 do_handshake_on_connect=True,
758 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100759 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000760 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200761 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000762
Antoine Pitrou152efa22010-05-16 18:19:27 +0000763 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100764 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000765 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000766 if server_side and not certfile:
767 raise ValueError("certfile must be specified for server-side "
768 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000769 if keyfile and not certfile:
770 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000771 if certfile and not keyfile:
772 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100773 self._context = SSLContext(ssl_version)
774 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000775 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100776 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000777 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100778 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100779 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100780 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000781 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100782 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000783 self.keyfile = keyfile
784 self.certfile = certfile
785 self.cert_reqs = cert_reqs
786 self.ssl_version = ssl_version
787 self.ca_certs = ca_certs
788 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100789 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
790 # mixed in.
791 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
792 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200793 if server_side:
794 if server_hostname:
795 raise ValueError("server_hostname can only be specified "
796 "in client mode")
797 if _session is not None:
798 raise ValueError("session can only be specified in "
799 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100800 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600801 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200802 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000803 self.server_side = server_side
Christian Heimes11a14932018-02-24 02:35:08 +0100804 self.server_hostname = self._context._encode_hostname(server_hostname)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000805 self.do_handshake_on_connect = do_handshake_on_connect
806 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000807 if sock is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100808 super().__init__(family=sock.family,
809 type=sock.type,
810 proto=sock.proto,
811 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000812 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000813 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000814 elif fileno is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100815 super().__init__(fileno=fileno)
Bill Janssen6e027db2007-11-15 22:23:56 +0000816 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100817 super().__init__(family=family, type=type, proto=proto)
Bill Janssen6e027db2007-11-15 22:23:56 +0000818
Antoine Pitrou242db722013-05-01 20:52:07 +0200819 # See if we are connected
820 try:
821 self.getpeername()
822 except OSError as e:
823 if e.errno != errno.ENOTCONN:
824 raise
825 connected = False
826 else:
827 connected = True
828
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000829 self._closed = False
830 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000831 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000832 if connected:
833 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000834 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200835 sslobj = self._context._wrap_socket(self, server_side,
Christian Heimes11a14932018-02-24 02:35:08 +0100836 self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200837 self._sslobj = SSLObject(sslobj, owner=self,
838 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000839 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000840 timeout = self.gettimeout()
841 if timeout == 0.0:
842 # non-blocking
843 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000844 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000845
Christian Heimes1aa9a752013-12-02 02:41:19 +0100846 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000847 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100848 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200849
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100850 @property
851 def context(self):
852 return self._context
853
854 @context.setter
855 def context(self, ctx):
856 self._context = ctx
857 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000858
Christian Heimes99a65702016-09-10 23:44:53 +0200859 @property
860 def session(self):
861 """The SSLSession for client socket."""
862 if self._sslobj is not None:
863 return self._sslobj.session
864
865 @session.setter
866 def session(self, session):
867 self._session = session
868 if self._sslobj is not None:
869 self._sslobj.session = session
870
871 @property
872 def session_reused(self):
873 """Was the client session reused during handshake"""
874 if self._sslobj is not None:
875 return self._sslobj.session_reused
876
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000877 def dup(self):
878 raise NotImplemented("Can't dup() %s instances" %
879 self.__class__.__name__)
880
Bill Janssen6e027db2007-11-15 22:23:56 +0000881 def _checkClosed(self, msg=None):
882 # raise an exception here if you wish to check for spurious closes
883 pass
884
Antoine Pitrou242db722013-05-01 20:52:07 +0200885 def _check_connected(self):
886 if not self._connected:
887 # getpeername() will raise ENOTCONN if the socket is really
888 # not connected; note that we can be connected even without
889 # _connected being set, e.g. if connect() first returned
890 # EAGAIN.
891 self.getpeername()
892
Martin Panterf6b1d662016-03-28 00:22:09 +0000893 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000894 """Read up to LEN bytes and return them.
895 Return zero-length string on EOF."""
896
Bill Janssen6e027db2007-11-15 22:23:56 +0000897 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200898 if not self._sslobj:
899 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000900 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200901 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000902 except SSLError as x:
903 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000904 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000905 return 0
906 else:
907 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000908 else:
909 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000910
911 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000912 """Write DATA to the underlying SSL channel. Returns
913 number of bytes of DATA actually transmitted."""
914
Bill Janssen6e027db2007-11-15 22:23:56 +0000915 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200916 if not self._sslobj:
917 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000918 return self._sslobj.write(data)
919
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000921 """Returns a formatted version of the data in the
922 certificate provided by the other end of the SSL channel.
923 Return None if no certificate was provided, {} if a
924 certificate was provided, but not validated."""
925
Bill Janssen6e027db2007-11-15 22:23:56 +0000926 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200927 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200928 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100930 def selected_npn_protocol(self):
931 self._checkClosed()
932 if not self._sslobj or not _ssl.HAS_NPN:
933 return None
934 else:
935 return self._sslobj.selected_npn_protocol()
936
Benjamin Petersoncca27322015-01-23 16:35:37 -0500937 def selected_alpn_protocol(self):
938 self._checkClosed()
939 if not self._sslobj or not _ssl.HAS_ALPN:
940 return None
941 else:
942 return self._sslobj.selected_alpn_protocol()
943
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000944 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000945 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946 if not self._sslobj:
947 return None
948 else:
949 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000950
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600951 def shared_ciphers(self):
952 self._checkClosed()
953 if not self._sslobj:
954 return None
955 return self._sslobj.shared_ciphers()
956
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100957 def compression(self):
958 self._checkClosed()
959 if not self._sslobj:
960 return None
961 else:
962 return self._sslobj.compression()
963
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000964 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000965 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000966 if self._sslobj:
967 if flags != 0:
968 raise ValueError(
969 "non-zero flags not allowed in calls to send() on %s" %
970 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200971 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000972 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100973 return super().send(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000974
Antoine Pitroua468adc2010-09-14 14:43:44 +0000975 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000976 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000977 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000978 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000979 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000980 elif addr is None:
Mads Jensen746cc752018-01-27 13:34:28 +0100981 return super().sendto(data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000982 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100983 return super().sendto(data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000984
Nick Coghlan513886a2011-08-28 00:00:27 +1000985 def sendmsg(self, *args, **kwargs):
986 # Ensure programs don't send data unencrypted if they try to
987 # use this method.
988 raise NotImplementedError("sendmsg not allowed on instances of %s" %
989 self.__class__)
990
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000991 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000992 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000993 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000994 if flags != 0:
995 raise ValueError(
996 "non-zero flags not allowed in calls to sendall() on %s" %
997 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000998 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700999 with memoryview(data) as view, view.cast("B") as byte_view:
1000 amount = len(byte_view)
1001 while count < amount:
1002 v = self.send(byte_view[count:])
1003 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001004 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001005 return super().sendall(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001006
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001007 def sendfile(self, file, offset=0, count=None):
1008 """Send a file, possibly by using os.sendfile() if this is a
1009 clear-text socket. Return the total number of bytes sent.
1010 """
1011 if self._sslobj is None:
1012 # os.sendfile() works with plain sockets only
1013 return super().sendfile(file, offset, count)
1014 else:
1015 return self._sendfile_use_send(file, offset, count)
1016
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001017 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001018 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001019 if self._sslobj:
1020 if flags != 0:
1021 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +00001022 "non-zero flags not allowed in calls to recv() on %s" %
1023 self.__class__)
1024 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001025 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001026 return super().recv(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001027
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001028 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001029 self._checkClosed()
1030 if buffer and (nbytes is None):
1031 nbytes = len(buffer)
1032 elif nbytes is None:
1033 nbytes = 1024
1034 if self._sslobj:
1035 if flags != 0:
1036 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001037 "non-zero flags not allowed in calls to recv_into() on %s" %
1038 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001039 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001040 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001041 return super().recv_into(buffer, nbytes, flags)
Bill Janssen6e027db2007-11-15 22:23:56 +00001042
Antoine Pitroua468adc2010-09-14 14:43:44 +00001043 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001044 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001045 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001046 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001047 self.__class__)
1048 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001049 return super().recvfrom(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001050
Bill Janssen58afe4c2008-09-08 16:45:19 +00001051 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1052 self._checkClosed()
1053 if self._sslobj:
1054 raise ValueError("recvfrom_into not allowed on instances of %s" %
1055 self.__class__)
1056 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001057 return super().recvfrom_into(buffer, nbytes, flags)
Bill Janssen58afe4c2008-09-08 16:45:19 +00001058
Nick Coghlan513886a2011-08-28 00:00:27 +10001059 def recvmsg(self, *args, **kwargs):
1060 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1061 self.__class__)
1062
1063 def recvmsg_into(self, *args, **kwargs):
1064 raise NotImplementedError("recvmsg_into not allowed on instances of "
1065 "%s" % self.__class__)
1066
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001067 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001068 self._checkClosed()
1069 if self._sslobj:
1070 return self._sslobj.pending()
1071 else:
1072 return 0
1073
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001074 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001075 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001077 super().shutdown(how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001078
Ezio Melottidc55e672010-01-18 09:15:14 +00001079 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001080 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001081 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001082 self._sslobj = None
1083 return s
1084 else:
1085 raise ValueError("No SSL wrapper around " + str(self))
1086
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001087 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001089 super()._real_close()
Bill Janssen6e027db2007-11-15 22:23:56 +00001090
Bill Janssen48dc27c2007-12-05 03:38:10 +00001091 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001092 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001093 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001094 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001095 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001096 if timeout == 0.0 and block:
1097 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001098 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001099 finally:
1100 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001101
Antoine Pitroub4410db2011-05-18 18:51:06 +02001102 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001103 if self.server_side:
1104 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001105 # Here we assume that the socket is client-side, and not
1106 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001107 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001109 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001110 self._sslobj = SSLObject(sslobj, owner=self,
1111 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001112 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001113 if connect_ex:
Mads Jensen746cc752018-01-27 13:34:28 +01001114 rc = super().connect_ex(addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001115 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001116 rc = None
Mads Jensen746cc752018-01-27 13:34:28 +01001117 super().connect(addr)
Antoine Pitroub4410db2011-05-18 18:51:06 +02001118 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001119 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001120 if self.do_handshake_on_connect:
1121 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001122 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001123 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001124 self._sslobj = None
1125 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001126
1127 def connect(self, addr):
1128 """Connects to remote ADDR, and then wraps the connection in
1129 an SSL channel."""
1130 self._real_connect(addr, False)
1131
1132 def connect_ex(self, addr):
1133 """Connects to remote ADDR, and then wraps the connection in
1134 an SSL channel."""
1135 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001136
1137 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001138 """Accepts a new connection from a remote client, and returns
1139 a tuple containing that new connection wrapped with a server-side
1140 SSL channel, and the address of the remote client."""
1141
Mads Jensen746cc752018-01-27 13:34:28 +01001142 newsock, addr = super().accept()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001143 newsock = self.context.wrap_socket(newsock,
1144 do_handshake_on_connect=self.do_handshake_on_connect,
1145 suppress_ragged_eofs=self.suppress_ragged_eofs,
1146 server_side=True)
1147 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Antoine Pitroud6494802011-07-21 01:11:30 +02001149 def get_channel_binding(self, cb_type="tls-unique"):
1150 """Get channel binding data for current connection. Raise ValueError
1151 if the requested `cb_type` is not supported. Return bytes of the data
1152 or None if the data is not available (e.g. before the handshake).
1153 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001154 if self._sslobj is None:
1155 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001156 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001157
Antoine Pitrou47e40422014-09-04 21:00:10 +02001158 def version(self):
1159 """
1160 Return a string identifying the protocol version used by the
1161 current SSL channel, or None if there is no established channel.
1162 """
1163 if self._sslobj is None:
1164 return None
1165 return self._sslobj.version()
1166
Bill Janssen54cc54c2007-12-14 22:08:56 +00001167
Christian Heimes4df60f12017-09-15 20:26:05 +02001168# Python does not support forward declaration of types.
1169SSLContext.sslsocket_class = SSLSocket
1170SSLContext.sslobject_class = SSLObject
1171
1172
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173def wrap_socket(sock, keyfile=None, certfile=None,
1174 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001175 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001176 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001177 suppress_ragged_eofs=True,
1178 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001179 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001181 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001182 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001183 suppress_ragged_eofs=suppress_ragged_eofs,
1184 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001185
Thomas Woutersed03b412007-08-28 21:37:11 +00001186# some utility functions
1187
1188def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001189 """Return the time in seconds since the Epoch, given the timestring
1190 representing the "notBefore" or "notAfter" date from a certificate
1191 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001192
Antoine Pitrouc695c952014-04-28 20:57:36 +02001193 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1194
1195 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1196 UTC should be specified as GMT (see ASN1_TIME_print())
1197 """
1198 from time import strptime
1199 from calendar import timegm
1200
1201 months = (
1202 "Jan","Feb","Mar","Apr","May","Jun",
1203 "Jul","Aug","Sep","Oct","Nov","Dec"
1204 )
1205 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1206 try:
1207 month_number = months.index(cert_time[:3].title()) + 1
1208 except ValueError:
1209 raise ValueError('time data %r does not match '
1210 'format "%%b%s"' % (cert_time, time_format))
1211 else:
1212 # found valid month
1213 tt = strptime(cert_time[3:], time_format)
1214 # return an integer, the previous mktime()-based implementation
1215 # returned a float (fractional seconds are always zero here).
1216 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001217
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1219PEM_FOOTER = "-----END CERTIFICATE-----"
1220
1221def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222 """Takes a certificate in binary DER format and returns the
1223 PEM version of it as a string."""
1224
Bill Janssen6e027db2007-11-15 22:23:56 +00001225 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001226 ss = [PEM_HEADER]
1227 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1228 ss.append(PEM_FOOTER + '\n')
1229 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001230
1231def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232 """Takes a certificate in ASCII PEM format and returns the
1233 DER-encoded version of it as a byte sequence"""
1234
1235 if not pem_cert_string.startswith(PEM_HEADER):
1236 raise ValueError("Invalid PEM encoding; must start with %s"
1237 % PEM_HEADER)
1238 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1239 raise ValueError("Invalid PEM encoding; must end with %s"
1240 % PEM_FOOTER)
1241 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001242 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Christian Heimes598894f2016-09-05 23:19:05 +02001244def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245 """Retrieve the certificate from the server at the specified address,
1246 and return it as a PEM-encoded string.
1247 If 'ca_certs' is specified, validate the server cert against it.
1248 If 'ssl_version' is specified, use it in the connection attempt."""
1249
1250 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001251 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252 cert_reqs = CERT_REQUIRED
1253 else:
1254 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001255 context = _create_stdlib_context(ssl_version,
1256 cert_reqs=cert_reqs,
1257 cafile=ca_certs)
1258 with create_connection(addr) as sock:
1259 with context.wrap_socket(sock) as sslsock:
1260 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001261 return DER_cert_to_PEM_cert(dercert)
1262
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001263def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001264 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')