blob: 75ebcc165a17cb6fbc0a998abd2800323ce577ef [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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800161import 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
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800169CHANNEL_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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800182 - 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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800192 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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800197 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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800201 dn_leftmost, sep, dn_remainder = dn.partition('.')
Georg Brandl72c98d32013-10-27 07:16:53 +0100202
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800203 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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800260 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
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800267 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:
Miss Islington (bot)46632f42018-02-24 06:06:46 -0800282 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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800379 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):
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800391 # SSLSocket class handles server_hostname encoding before it calls
392 # ctx._wrap_socket()
Christian Heimes89c20512018-02-27 11:17:32 +0100393 return self.sslsocket_class._create(
Christian Heimes4df60f12017-09-15 20:26:05 +0200394 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,
Christian Heimes89c20512018-02-27 11:17:32 +0100399 context=self,
400 session=session
Christian Heimes4df60f12017-09-15 20:26:05 +0200401 )
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):
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800405 # Need to encode server_hostname here because _wrap_bio() can only
406 # handle ASCII str.
Christian Heimes89c20512018-02-27 11:17:32 +0100407 return self.sslobject_class._create(
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800408 incoming, outgoing, server_side=server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800409 server_hostname=self._encode_hostname(server_hostname),
Christian Heimes89c20512018-02-27 11:17:32 +0100410 session=session, context=self,
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800411 )
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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800424 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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800496 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 """
Christian Heimes89c20512018-02-27 11:17:32 +0100615 def __init__(self, *args, **kwargs):
616 raise TypeError(
617 f"{self.__class__.__name__} does not have a public "
618 f"constructor. Instances are returned by SSLContext.wrap_bio()."
619 )
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200620
Christian Heimes89c20512018-02-27 11:17:32 +0100621 @classmethod
622 def _create(cls, incoming, outgoing, server_side=False,
623 server_hostname=None, session=None, context=None):
624 self = cls.__new__(cls)
625 sslobj = context._wrap_bio(
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800626 incoming, outgoing, server_side=server_side,
627 server_hostname=server_hostname,
628 owner=self, session=session
629 )
Christian Heimes89c20512018-02-27 11:17:32 +0100630 self._sslobj = sslobj
631 return self
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632
633 @property
634 def context(self):
635 """The SSLContext that is currently in use."""
636 return self._sslobj.context
637
638 @context.setter
639 def context(self, ctx):
640 self._sslobj.context = ctx
641
642 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200643 def session(self):
644 """The SSLSession for client socket."""
645 return self._sslobj.session
646
647 @session.setter
648 def session(self, session):
649 self._sslobj.session = session
650
651 @property
652 def session_reused(self):
653 """Was the client session reused during handshake"""
654 return self._sslobj.session_reused
655
656 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200657 def server_side(self):
658 """Whether this is a server-side socket."""
659 return self._sslobj.server_side
660
661 @property
662 def server_hostname(self):
663 """The currently set server hostname (for SNI), or ``None`` if no
664 server hostame is set."""
665 return self._sslobj.server_hostname
666
Martin Panterf6b1d662016-03-28 00:22:09 +0000667 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200668 """Read up to 'len' bytes from the SSL object and return them.
669
670 If 'buffer' is provided, read into this buffer and return the number of
671 bytes read.
672 """
673 if buffer is not None:
674 v = self._sslobj.read(len, buffer)
675 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000676 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200677 return v
678
679 def write(self, data):
680 """Write 'data' to the SSL object and return the number of bytes
681 written.
682
683 The 'data' argument must support the buffer interface.
684 """
685 return self._sslobj.write(data)
686
687 def getpeercert(self, binary_form=False):
688 """Returns a formatted version of the data in the certificate provided
689 by the other end of the SSL channel.
690
691 Return None if no certificate was provided, {} if a certificate was
692 provided, but not validated.
693 """
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800694 return self._sslobj.getpeercert(binary_form)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200695
696 def selected_npn_protocol(self):
697 """Return the currently selected NPN protocol as a string, or ``None``
698 if a next protocol was not negotiated or if NPN is not supported by one
699 of the peers."""
700 if _ssl.HAS_NPN:
701 return self._sslobj.selected_npn_protocol()
702
Benjamin Petersoncca27322015-01-23 16:35:37 -0500703 def selected_alpn_protocol(self):
704 """Return the currently selected ALPN protocol as a string, or ``None``
705 if a next protocol was not negotiated or if ALPN is not supported by one
706 of the peers."""
707 if _ssl.HAS_ALPN:
708 return self._sslobj.selected_alpn_protocol()
709
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200710 def cipher(self):
711 """Return the currently selected cipher as a 3-tuple ``(name,
712 ssl_version, secret_bits)``."""
713 return self._sslobj.cipher()
714
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600715 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500716 """Return a list of ciphers shared by the client during the handshake or
717 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600718 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600719 return self._sslobj.shared_ciphers()
720
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200721 def compression(self):
722 """Return the current compression algorithm in use, or ``None`` if
723 compression was not negotiated or not supported by one of the peers."""
724 return self._sslobj.compression()
725
726 def pending(self):
727 """Return the number of bytes that can be read immediately."""
728 return self._sslobj.pending()
729
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200730 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200731 """Start the SSL/TLS handshake."""
732 self._sslobj.do_handshake()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200733
734 def unwrap(self):
735 """Start the SSL shutdown handshake."""
736 return self._sslobj.shutdown()
737
738 def get_channel_binding(self, cb_type="tls-unique"):
739 """Get channel binding data for current connection. Raise ValueError
740 if the requested `cb_type` is not supported. Return bytes of the data
741 or None if the data is not available (e.g. before the handshake)."""
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800742 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200743
744 def version(self):
745 """Return a string identifying the protocol version used by the
746 current SSL channel. """
747 return self._sslobj.version()
748
749
Antoine Pitrou152efa22010-05-16 18:19:27 +0000750class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000751 """This class implements a subtype of socket.socket that wraps
752 the underlying OS socket in an SSL context when necessary, and
Christian Heimes89c20512018-02-27 11:17:32 +0100753 provides read and write methods over that channel. """
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000754
Christian Heimes89c20512018-02-27 11:17:32 +0100755 def __init__(self, *args, **kwargs):
756 raise TypeError(
757 f"{self.__class__.__name__} does not have a public "
758 f"constructor. Instances are returned by "
759 f"SSLContext.wrap_socket()."
760 )
Bill Janssen6e027db2007-11-15 22:23:56 +0000761
Christian Heimes89c20512018-02-27 11:17:32 +0100762 @classmethod
763 def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
764 suppress_ragged_eofs=True, server_hostname=None,
765 context=None, session=None):
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100766 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
767 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200768 if server_side:
769 if server_hostname:
770 raise ValueError("server_hostname can only be specified "
771 "in client mode")
Christian Heimes89c20512018-02-27 11:17:32 +0100772 if session is not None:
Christian Heimes99a65702016-09-10 23:44:53 +0200773 raise ValueError("session can only be specified in "
774 "client mode")
Christian Heimes89c20512018-02-27 11:17:32 +0100775 if context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600776 raise ValueError("check_hostname requires server_hostname")
Christian Heimes89c20512018-02-27 11:17:32 +0100777
778 kwargs = dict(
779 family=sock.family, type=sock.type, proto=sock.proto,
780 fileno=sock.fileno()
781 )
782 self = cls.__new__(cls, **kwargs)
783 super(SSLSocket, self).__init__(**kwargs)
784 self.settimeout(sock.gettimeout())
785 sock.detach()
786
787 self._context = context
788 self._session = session
789 self._closed = False
790 self._sslobj = None
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000791 self.server_side = server_side
Christian Heimes89c20512018-02-27 11:17:32 +0100792 self.server_hostname = context._encode_hostname(server_hostname)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000793 self.do_handshake_on_connect = do_handshake_on_connect
794 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000795
Antoine Pitrou242db722013-05-01 20:52:07 +0200796 # See if we are connected
797 try:
798 self.getpeername()
799 except OSError as e:
800 if e.errno != errno.ENOTCONN:
801 raise
802 connected = False
803 else:
804 connected = True
805
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000806 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000807 if connected:
808 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000809 try:
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800810 self._sslobj = self._context._wrap_socket(
811 self, server_side, self.server_hostname,
812 owner=self, session=self._session,
813 )
Bill Janssen6e027db2007-11-15 22:23:56 +0000814 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000815 timeout = self.gettimeout()
816 if timeout == 0.0:
817 # non-blocking
818 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000819 self.do_handshake()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100820 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000821 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100822 raise
Christian Heimes89c20512018-02-27 11:17:32 +0100823 return self
Antoine Pitrou242db722013-05-01 20:52:07 +0200824
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100825 @property
826 def context(self):
827 return self._context
828
829 @context.setter
830 def context(self, ctx):
831 self._context = ctx
832 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000833
Christian Heimes99a65702016-09-10 23:44:53 +0200834 @property
835 def session(self):
836 """The SSLSession for client socket."""
837 if self._sslobj is not None:
838 return self._sslobj.session
839
840 @session.setter
841 def session(self, session):
842 self._session = session
843 if self._sslobj is not None:
844 self._sslobj.session = session
845
846 @property
847 def session_reused(self):
848 """Was the client session reused during handshake"""
849 if self._sslobj is not None:
850 return self._sslobj.session_reused
851
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000852 def dup(self):
853 raise NotImplemented("Can't dup() %s instances" %
854 self.__class__.__name__)
855
Bill Janssen6e027db2007-11-15 22:23:56 +0000856 def _checkClosed(self, msg=None):
857 # raise an exception here if you wish to check for spurious closes
858 pass
859
Antoine Pitrou242db722013-05-01 20:52:07 +0200860 def _check_connected(self):
861 if not self._connected:
862 # getpeername() will raise ENOTCONN if the socket is really
863 # not connected; note that we can be connected even without
864 # _connected being set, e.g. if connect() first returned
865 # EAGAIN.
866 self.getpeername()
867
Martin Panterf6b1d662016-03-28 00:22:09 +0000868 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000869 """Read up to LEN bytes and return them.
870 Return zero-length string on EOF."""
871
Bill Janssen6e027db2007-11-15 22:23:56 +0000872 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800873 if self._sslobj is None:
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200874 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000875 try:
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800876 if buffer is not None:
877 return self._sslobj.read(len, buffer)
878 else:
879 return self._sslobj.read(len)
Bill Janssen6e027db2007-11-15 22:23:56 +0000880 except SSLError as x:
881 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000882 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000883 return 0
884 else:
885 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000886 else:
887 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000888
889 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000890 """Write DATA to the underlying SSL channel. Returns
891 number of bytes of DATA actually transmitted."""
892
Bill Janssen6e027db2007-11-15 22:23:56 +0000893 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800894 if self._sslobj is None:
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200895 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000896 return self._sslobj.write(data)
897
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000899 """Returns a formatted version of the data in the
900 certificate provided by the other end of the SSL channel.
901 Return None if no certificate was provided, {} if a
902 certificate was provided, but not validated."""
903
Bill Janssen6e027db2007-11-15 22:23:56 +0000904 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200905 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200906 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100908 def selected_npn_protocol(self):
909 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800910 if self._sslobj is None or not _ssl.HAS_NPN:
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100911 return None
912 else:
913 return self._sslobj.selected_npn_protocol()
914
Benjamin Petersoncca27322015-01-23 16:35:37 -0500915 def selected_alpn_protocol(self):
916 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800917 if self._sslobj is None or not _ssl.HAS_ALPN:
Benjamin Petersoncca27322015-01-23 16:35:37 -0500918 return None
919 else:
920 return self._sslobj.selected_alpn_protocol()
921
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000922 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000923 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800924 if self._sslobj is None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925 return None
926 else:
927 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000928
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600929 def shared_ciphers(self):
930 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800931 if self._sslobj is None:
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600932 return None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800933 else:
934 return self._sslobj.shared_ciphers()
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600935
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100936 def compression(self):
937 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800938 if self._sslobj is None:
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100939 return None
940 else:
941 return self._sslobj.compression()
942
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000943 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000944 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800945 if self._sslobj is not None:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000946 if flags != 0:
947 raise ValueError(
948 "non-zero flags not allowed in calls to send() on %s" %
949 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200950 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000951 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100952 return super().send(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000953
Antoine Pitroua468adc2010-09-14 14:43:44 +0000954 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000955 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800956 if self._sslobj is not None:
Bill Janssen980f3142008-06-29 00:05:51 +0000957 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000958 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000959 elif addr is None:
Mads Jensen746cc752018-01-27 13:34:28 +0100960 return super().sendto(data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000961 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100962 return super().sendto(data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000963
Nick Coghlan513886a2011-08-28 00:00:27 +1000964 def sendmsg(self, *args, **kwargs):
965 # Ensure programs don't send data unencrypted if they try to
966 # use this method.
967 raise NotImplementedError("sendmsg not allowed on instances of %s" %
968 self.__class__)
969
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000970 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000971 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800972 if self._sslobj is not None:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000973 if flags != 0:
974 raise ValueError(
975 "non-zero flags not allowed in calls to sendall() on %s" %
976 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000977 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700978 with memoryview(data) as view, view.cast("B") as byte_view:
979 amount = len(byte_view)
980 while count < amount:
981 v = self.send(byte_view[count:])
982 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000983 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100984 return super().sendall(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000985
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200986 def sendfile(self, file, offset=0, count=None):
987 """Send a file, possibly by using os.sendfile() if this is a
988 clear-text socket. Return the total number of bytes sent.
989 """
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800990 if self._sslobj is not None:
991 return self._sendfile_use_send(file, offset, count)
992 else:
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200993 # os.sendfile() works with plain sockets only
994 return super().sendfile(file, offset, count)
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200995
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000996 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000997 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800998 if self._sslobj is not None:
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000999 if flags != 0:
1000 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +00001001 "non-zero flags not allowed in calls to recv() on %s" %
1002 self.__class__)
1003 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001004 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001005 return super().recv(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001006
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001007 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001008 self._checkClosed()
1009 if buffer and (nbytes is None):
1010 nbytes = len(buffer)
1011 elif nbytes is None:
1012 nbytes = 1024
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001013 if self._sslobj is not None:
Bill Janssen6e027db2007-11-15 22:23:56 +00001014 if flags != 0:
1015 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001016 "non-zero flags not allowed in calls to recv_into() on %s" %
1017 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001018 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001019 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001020 return super().recv_into(buffer, nbytes, flags)
Bill Janssen6e027db2007-11-15 22:23:56 +00001021
Antoine Pitroua468adc2010-09-14 14:43:44 +00001022 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001023 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001024 if self._sslobj is not None:
Bill Janssen980f3142008-06-29 00:05:51 +00001025 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001026 self.__class__)
1027 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001028 return super().recvfrom(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001029
Bill Janssen58afe4c2008-09-08 16:45:19 +00001030 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1031 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001032 if self._sslobj is not None:
Bill Janssen58afe4c2008-09-08 16:45:19 +00001033 raise ValueError("recvfrom_into not allowed on instances of %s" %
1034 self.__class__)
1035 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001036 return super().recvfrom_into(buffer, nbytes, flags)
Bill Janssen58afe4c2008-09-08 16:45:19 +00001037
Nick Coghlan513886a2011-08-28 00:00:27 +10001038 def recvmsg(self, *args, **kwargs):
1039 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1040 self.__class__)
1041
1042 def recvmsg_into(self, *args, **kwargs):
1043 raise NotImplementedError("recvmsg_into not allowed on instances of "
1044 "%s" % self.__class__)
1045
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001046 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001047 self._checkClosed()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001048 if self._sslobj is not None:
Bill Janssen6e027db2007-11-15 22:23:56 +00001049 return self._sslobj.pending()
1050 else:
1051 return 0
1052
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001053 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001054 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001056 super().shutdown(how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001057
Ezio Melottidc55e672010-01-18 09:15:14 +00001058 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001059 if self._sslobj:
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001060 s = self._sslobj.shutdown()
Bill Janssen40a0f662008-08-12 16:56:25 +00001061 self._sslobj = None
1062 return s
1063 else:
1064 raise ValueError("No SSL wrapper around " + str(self))
1065
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001066 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001068 super()._real_close()
Bill Janssen6e027db2007-11-15 22:23:56 +00001069
Bill Janssen48dc27c2007-12-05 03:38:10 +00001070 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001071 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001072 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001073 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001074 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001075 if timeout == 0.0 and block:
1076 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001077 self._sslobj.do_handshake()
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001078 if self.context.check_hostname:
1079 if not self.server_hostname:
1080 raise ValueError("check_hostname needs server_hostname "
1081 "argument")
1082 match_hostname(self.getpeercert(), self.server_hostname)
Bill Janssen48dc27c2007-12-05 03:38:10 +00001083 finally:
1084 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001085
Antoine Pitroub4410db2011-05-18 18:51:06 +02001086 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001087 if self.server_side:
1088 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001089 # Here we assume that the socket is client-side, and not
1090 # connected at the time of the call. We connect it, then wrap it.
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001091 if self._connected or self._sslobj is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092 raise ValueError("attempt to connect already-connected SSLSocket!")
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001093 self._sslobj = self.context._wrap_socket(
1094 self, False, self.server_hostname,
1095 owner=self, session=self._session
1096 )
Bill Janssen54cc54c2007-12-14 22:08:56 +00001097 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001098 if connect_ex:
Mads Jensen746cc752018-01-27 13:34:28 +01001099 rc = super().connect_ex(addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001100 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001101 rc = None
Mads Jensen746cc752018-01-27 13:34:28 +01001102 super().connect(addr)
Antoine Pitroub4410db2011-05-18 18:51:06 +02001103 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001104 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001105 if self.do_handshake_on_connect:
1106 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001107 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001108 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001109 self._sslobj = None
1110 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001111
1112 def connect(self, addr):
1113 """Connects to remote ADDR, and then wraps the connection in
1114 an SSL channel."""
1115 self._real_connect(addr, False)
1116
1117 def connect_ex(self, addr):
1118 """Connects to remote ADDR, and then wraps the connection in
1119 an SSL channel."""
1120 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001121
1122 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001123 """Accepts a new connection from a remote client, and returns
1124 a tuple containing that new connection wrapped with a server-side
1125 SSL channel, and the address of the remote client."""
1126
Mads Jensen746cc752018-01-27 13:34:28 +01001127 newsock, addr = super().accept()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001128 newsock = self.context.wrap_socket(newsock,
1129 do_handshake_on_connect=self.do_handshake_on_connect,
1130 suppress_ragged_eofs=self.suppress_ragged_eofs,
1131 server_side=True)
1132 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Antoine Pitroud6494802011-07-21 01:11:30 +02001134 def get_channel_binding(self, cb_type="tls-unique"):
1135 """Get channel binding data for current connection. Raise ValueError
1136 if the requested `cb_type` is not supported. Return bytes of the data
1137 or None if the data is not available (e.g. before the handshake).
1138 """
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001139 if self._sslobj is not None:
1140 return self._sslobj.get_channel_binding(cb_type)
1141 else:
1142 if cb_type not in CHANNEL_BINDING_TYPES:
1143 raise ValueError(
1144 "{0} channel binding type not implemented".format(cb_type)
1145 )
Antoine Pitroud6494802011-07-21 01:11:30 +02001146 return None
Antoine Pitroud6494802011-07-21 01:11:30 +02001147
Antoine Pitrou47e40422014-09-04 21:00:10 +02001148 def version(self):
1149 """
1150 Return a string identifying the protocol version used by the
1151 current SSL channel, or None if there is no established channel.
1152 """
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001153 if self._sslobj is not None:
1154 return self._sslobj.version()
1155 else:
Antoine Pitrou47e40422014-09-04 21:00:10 +02001156 return None
Antoine Pitrou47e40422014-09-04 21:00:10 +02001157
Bill Janssen54cc54c2007-12-14 22:08:56 +00001158
Christian Heimes4df60f12017-09-15 20:26:05 +02001159# Python does not support forward declaration of types.
1160SSLContext.sslsocket_class = SSLSocket
1161SSLContext.sslobject_class = SSLObject
1162
1163
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164def wrap_socket(sock, keyfile=None, certfile=None,
1165 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001166 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001167 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001168 suppress_ragged_eofs=True,
1169 ciphers=None):
Christian Heimes89c20512018-02-27 11:17:32 +01001170
1171 if server_side and not certfile:
1172 raise ValueError("certfile must be specified for server-side "
1173 "operations")
1174 if keyfile and not certfile:
1175 raise ValueError("certfile must be specified")
1176 context = SSLContext(ssl_version)
1177 context.verify_mode = cert_reqs
1178 if ca_certs:
1179 context.load_verify_locations(ca_certs)
1180 if certfile:
1181 context.load_cert_chain(certfile, keyfile)
1182 if ciphers:
1183 context.set_ciphers(ciphers)
1184 return context.wrap_socket(
1185 sock=sock, server_side=server_side,
1186 do_handshake_on_connect=do_handshake_on_connect,
1187 suppress_ragged_eofs=suppress_ragged_eofs
1188 )
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189
Thomas Woutersed03b412007-08-28 21:37:11 +00001190# some utility functions
1191
1192def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001193 """Return the time in seconds since the Epoch, given the timestring
1194 representing the "notBefore" or "notAfter" date from a certificate
1195 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001196
Antoine Pitrouc695c952014-04-28 20:57:36 +02001197 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1198
1199 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1200 UTC should be specified as GMT (see ASN1_TIME_print())
1201 """
1202 from time import strptime
1203 from calendar import timegm
1204
1205 months = (
1206 "Jan","Feb","Mar","Apr","May","Jun",
1207 "Jul","Aug","Sep","Oct","Nov","Dec"
1208 )
1209 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1210 try:
1211 month_number = months.index(cert_time[:3].title()) + 1
1212 except ValueError:
1213 raise ValueError('time data %r does not match '
1214 'format "%%b%s"' % (cert_time, time_format))
1215 else:
1216 # found valid month
1217 tt = strptime(cert_time[3:], time_format)
1218 # return an integer, the previous mktime()-based implementation
1219 # returned a float (fractional seconds are always zero here).
1220 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001221
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1223PEM_FOOTER = "-----END CERTIFICATE-----"
1224
1225def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226 """Takes a certificate in binary DER format and returns the
1227 PEM version of it as a string."""
1228
Bill Janssen6e027db2007-11-15 22:23:56 +00001229 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001230 ss = [PEM_HEADER]
1231 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1232 ss.append(PEM_FOOTER + '\n')
1233 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234
1235def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236 """Takes a certificate in ASCII PEM format and returns the
1237 DER-encoded version of it as a byte sequence"""
1238
1239 if not pem_cert_string.startswith(PEM_HEADER):
1240 raise ValueError("Invalid PEM encoding; must start with %s"
1241 % PEM_HEADER)
1242 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1243 raise ValueError("Invalid PEM encoding; must end with %s"
1244 % PEM_FOOTER)
1245 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001246 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001247
Christian Heimes598894f2016-09-05 23:19:05 +02001248def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249 """Retrieve the certificate from the server at the specified address,
1250 and return it as a PEM-encoded string.
1251 If 'ca_certs' is specified, validate the server cert against it.
1252 If 'ssl_version' is specified, use it in the connection attempt."""
1253
1254 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001255 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256 cert_reqs = CERT_REQUIRED
1257 else:
1258 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001259 context = _create_stdlib_context(ssl_version,
1260 cert_reqs=cert_reqs,
1261 cafile=ca_certs)
1262 with create_connection(addr) as sock:
1263 with context.wrap_socket(sock) as sslsock:
1264 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265 return DER_cert_to_PEM_cert(dercert)
1266
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001267def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001268 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')