blob: 94ea35e358a39baf28d57332ed1b28046588175b [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
Christian Heimes141c5e82018-02-24 21:10:57 +0100169CHANNEL_BINDING_TYPES = ['tls-unique']
Thomas Woutersed03b412007-08-28 21:37:11 +0000170
Christian Heimes61d478c2018-01-27 15:51:38 +0100171HAS_NEVER_CHECK_COMMON_NAME = hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT')
172
Christian Heimes03d13c02016-09-06 20:06:47 +0200173
Christian Heimes892d66e2018-01-29 14:10:18 +0100174_RESTRICTED_SERVER_CIPHERS = _DEFAULT_CIPHERS
Christian Heimes4c05b472013-11-23 15:58:30 +0100175
Christian Heimes61d478c2018-01-27 15:51:38 +0100176CertificateError = SSLCertVerificationError
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000177
178
Mandeep Singhede2ac92017-11-27 04:01:27 +0530179def _dnsname_match(dn, hostname):
Georg Brandl72c98d32013-10-27 07:16:53 +0100180 """Matching according to RFC 6125, section 6.4.3
181
Christian Heimesaef12832018-02-24 14:35:56 +0100182 - Hostnames are compared lower case.
183 - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE).
184 - Partial wildcards like 'www*.example.org', multiple wildcards, sole
185 wildcard or wildcards in labels other then the left-most label are not
186 supported and a CertificateError is raised.
187 - A wildcard must match at least one character.
Georg Brandl72c98d32013-10-27 07:16:53 +0100188 """
Georg Brandl72c98d32013-10-27 07:16:53 +0100189 if not dn:
190 return False
191
Christian Heimesaef12832018-02-24 14:35:56 +0100192 wildcards = dn.count('*')
Georg Brandl72c98d32013-10-27 07:16:53 +0100193 # speed up common case w/o wildcards
194 if not wildcards:
195 return dn.lower() == hostname.lower()
196
Christian Heimesaef12832018-02-24 14:35:56 +0100197 if wildcards > 1:
198 raise CertificateError(
199 "too many wildcards in certificate DNS name: {!r}.".format(dn))
Georg Brandl72c98d32013-10-27 07:16:53 +0100200
Christian Heimesaef12832018-02-24 14:35:56 +0100201 dn_leftmost, sep, dn_remainder = dn.partition('.')
Georg Brandl72c98d32013-10-27 07:16:53 +0100202
Christian Heimesaef12832018-02-24 14:35:56 +0100203 if '*' in dn_remainder:
204 # Only match wildcard in leftmost segment.
205 raise CertificateError(
206 "wildcard can only be present in the leftmost label: "
207 "{!r}.".format(dn))
208
209 if not sep:
210 # no right side
211 raise CertificateError(
212 "sole wildcard without additional labels are not support: "
213 "{!r}.".format(dn))
214
215 if dn_leftmost != '*':
216 # no partial wildcard matching
217 raise CertificateError(
218 "partial wildcards in leftmost label are not supported: "
219 "{!r}.".format(dn))
220
221 hostname_leftmost, sep, hostname_remainder = hostname.partition('.')
222 if not hostname_leftmost or not sep:
223 # wildcard must match at least one char
224 return False
225 return dn_remainder.lower() == hostname_remainder.lower()
226
227
228def _inet_paton(ipname):
229 """Try to convert an IP address to packed binary form
230
231 Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6
232 support.
233 """
234 # inet_aton() also accepts strings like '1'
235 if ipname.count('.') == 3:
236 try:
237 return _socket.inet_aton(ipname)
238 except OSError:
239 pass
240
241 try:
242 return _socket.inet_pton(_socket.AF_INET6, ipname)
243 except OSError:
244 raise ValueError("{!r} is neither an IPv4 nor an IP6 "
245 "address.".format(ipname))
246 except AttributeError:
247 # AF_INET6 not available
248 pass
249
250 raise ValueError("{!r} is not an IPv4 address.".format(ipname))
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000251
252
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100253def _ipaddress_match(ipname, host_ip):
254 """Exact matching of IP addresses.
255
256 RFC 6125 explicitly doesn't define an algorithm for this
257 (section 1.7.2 - "Out of Scope").
258 """
259 # OpenSSL may add a trailing newline to a subjectAltName's IP address
Christian Heimesaef12832018-02-24 14:35:56 +0100260 ip = _inet_paton(ipname.rstrip())
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100261 return ip == host_ip
262
263
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000264def match_hostname(cert, hostname):
265 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100266 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
Christian Heimesaef12832018-02-24 14:35:56 +0100267 rules are followed.
268
269 The function matches IP addresses rather than dNSNames if hostname is a
270 valid ipaddress string. IPv4 addresses are supported on all platforms.
271 IPv6 addresses are supported on platforms with IPv6 support (AF_INET6
272 and inet_pton).
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000273
274 CertificateError is raised on failure. On success, the function
275 returns nothing.
276 """
277 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100278 raise ValueError("empty or no certificate, match_hostname needs a "
279 "SSL socket or SSL context with either "
280 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100281 try:
Christian Heimesaef12832018-02-24 14:35:56 +0100282 host_ip = _inet_paton(hostname)
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100283 except ValueError:
284 # Not an IP address (common case)
285 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000286 dnsnames = []
287 san = cert.get('subjectAltName', ())
288 for key, value in san:
289 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100290 if host_ip is None and _dnsname_match(value, hostname):
291 return
292 dnsnames.append(value)
293 elif key == 'IP Address':
294 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000295 return
296 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200297 if not dnsnames:
298 # The subject is only checked when there is no dNSName entry
299 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000300 for sub in cert.get('subject', ()):
301 for key, value in sub:
302 # XXX according to RFC 2818, the most specific Common Name
303 # must be used.
304 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100305 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000306 return
307 dnsnames.append(value)
308 if len(dnsnames) > 1:
309 raise CertificateError("hostname %r "
310 "doesn't match either of %s"
311 % (hostname, ', '.join(map(repr, dnsnames))))
312 elif len(dnsnames) == 1:
313 raise CertificateError("hostname %r "
314 "doesn't match %r"
315 % (hostname, dnsnames[0]))
316 else:
317 raise CertificateError("no appropriate commonName or "
318 "subjectAltName fields were found")
319
320
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100321DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200322 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
323 "openssl_capath")
324
325def get_default_verify_paths():
326 """Return paths to default cafile and capath.
327 """
328 parts = _ssl.get_default_verify_paths()
329
330 # environment vars shadow paths
331 cafile = os.environ.get(parts[0], parts[1])
332 capath = os.environ.get(parts[2], parts[3])
333
334 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
335 capath if os.path.isdir(capath) else None,
336 *parts)
337
338
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100339class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
340 """ASN.1 object identifier lookup
341 """
342 __slots__ = ()
343
344 def __new__(cls, oid):
345 return super().__new__(cls, *_txt2obj(oid, name=False))
346
347 @classmethod
348 def fromnid(cls, nid):
349 """Create _ASN1Object from OpenSSL numeric ID
350 """
351 return super().__new__(cls, *_nid2obj(nid))
352
353 @classmethod
354 def fromname(cls, name):
355 """Create _ASN1Object from short name, long name or OID
356 """
357 return super().__new__(cls, *_txt2obj(name, name=True))
358
359
Christian Heimes72d28502013-11-23 13:56:58 +0100360class Purpose(_ASN1Object, _Enum):
361 """SSLContext purpose flags with X509v3 Extended Key Usage objects
362 """
363 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
364 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
365
366
Antoine Pitrou152efa22010-05-16 18:19:27 +0000367class SSLContext(_SSLContext):
368 """An SSLContext holds various SSL-related configuration options and
369 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100370 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000371
Christian Heimes4df60f12017-09-15 20:26:05 +0200372 sslsocket_class = None # SSLSocket is assigned later.
373 sslobject_class = None # SSLObject is assigned later.
374
Christian Heimes598894f2016-09-05 23:19:05 +0200375 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100376 self = _SSLContext.__new__(cls, protocol)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100377 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000378
Christian Heimes11a14932018-02-24 02:35:08 +0100379 def _encode_hostname(self, hostname):
380 if hostname is None:
381 return None
382 elif isinstance(hostname, str):
383 return hostname.encode('idna').decode('ascii')
384 else:
385 return hostname.decode('ascii')
Antoine Pitrou152efa22010-05-16 18:19:27 +0000386
387 def wrap_socket(self, sock, server_side=False,
388 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000389 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200390 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100391 # SSLSocket class handles server_hostname encoding before it calls
392 # ctx._wrap_socket()
Christian Heimes4df60f12017-09-15 20:26:05 +0200393 return self.sslsocket_class(
394 sock=sock,
395 server_side=server_side,
396 do_handshake_on_connect=do_handshake_on_connect,
397 suppress_ragged_eofs=suppress_ragged_eofs,
398 server_hostname=server_hostname,
399 _context=self,
400 _session=session
401 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000402
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200403 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200404 server_hostname=None, session=None):
Christian Heimes11a14932018-02-24 02:35:08 +0100405 # Need to encode server_hostname here because _wrap_bio() can only
406 # handle ASCII str.
Christian Heimes141c5e82018-02-24 21:10:57 +0100407 return self.sslobject_class(
Christian Heimes11a14932018-02-24 02:35:08 +0100408 incoming, outgoing, server_side=server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +0100409 server_hostname=self._encode_hostname(server_hostname),
410 session=session, _context=self,
Christian Heimes11a14932018-02-24 02:35:08 +0100411 )
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200412
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100413 def set_npn_protocols(self, npn_protocols):
414 protos = bytearray()
415 for protocol in npn_protocols:
416 b = bytes(protocol, 'ascii')
417 if len(b) == 0 or len(b) > 255:
418 raise SSLError('NPN protocols must be 1 to 255 in length')
419 protos.append(len(b))
420 protos.extend(b)
421
422 self._set_npn_protocols(protos)
423
Christian Heimes11a14932018-02-24 02:35:08 +0100424 def set_servername_callback(self, server_name_callback):
425 if server_name_callback is None:
426 self.sni_callback = None
427 else:
428 if not callable(server_name_callback):
429 raise TypeError("not a callable object")
430
431 def shim_cb(sslobj, servername, sslctx):
432 servername = self._encode_hostname(servername)
433 return server_name_callback(sslobj, servername, sslctx)
434
435 self.sni_callback = shim_cb
436
Benjamin Petersoncca27322015-01-23 16:35:37 -0500437 def set_alpn_protocols(self, alpn_protocols):
438 protos = bytearray()
439 for protocol in alpn_protocols:
440 b = bytes(protocol, 'ascii')
441 if len(b) == 0 or len(b) > 255:
442 raise SSLError('ALPN protocols must be 1 to 255 in length')
443 protos.append(len(b))
444 protos.extend(b)
445
446 self._set_alpn_protocols(protos)
447
Christian Heimes72d28502013-11-23 13:56:58 +0100448 def _load_windows_store_certs(self, storename, purpose):
449 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700450 try:
451 for cert, encoding, trust in enum_certificates(storename):
452 # CA certs are never PKCS#7 encoded
453 if encoding == "x509_asn":
454 if trust is True or purpose.oid in trust:
455 certs.extend(cert)
456 except PermissionError:
457 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700458 if certs:
459 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100460 return certs
461
462 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
463 if not isinstance(purpose, _ASN1Object):
464 raise TypeError(purpose)
465 if sys.platform == "win32":
466 for storename in self._windows_cert_stores:
467 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400468 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100469
Christian Heimes3aeacad2016-09-10 00:19:35 +0200470 @property
471 def options(self):
472 return Options(super().options)
473
474 @options.setter
475 def options(self, value):
476 super(SSLContext, SSLContext).options.__set__(self, value)
477
Christian Heimes61d478c2018-01-27 15:51:38 +0100478 if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
479 @property
480 def hostname_checks_common_name(self):
481 ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
482 return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
483
484 @hostname_checks_common_name.setter
485 def hostname_checks_common_name(self, value):
486 if value:
487 self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
488 else:
489 self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
490 else:
491 @property
492 def hostname_checks_common_name(self):
493 return True
494
Christian Heimes3aeacad2016-09-10 00:19:35 +0200495 @property
Christian Heimes11a14932018-02-24 02:35:08 +0100496 def protocol(self):
497 return _SSLMethod(super().protocol)
498
499 @property
Christian Heimes3aeacad2016-09-10 00:19:35 +0200500 def verify_flags(self):
501 return VerifyFlags(super().verify_flags)
502
503 @verify_flags.setter
504 def verify_flags(self, value):
505 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
506
507 @property
508 def verify_mode(self):
509 value = super().verify_mode
510 try:
511 return VerifyMode(value)
512 except ValueError:
513 return value
514
515 @verify_mode.setter
516 def verify_mode(self, value):
517 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
518
Antoine Pitrou152efa22010-05-16 18:19:27 +0000519
Christian Heimes4c05b472013-11-23 15:58:30 +0100520def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
521 capath=None, cadata=None):
522 """Create a SSLContext object with default settings.
523
524 NOTE: The protocol and settings may change anytime without prior
525 deprecation. The values represent a fair balance between maximum
526 compatibility and security.
527 """
528 if not isinstance(purpose, _ASN1Object):
529 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400530
Christian Heimes358cfd42016-09-10 22:43:48 +0200531 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
532 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
533 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200534 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400535
Christian Heimes4c05b472013-11-23 15:58:30 +0100536 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400537 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100538 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100539 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400540
Christian Heimes4c05b472013-11-23 15:58:30 +0100541 if cafile or capath or cadata:
542 context.load_verify_locations(cafile, capath, cadata)
543 elif context.verify_mode != CERT_NONE:
544 # no explicit cafile, capath or cadata but the verify mode is
545 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
546 # root CA certificates for the given purpose. This may fail silently.
547 context.load_default_certs(purpose)
548 return context
549
Christian Heimesa170fa12017-09-15 20:27:30 +0200550def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100551 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100552 certfile=None, keyfile=None,
553 cafile=None, capath=None, cadata=None):
554 """Create a SSLContext object for Python stdlib modules
555
556 All Python stdlib modules shall use this function to create SSLContext
557 objects in order to keep common settings in one place. The configuration
558 is less restrict than create_default_context()'s to increase backward
559 compatibility.
560 """
561 if not isinstance(purpose, _ASN1Object):
562 raise TypeError(purpose)
563
Christian Heimes358cfd42016-09-10 22:43:48 +0200564 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
565 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
566 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100567 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100568
Christian Heimesa170fa12017-09-15 20:27:30 +0200569 if not check_hostname:
570 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100571 if cert_reqs is not None:
572 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200573 if check_hostname:
574 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100575
576 if keyfile and not certfile:
577 raise ValueError("certfile must be specified")
578 if certfile or keyfile:
579 context.load_cert_chain(certfile, keyfile)
580
581 # load CA root certs
582 if cafile or capath or cadata:
583 context.load_verify_locations(cafile, capath, cadata)
584 elif context.verify_mode != CERT_NONE:
585 # no explicit cafile, capath or cadata but the verify mode is
586 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
587 # root CA certificates for the given purpose. This may fail silently.
588 context.load_default_certs(purpose)
589
590 return context
591
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500592# Used by http.client if no context is explicitly passed.
593_create_default_https_context = create_default_context
594
595
596# Backwards compatibility alias, even though it's not a public name.
597_create_stdlib_context = _create_unverified_context
598
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200599
600class SSLObject:
601 """This class implements an interface on top of a low-level SSL object as
602 implemented by OpenSSL. This object captures the state of an SSL connection
603 but does not provide any network IO itself. IO needs to be performed
604 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
605
606 This class does not have a public constructor. Instances are returned by
607 ``SSLContext.wrap_bio``. This class is typically used by framework authors
608 that want to implement asynchronous IO for SSL through memory buffers.
609
610 When compared to ``SSLSocket``, this object lacks the following features:
611
612 * Any form of network IO incluging methods such as ``recv`` and ``send``.
613 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
614 """
615
Christian Heimes141c5e82018-02-24 21:10:57 +0100616 def __init__(self, incoming, outgoing, server_side=False,
617 server_hostname=None, session=None, _context=None):
618 self._sslobj = _context._wrap_bio(
619 incoming, outgoing, server_side=server_side,
620 server_hostname=server_hostname,
621 owner=self, session=session
622 )
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200623
624 @property
625 def context(self):
626 """The SSLContext that is currently in use."""
627 return self._sslobj.context
628
629 @context.setter
630 def context(self, ctx):
631 self._sslobj.context = ctx
632
633 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200634 def session(self):
635 """The SSLSession for client socket."""
636 return self._sslobj.session
637
638 @session.setter
639 def session(self, session):
640 self._sslobj.session = session
641
642 @property
643 def session_reused(self):
644 """Was the client session reused during handshake"""
645 return self._sslobj.session_reused
646
647 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200648 def server_side(self):
649 """Whether this is a server-side socket."""
650 return self._sslobj.server_side
651
652 @property
653 def server_hostname(self):
654 """The currently set server hostname (for SNI), or ``None`` if no
655 server hostame is set."""
656 return self._sslobj.server_hostname
657
Martin Panterf6b1d662016-03-28 00:22:09 +0000658 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200659 """Read up to 'len' bytes from the SSL object and return them.
660
661 If 'buffer' is provided, read into this buffer and return the number of
662 bytes read.
663 """
664 if buffer is not None:
665 v = self._sslobj.read(len, buffer)
666 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000667 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200668 return v
669
670 def write(self, data):
671 """Write 'data' to the SSL object and return the number of bytes
672 written.
673
674 The 'data' argument must support the buffer interface.
675 """
676 return self._sslobj.write(data)
677
678 def getpeercert(self, binary_form=False):
679 """Returns a formatted version of the data in the certificate provided
680 by the other end of the SSL channel.
681
682 Return None if no certificate was provided, {} if a certificate was
683 provided, but not validated.
684 """
Christian Heimes141c5e82018-02-24 21:10:57 +0100685 return self._sslobj.getpeercert(binary_form)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200686
687 def selected_npn_protocol(self):
688 """Return the currently selected NPN protocol as a string, or ``None``
689 if a next protocol was not negotiated or if NPN is not supported by one
690 of the peers."""
691 if _ssl.HAS_NPN:
692 return self._sslobj.selected_npn_protocol()
693
Benjamin Petersoncca27322015-01-23 16:35:37 -0500694 def selected_alpn_protocol(self):
695 """Return the currently selected ALPN protocol as a string, or ``None``
696 if a next protocol was not negotiated or if ALPN is not supported by one
697 of the peers."""
698 if _ssl.HAS_ALPN:
699 return self._sslobj.selected_alpn_protocol()
700
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200701 def cipher(self):
702 """Return the currently selected cipher as a 3-tuple ``(name,
703 ssl_version, secret_bits)``."""
704 return self._sslobj.cipher()
705
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600706 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500707 """Return a list of ciphers shared by the client during the handshake or
708 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600709 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600710 return self._sslobj.shared_ciphers()
711
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200712 def compression(self):
713 """Return the current compression algorithm in use, or ``None`` if
714 compression was not negotiated or not supported by one of the peers."""
715 return self._sslobj.compression()
716
717 def pending(self):
718 """Return the number of bytes that can be read immediately."""
719 return self._sslobj.pending()
720
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200721 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200722 """Start the SSL/TLS handshake."""
723 self._sslobj.do_handshake()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200724
725 def unwrap(self):
726 """Start the SSL shutdown handshake."""
727 return self._sslobj.shutdown()
728
729 def get_channel_binding(self, cb_type="tls-unique"):
730 """Get channel binding data for current connection. Raise ValueError
731 if the requested `cb_type` is not supported. Return bytes of the data
732 or None if the data is not available (e.g. before the handshake)."""
Christian Heimes141c5e82018-02-24 21:10:57 +0100733 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200734
735 def version(self):
736 """Return a string identifying the protocol version used by the
737 current SSL channel. """
738 return self._sslobj.version()
739
740
Antoine Pitrou152efa22010-05-16 18:19:27 +0000741class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000742 """This class implements a subtype of socket.socket that wraps
743 the underlying OS socket in an SSL context when necessary, and
744 provides read and write methods over that channel."""
745
Bill Janssen6e027db2007-11-15 22:23:56 +0000746 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000747 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200748 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000749 do_handshake_on_connect=True,
750 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100751 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000752 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200753 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000754
Antoine Pitrou152efa22010-05-16 18:19:27 +0000755 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000757 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000758 if server_side and not certfile:
759 raise ValueError("certfile must be specified for server-side "
760 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000761 if keyfile and not certfile:
762 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000763 if certfile and not keyfile:
764 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100765 self._context = SSLContext(ssl_version)
766 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000767 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100768 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000769 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100770 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100771 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100772 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000773 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100774 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000775 self.keyfile = keyfile
776 self.certfile = certfile
777 self.cert_reqs = cert_reqs
778 self.ssl_version = ssl_version
779 self.ca_certs = ca_certs
780 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100781 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
782 # mixed in.
783 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
784 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200785 if server_side:
786 if server_hostname:
787 raise ValueError("server_hostname can only be specified "
788 "in client mode")
789 if _session is not None:
790 raise ValueError("session can only be specified in "
791 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100792 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600793 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200794 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000795 self.server_side = server_side
Christian Heimes11a14932018-02-24 02:35:08 +0100796 self.server_hostname = self._context._encode_hostname(server_hostname)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000797 self.do_handshake_on_connect = do_handshake_on_connect
798 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000799 if sock is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100800 super().__init__(family=sock.family,
801 type=sock.type,
802 proto=sock.proto,
803 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000804 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000805 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000806 elif fileno is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100807 super().__init__(fileno=fileno)
Bill Janssen6e027db2007-11-15 22:23:56 +0000808 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100809 super().__init__(family=family, type=type, proto=proto)
Bill Janssen6e027db2007-11-15 22:23:56 +0000810
Antoine Pitrou242db722013-05-01 20:52:07 +0200811 # See if we are connected
812 try:
813 self.getpeername()
814 except OSError as e:
815 if e.errno != errno.ENOTCONN:
816 raise
817 connected = False
818 else:
819 connected = True
820
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000821 self._closed = False
822 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000823 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000824 if connected:
825 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000826 try:
Christian Heimes141c5e82018-02-24 21:10:57 +0100827 self._sslobj = self._context._wrap_socket(
828 self, server_side, self.server_hostname,
829 owner=self, session=self._session,
830 )
Bill Janssen6e027db2007-11-15 22:23:56 +0000831 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000832 timeout = self.gettimeout()
833 if timeout == 0.0:
834 # non-blocking
835 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000836 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000837
Christian Heimes1aa9a752013-12-02 02:41:19 +0100838 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000839 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100840 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200841
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100842 @property
843 def context(self):
844 return self._context
845
846 @context.setter
847 def context(self, ctx):
848 self._context = ctx
849 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000850
Christian Heimes99a65702016-09-10 23:44:53 +0200851 @property
852 def session(self):
853 """The SSLSession for client socket."""
854 if self._sslobj is not None:
855 return self._sslobj.session
856
857 @session.setter
858 def session(self, session):
859 self._session = session
860 if self._sslobj is not None:
861 self._sslobj.session = session
862
863 @property
864 def session_reused(self):
865 """Was the client session reused during handshake"""
866 if self._sslobj is not None:
867 return self._sslobj.session_reused
868
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000869 def dup(self):
870 raise NotImplemented("Can't dup() %s instances" %
871 self.__class__.__name__)
872
Bill Janssen6e027db2007-11-15 22:23:56 +0000873 def _checkClosed(self, msg=None):
874 # raise an exception here if you wish to check for spurious closes
875 pass
876
Antoine Pitrou242db722013-05-01 20:52:07 +0200877 def _check_connected(self):
878 if not self._connected:
879 # getpeername() will raise ENOTCONN if the socket is really
880 # not connected; note that we can be connected even without
881 # _connected being set, e.g. if connect() first returned
882 # EAGAIN.
883 self.getpeername()
884
Martin Panterf6b1d662016-03-28 00:22:09 +0000885 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000886 """Read up to LEN bytes and return them.
887 Return zero-length string on EOF."""
888
Bill Janssen6e027db2007-11-15 22:23:56 +0000889 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100890 if self._sslobj is None:
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200891 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000892 try:
Christian Heimes141c5e82018-02-24 21:10:57 +0100893 if buffer is not None:
894 return self._sslobj.read(len, buffer)
895 else:
896 return self._sslobj.read(len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000897 except SSLError as x:
898 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000899 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000900 return 0
901 else:
902 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000903 else:
904 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000905
906 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000907 """Write DATA to the underlying SSL channel. Returns
908 number of bytes of DATA actually transmitted."""
909
Bill Janssen6e027db2007-11-15 22:23:56 +0000910 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100911 if self._sslobj is None:
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200912 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000913 return self._sslobj.write(data)
914
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000916 """Returns a formatted version of the data in the
917 certificate provided by the other end of the SSL channel.
918 Return None if no certificate was provided, {} if a
919 certificate was provided, but not validated."""
920
Bill Janssen6e027db2007-11-15 22:23:56 +0000921 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200922 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200923 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100925 def selected_npn_protocol(self):
926 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100927 if self._sslobj is None or not _ssl.HAS_NPN:
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100928 return None
929 else:
930 return self._sslobj.selected_npn_protocol()
931
Benjamin Petersoncca27322015-01-23 16:35:37 -0500932 def selected_alpn_protocol(self):
933 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100934 if self._sslobj is None or not _ssl.HAS_ALPN:
Benjamin Petersoncca27322015-01-23 16:35:37 -0500935 return None
936 else:
937 return self._sslobj.selected_alpn_protocol()
938
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000939 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000940 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100941 if self._sslobj is None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942 return None
943 else:
944 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000945
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600946 def shared_ciphers(self):
947 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100948 if self._sslobj is None:
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600949 return None
Christian Heimes141c5e82018-02-24 21:10:57 +0100950 else:
951 return self._sslobj.shared_ciphers()
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600952
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100953 def compression(self):
954 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100955 if self._sslobj is None:
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100956 return None
957 else:
958 return self._sslobj.compression()
959
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000960 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000961 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100962 if self._sslobj is not None:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000963 if flags != 0:
964 raise ValueError(
965 "non-zero flags not allowed in calls to send() on %s" %
966 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200967 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000968 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100969 return super().send(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000970
Antoine Pitroua468adc2010-09-14 14:43:44 +0000971 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000972 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100973 if self._sslobj is not None:
Bill Janssen980f3142008-06-29 00:05:51 +0000974 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000975 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000976 elif addr is None:
Mads Jensen746cc752018-01-27 13:34:28 +0100977 return super().sendto(data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000978 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100979 return super().sendto(data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000980
Nick Coghlan513886a2011-08-28 00:00:27 +1000981 def sendmsg(self, *args, **kwargs):
982 # Ensure programs don't send data unencrypted if they try to
983 # use this method.
984 raise NotImplementedError("sendmsg not allowed on instances of %s" %
985 self.__class__)
986
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000987 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000988 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +0100989 if self._sslobj is not None:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000990 if flags != 0:
991 raise ValueError(
992 "non-zero flags not allowed in calls to sendall() on %s" %
993 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000994 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700995 with memoryview(data) as view, view.cast("B") as byte_view:
996 amount = len(byte_view)
997 while count < amount:
998 v = self.send(byte_view[count:])
999 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001000 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001001 return super().sendall(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001002
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001003 def sendfile(self, file, offset=0, count=None):
1004 """Send a file, possibly by using os.sendfile() if this is a
1005 clear-text socket. Return the total number of bytes sent.
1006 """
Christian Heimes141c5e82018-02-24 21:10:57 +01001007 if self._sslobj is not None:
1008 return self._sendfile_use_send(file, offset, count)
1009 else:
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001010 # os.sendfile() works with plain sockets only
1011 return super().sendfile(file, offset, count)
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02001012
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001013 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001014 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +01001015 if self._sslobj is not None:
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001016 if flags != 0:
1017 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +00001018 "non-zero flags not allowed in calls to recv() on %s" %
1019 self.__class__)
1020 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001021 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001022 return super().recv(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001023
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001024 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001025 self._checkClosed()
1026 if buffer and (nbytes is None):
1027 nbytes = len(buffer)
1028 elif nbytes is None:
1029 nbytes = 1024
Christian Heimes141c5e82018-02-24 21:10:57 +01001030 if self._sslobj is not None:
Bill Janssen6e027db2007-11-15 22:23:56 +00001031 if flags != 0:
1032 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001033 "non-zero flags not allowed in calls to recv_into() on %s" %
1034 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001035 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001036 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001037 return super().recv_into(buffer, nbytes, flags)
Bill Janssen6e027db2007-11-15 22:23:56 +00001038
Antoine Pitroua468adc2010-09-14 14:43:44 +00001039 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001040 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +01001041 if self._sslobj is not None:
Bill Janssen980f3142008-06-29 00:05:51 +00001042 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001043 self.__class__)
1044 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001045 return super().recvfrom(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001046
Bill Janssen58afe4c2008-09-08 16:45:19 +00001047 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1048 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +01001049 if self._sslobj is not None:
Bill Janssen58afe4c2008-09-08 16:45:19 +00001050 raise ValueError("recvfrom_into not allowed on instances of %s" %
1051 self.__class__)
1052 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001053 return super().recvfrom_into(buffer, nbytes, flags)
Bill Janssen58afe4c2008-09-08 16:45:19 +00001054
Nick Coghlan513886a2011-08-28 00:00:27 +10001055 def recvmsg(self, *args, **kwargs):
1056 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1057 self.__class__)
1058
1059 def recvmsg_into(self, *args, **kwargs):
1060 raise NotImplementedError("recvmsg_into not allowed on instances of "
1061 "%s" % self.__class__)
1062
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001063 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001064 self._checkClosed()
Christian Heimes141c5e82018-02-24 21:10:57 +01001065 if self._sslobj is not None:
Bill Janssen6e027db2007-11-15 22:23:56 +00001066 return self._sslobj.pending()
1067 else:
1068 return 0
1069
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001070 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001071 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001073 super().shutdown(how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001074
Ezio Melottidc55e672010-01-18 09:15:14 +00001075 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001076 if self._sslobj:
Christian Heimes141c5e82018-02-24 21:10:57 +01001077 s = self._sslobj.shutdown()
Bill Janssen40a0f662008-08-12 16:56:25 +00001078 self._sslobj = None
1079 return s
1080 else:
1081 raise ValueError("No SSL wrapper around " + str(self))
1082
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001083 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001085 super()._real_close()
Bill Janssen6e027db2007-11-15 22:23:56 +00001086
Bill Janssen48dc27c2007-12-05 03:38:10 +00001087 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001088 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001089 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001090 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001091 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001092 if timeout == 0.0 and block:
1093 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001094 self._sslobj.do_handshake()
Christian Heimes141c5e82018-02-24 21:10:57 +01001095 if self.context.check_hostname:
1096 if not self.server_hostname:
1097 raise ValueError("check_hostname needs server_hostname "
1098 "argument")
1099 match_hostname(self.getpeercert(), self.server_hostname)
Bill Janssen48dc27c2007-12-05 03:38:10 +00001100 finally:
1101 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001102
Antoine Pitroub4410db2011-05-18 18:51:06 +02001103 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001104 if self.server_side:
1105 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001106 # Here we assume that the socket is client-side, and not
1107 # connected at the time of the call. We connect it, then wrap it.
Christian Heimes141c5e82018-02-24 21:10:57 +01001108 if self._connected or self._sslobj is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109 raise ValueError("attempt to connect already-connected SSLSocket!")
Christian Heimes141c5e82018-02-24 21:10:57 +01001110 self._sslobj = self.context._wrap_socket(
1111 self, False, self.server_hostname,
1112 owner=self, session=self._session
1113 )
Bill Janssen54cc54c2007-12-14 22:08:56 +00001114 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001115 if connect_ex:
Mads Jensen746cc752018-01-27 13:34:28 +01001116 rc = super().connect_ex(addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001117 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001118 rc = None
Mads Jensen746cc752018-01-27 13:34:28 +01001119 super().connect(addr)
Antoine Pitroub4410db2011-05-18 18:51:06 +02001120 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001121 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001122 if self.do_handshake_on_connect:
1123 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001124 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001125 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001126 self._sslobj = None
1127 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001128
1129 def connect(self, addr):
1130 """Connects to remote ADDR, and then wraps the connection in
1131 an SSL channel."""
1132 self._real_connect(addr, False)
1133
1134 def connect_ex(self, addr):
1135 """Connects to remote ADDR, and then wraps the connection in
1136 an SSL channel."""
1137 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001138
1139 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001140 """Accepts a new connection from a remote client, and returns
1141 a tuple containing that new connection wrapped with a server-side
1142 SSL channel, and the address of the remote client."""
1143
Mads Jensen746cc752018-01-27 13:34:28 +01001144 newsock, addr = super().accept()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001145 newsock = self.context.wrap_socket(newsock,
1146 do_handshake_on_connect=self.do_handshake_on_connect,
1147 suppress_ragged_eofs=self.suppress_ragged_eofs,
1148 server_side=True)
1149 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150
Antoine Pitroud6494802011-07-21 01:11:30 +02001151 def get_channel_binding(self, cb_type="tls-unique"):
1152 """Get channel binding data for current connection. Raise ValueError
1153 if the requested `cb_type` is not supported. Return bytes of the data
1154 or None if the data is not available (e.g. before the handshake).
1155 """
Christian Heimes141c5e82018-02-24 21:10:57 +01001156 if self._sslobj is not None:
1157 return self._sslobj.get_channel_binding(cb_type)
1158 else:
1159 if cb_type not in CHANNEL_BINDING_TYPES:
1160 raise ValueError(
1161 "{0} channel binding type not implemented".format(cb_type)
1162 )
Antoine Pitroud6494802011-07-21 01:11:30 +02001163 return None
Antoine Pitroud6494802011-07-21 01:11:30 +02001164
Antoine Pitrou47e40422014-09-04 21:00:10 +02001165 def version(self):
1166 """
1167 Return a string identifying the protocol version used by the
1168 current SSL channel, or None if there is no established channel.
1169 """
Christian Heimes141c5e82018-02-24 21:10:57 +01001170 if self._sslobj is not None:
1171 return self._sslobj.version()
1172 else:
Antoine Pitrou47e40422014-09-04 21:00:10 +02001173 return None
Antoine Pitrou47e40422014-09-04 21:00:10 +02001174
Bill Janssen54cc54c2007-12-14 22:08:56 +00001175
Christian Heimes4df60f12017-09-15 20:26:05 +02001176# Python does not support forward declaration of types.
1177SSLContext.sslsocket_class = SSLSocket
1178SSLContext.sslobject_class = SSLObject
1179
1180
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001181def wrap_socket(sock, keyfile=None, certfile=None,
1182 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001183 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001184 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001185 suppress_ragged_eofs=True,
1186 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001187 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001189 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001190 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001191 suppress_ragged_eofs=suppress_ragged_eofs,
1192 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Thomas Woutersed03b412007-08-28 21:37:11 +00001194# some utility functions
1195
1196def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001197 """Return the time in seconds since the Epoch, given the timestring
1198 representing the "notBefore" or "notAfter" date from a certificate
1199 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001200
Antoine Pitrouc695c952014-04-28 20:57:36 +02001201 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1202
1203 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1204 UTC should be specified as GMT (see ASN1_TIME_print())
1205 """
1206 from time import strptime
1207 from calendar import timegm
1208
1209 months = (
1210 "Jan","Feb","Mar","Apr","May","Jun",
1211 "Jul","Aug","Sep","Oct","Nov","Dec"
1212 )
1213 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1214 try:
1215 month_number = months.index(cert_time[:3].title()) + 1
1216 except ValueError:
1217 raise ValueError('time data %r does not match '
1218 'format "%%b%s"' % (cert_time, time_format))
1219 else:
1220 # found valid month
1221 tt = strptime(cert_time[3:], time_format)
1222 # return an integer, the previous mktime()-based implementation
1223 # returned a float (fractional seconds are always zero here).
1224 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001225
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1227PEM_FOOTER = "-----END CERTIFICATE-----"
1228
1229def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001230 """Takes a certificate in binary DER format and returns the
1231 PEM version of it as a string."""
1232
Bill Janssen6e027db2007-11-15 22:23:56 +00001233 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001234 ss = [PEM_HEADER]
1235 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1236 ss.append(PEM_FOOTER + '\n')
1237 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
1239def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240 """Takes a certificate in ASCII PEM format and returns the
1241 DER-encoded version of it as a byte sequence"""
1242
1243 if not pem_cert_string.startswith(PEM_HEADER):
1244 raise ValueError("Invalid PEM encoding; must start with %s"
1245 % PEM_HEADER)
1246 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1247 raise ValueError("Invalid PEM encoding; must end with %s"
1248 % PEM_FOOTER)
1249 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001250 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251
Christian Heimes598894f2016-09-05 23:19:05 +02001252def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253 """Retrieve the certificate from the server at the specified address,
1254 and return it as a PEM-encoded string.
1255 If 'ca_certs' is specified, validate the server cert against it.
1256 If 'ssl_version' is specified, use it in the connection attempt."""
1257
1258 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001259 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260 cert_reqs = CERT_REQUIRED
1261 else:
1262 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001263 context = _create_stdlib_context(ssl_version,
1264 cert_reqs=cert_reqs,
1265 cafile=ca_certs)
1266 with create_connection(addr) as sock:
1267 with context.wrap_socket(sock) as sslsock:
1268 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001269 return DER_cert_to_PEM_cert(dercert)
1270
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001271def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001272 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')