blob: b6161d0f178d95f4464868769973f67f928acf42 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
15
16 cert_time_to_seconds -- convert time string used for certificate
17 notBefore and notAfter functions to integer
18 seconds past the Epoch (the time values
19 returned from time.time())
20
21 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22 by the server running on HOST at port PORT. No
23 validation of the certificate is performed.
24
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
Christian Heimes598894f2016-09-05 23:19:05 +020054PROTOCOL_TLS
Christian Heimes5fe668c2016-09-12 00:01:11 +020055PROTOCOL_TLS_CLIENT
56PROTOCOL_TLS_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010058PROTOCOL_TLSv1_1
59PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010060
61The following constants identify various SSL alert message descriptions as per
62http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
63
64ALERT_DESCRIPTION_CLOSE_NOTIFY
65ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
66ALERT_DESCRIPTION_BAD_RECORD_MAC
67ALERT_DESCRIPTION_RECORD_OVERFLOW
68ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
69ALERT_DESCRIPTION_HANDSHAKE_FAILURE
70ALERT_DESCRIPTION_BAD_CERTIFICATE
71ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
72ALERT_DESCRIPTION_CERTIFICATE_REVOKED
73ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
74ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
75ALERT_DESCRIPTION_ILLEGAL_PARAMETER
76ALERT_DESCRIPTION_UNKNOWN_CA
77ALERT_DESCRIPTION_ACCESS_DENIED
78ALERT_DESCRIPTION_DECODE_ERROR
79ALERT_DESCRIPTION_DECRYPT_ERROR
80ALERT_DESCRIPTION_PROTOCOL_VERSION
81ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
82ALERT_DESCRIPTION_INTERNAL_ERROR
83ALERT_DESCRIPTION_USER_CANCELLED
84ALERT_DESCRIPTION_NO_RENEGOTIATION
85ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
86ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
87ALERT_DESCRIPTION_UNRECOGNIZED_NAME
88ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
89ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
90ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000091"""
92
Antoine Pitrouc481bfb2015-02-15 18:12:20 +010093import ipaddress
Antoine Pitrou59fdd672010-10-08 10:37:08 +000094import re
Christian Heimes46bebee2013-06-09 19:03:31 +020095import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020096import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010097from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020098from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +000099
100import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000101
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000102from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200103from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200104from _ssl import (
105 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700106 SSLSyscallError, SSLEOFError, SSLCertVerificationError
Antoine Pitrou41032a62011-10-27 23:56:55 +0200107 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100109from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
110try:
111 from _ssl import RAND_egd
112except ImportError:
113 # LibreSSL does not provide RAND_egd
114 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100115
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100116
Christian Heimescb5b68a2017-09-07 18:07:00 -0700117from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
Christian Heimes892d66e2018-01-29 14:10:18 +0100118from _ssl import _DEFAULT_CIPHERS
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200119from _ssl import _OPENSSL_API_VERSION
120
Christian Heimes3aeacad2016-09-10 00:19:35 +0200121
Ethan Furman24e837f2015-03-18 17:27:57 -0700122_IntEnum._convert(
Christian Heimes3aeacad2016-09-10 00:19:35 +0200123 '_SSLMethod', __name__,
124 lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
125 source=_ssl)
126
127_IntFlag._convert(
128 'Options', __name__,
129 lambda name: name.startswith('OP_'),
130 source=_ssl)
131
132_IntEnum._convert(
133 'AlertDescription', __name__,
134 lambda name: name.startswith('ALERT_DESCRIPTION_'),
135 source=_ssl)
136
137_IntEnum._convert(
138 'SSLErrorNumber', __name__,
139 lambda name: name.startswith('SSL_ERROR_'),
140 source=_ssl)
141
142_IntFlag._convert(
143 'VerifyFlags', __name__,
144 lambda name: name.startswith('VERIFY_'),
145 source=_ssl)
146
147_IntEnum._convert(
148 'VerifyMode', __name__,
149 lambda name: name.startswith('CERT_'),
150 source=_ssl)
151
Christian Heimes598894f2016-09-05 23:19:05 +0200152PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200153_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
154
Christian Heimes3aeacad2016-09-10 00:19:35 +0200155_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
156
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100157
Christian Heimes46bebee2013-06-09 19:03:31 +0200158if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100159 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200160
Antoine Pitrou15399c32011-04-28 19:23:55 +0200161from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100162from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000164import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700165import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000166
Andrew Svetlov0832af62012-12-18 23:10:48 +0200167
168socket_error = OSError # keep that public name in module namespace
169
Antoine Pitroud6494802011-07-21 01:11:30 +0200170if _ssl.HAS_TLS_UNIQUE:
171 CHANNEL_BINDING_TYPES = ['tls-unique']
172else:
173 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000174
Christian Heimes61d478c2018-01-27 15:51:38 +0100175HAS_NEVER_CHECK_COMMON_NAME = hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT')
176
Christian Heimes03d13c02016-09-06 20:06:47 +0200177
Christian Heimes892d66e2018-01-29 14:10:18 +0100178_RESTRICTED_SERVER_CIPHERS = _DEFAULT_CIPHERS
Christian Heimes4c05b472013-11-23 15:58:30 +0100179
Christian Heimes61d478c2018-01-27 15:51:38 +0100180CertificateError = SSLCertVerificationError
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000181
182
Mandeep Singhede2ac92017-11-27 04:01:27 +0530183def _dnsname_match(dn, hostname):
Georg Brandl72c98d32013-10-27 07:16:53 +0100184 """Matching according to RFC 6125, section 6.4.3
185
186 http://tools.ietf.org/html/rfc6125#section-6.4.3
187 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000188 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100189 if not dn:
190 return False
191
192 leftmost, *remainder = dn.split(r'.')
193
194 wildcards = leftmost.count('*')
Mandeep Singhede2ac92017-11-27 04:01:27 +0530195 if wildcards == 1 and len(leftmost) > 1:
196 # Only match wildcard in leftmost segment.
197 raise CertificateError(
198 "wildcard can only be present in the leftmost segment: " + repr(dn))
199
200 if wildcards > 1:
Georg Brandl72c98d32013-10-27 07:16:53 +0100201 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300202 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100203 # policy among SSL implementations showed it to be a
204 # reasonable choice.
205 raise CertificateError(
206 "too many wildcards in certificate DNS name: " + repr(dn))
207
208 # speed up common case w/o wildcards
209 if not wildcards:
210 return dn.lower() == hostname.lower()
211
212 # RFC 6125, section 6.4.3, subitem 1.
213 # The client SHOULD NOT attempt to match a presented identifier in which
214 # the wildcard character comprises a label other than the left-most label.
215 if leftmost == '*':
216 # When '*' is a fragment by itself, it matches a non-empty dotless
217 # fragment.
218 pats.append('[^.]+')
219 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
220 # RFC 6125, section 6.4.3, subitem 3.
221 # The client SHOULD NOT attempt to match a presented identifier
222 # where the wildcard character is embedded within an A-label or
223 # U-label of an internationalized domain name.
224 pats.append(re.escape(leftmost))
225 else:
226 # Otherwise, '*' matches any dotless string, e.g. www*
227 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
228
229 # add the remaining fragments, ignore any wildcards
230 for frag in remainder:
231 pats.append(re.escape(frag))
232
233 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
234 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000235
236
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100237def _ipaddress_match(ipname, host_ip):
238 """Exact matching of IP addresses.
239
240 RFC 6125 explicitly doesn't define an algorithm for this
241 (section 1.7.2 - "Out of Scope").
242 """
243 # OpenSSL may add a trailing newline to a subjectAltName's IP address
244 ip = ipaddress.ip_address(ipname.rstrip())
245 return ip == host_ip
246
247
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000248def match_hostname(cert, hostname):
249 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100250 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
251 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000252
253 CertificateError is raised on failure. On success, the function
254 returns nothing.
255 """
256 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100257 raise ValueError("empty or no certificate, match_hostname needs a "
258 "SSL socket or SSL context with either "
259 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100260 try:
261 host_ip = ipaddress.ip_address(hostname)
262 except ValueError:
263 # Not an IP address (common case)
264 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000265 dnsnames = []
266 san = cert.get('subjectAltName', ())
267 for key, value in san:
268 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100269 if host_ip is None and _dnsname_match(value, hostname):
270 return
271 dnsnames.append(value)
272 elif key == 'IP Address':
273 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000274 return
275 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200276 if not dnsnames:
277 # The subject is only checked when there is no dNSName entry
278 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000279 for sub in cert.get('subject', ()):
280 for key, value in sub:
281 # XXX according to RFC 2818, the most specific Common Name
282 # must be used.
283 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100284 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000285 return
286 dnsnames.append(value)
287 if len(dnsnames) > 1:
288 raise CertificateError("hostname %r "
289 "doesn't match either of %s"
290 % (hostname, ', '.join(map(repr, dnsnames))))
291 elif len(dnsnames) == 1:
292 raise CertificateError("hostname %r "
293 "doesn't match %r"
294 % (hostname, dnsnames[0]))
295 else:
296 raise CertificateError("no appropriate commonName or "
297 "subjectAltName fields were found")
298
299
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100300DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200301 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
302 "openssl_capath")
303
304def get_default_verify_paths():
305 """Return paths to default cafile and capath.
306 """
307 parts = _ssl.get_default_verify_paths()
308
309 # environment vars shadow paths
310 cafile = os.environ.get(parts[0], parts[1])
311 capath = os.environ.get(parts[2], parts[3])
312
313 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
314 capath if os.path.isdir(capath) else None,
315 *parts)
316
317
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100318class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
319 """ASN.1 object identifier lookup
320 """
321 __slots__ = ()
322
323 def __new__(cls, oid):
324 return super().__new__(cls, *_txt2obj(oid, name=False))
325
326 @classmethod
327 def fromnid(cls, nid):
328 """Create _ASN1Object from OpenSSL numeric ID
329 """
330 return super().__new__(cls, *_nid2obj(nid))
331
332 @classmethod
333 def fromname(cls, name):
334 """Create _ASN1Object from short name, long name or OID
335 """
336 return super().__new__(cls, *_txt2obj(name, name=True))
337
338
Christian Heimes72d28502013-11-23 13:56:58 +0100339class Purpose(_ASN1Object, _Enum):
340 """SSLContext purpose flags with X509v3 Extended Key Usage objects
341 """
342 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
343 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
344
345
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346class SSLContext(_SSLContext):
347 """An SSLContext holds various SSL-related configuration options and
348 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100349 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350
Christian Heimes4df60f12017-09-15 20:26:05 +0200351 sslsocket_class = None # SSLSocket is assigned later.
352 sslobject_class = None # SSLObject is assigned later.
353
Christian Heimes598894f2016-09-05 23:19:05 +0200354 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100355 self = _SSLContext.__new__(cls, protocol)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100356 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000357
Christian Heimes598894f2016-09-05 23:19:05 +0200358 def __init__(self, protocol=PROTOCOL_TLS):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000359 self.protocol = protocol
360
361 def wrap_socket(self, sock, server_side=False,
362 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000363 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200364 server_hostname=None, session=None):
Christian Heimes4df60f12017-09-15 20:26:05 +0200365 return self.sslsocket_class(
366 sock=sock,
367 server_side=server_side,
368 do_handshake_on_connect=do_handshake_on_connect,
369 suppress_ragged_eofs=suppress_ragged_eofs,
370 server_hostname=server_hostname,
371 _context=self,
372 _session=session
373 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000374
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200375 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200376 server_hostname=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200377 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
378 server_hostname=server_hostname)
Christian Heimes4df60f12017-09-15 20:26:05 +0200379 return self.sslobject_class(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200380
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100381 def set_npn_protocols(self, npn_protocols):
382 protos = bytearray()
383 for protocol in npn_protocols:
384 b = bytes(protocol, 'ascii')
385 if len(b) == 0 or len(b) > 255:
386 raise SSLError('NPN protocols must be 1 to 255 in length')
387 protos.append(len(b))
388 protos.extend(b)
389
390 self._set_npn_protocols(protos)
391
Benjamin Petersoncca27322015-01-23 16:35:37 -0500392 def set_alpn_protocols(self, alpn_protocols):
393 protos = bytearray()
394 for protocol in alpn_protocols:
395 b = bytes(protocol, 'ascii')
396 if len(b) == 0 or len(b) > 255:
397 raise SSLError('ALPN protocols must be 1 to 255 in length')
398 protos.append(len(b))
399 protos.extend(b)
400
401 self._set_alpn_protocols(protos)
402
Christian Heimes72d28502013-11-23 13:56:58 +0100403 def _load_windows_store_certs(self, storename, purpose):
404 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700405 try:
406 for cert, encoding, trust in enum_certificates(storename):
407 # CA certs are never PKCS#7 encoded
408 if encoding == "x509_asn":
409 if trust is True or purpose.oid in trust:
410 certs.extend(cert)
411 except PermissionError:
412 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700413 if certs:
414 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100415 return certs
416
417 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
418 if not isinstance(purpose, _ASN1Object):
419 raise TypeError(purpose)
420 if sys.platform == "win32":
421 for storename in self._windows_cert_stores:
422 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400423 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100424
Christian Heimes3aeacad2016-09-10 00:19:35 +0200425 @property
426 def options(self):
427 return Options(super().options)
428
429 @options.setter
430 def options(self, value):
431 super(SSLContext, SSLContext).options.__set__(self, value)
432
Christian Heimes61d478c2018-01-27 15:51:38 +0100433 if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
434 @property
435 def hostname_checks_common_name(self):
436 ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
437 return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
438
439 @hostname_checks_common_name.setter
440 def hostname_checks_common_name(self, value):
441 if value:
442 self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
443 else:
444 self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
445 else:
446 @property
447 def hostname_checks_common_name(self):
448 return True
449
Christian Heimes3aeacad2016-09-10 00:19:35 +0200450 @property
451 def verify_flags(self):
452 return VerifyFlags(super().verify_flags)
453
454 @verify_flags.setter
455 def verify_flags(self, value):
456 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
457
458 @property
459 def verify_mode(self):
460 value = super().verify_mode
461 try:
462 return VerifyMode(value)
463 except ValueError:
464 return value
465
466 @verify_mode.setter
467 def verify_mode(self, value):
468 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
469
Antoine Pitrou152efa22010-05-16 18:19:27 +0000470
Christian Heimes4c05b472013-11-23 15:58:30 +0100471def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
472 capath=None, cadata=None):
473 """Create a SSLContext object with default settings.
474
475 NOTE: The protocol and settings may change anytime without prior
476 deprecation. The values represent a fair balance between maximum
477 compatibility and security.
478 """
479 if not isinstance(purpose, _ASN1Object):
480 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400481
Christian Heimes358cfd42016-09-10 22:43:48 +0200482 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
483 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
484 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200485 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400486
Christian Heimes4c05b472013-11-23 15:58:30 +0100487 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400488 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100489 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100490 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400491
Christian Heimes4c05b472013-11-23 15:58:30 +0100492 if cafile or capath or cadata:
493 context.load_verify_locations(cafile, capath, cadata)
494 elif context.verify_mode != CERT_NONE:
495 # no explicit cafile, capath or cadata but the verify mode is
496 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
497 # root CA certificates for the given purpose. This may fail silently.
498 context.load_default_certs(purpose)
499 return context
500
Christian Heimesa170fa12017-09-15 20:27:30 +0200501def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100502 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100503 certfile=None, keyfile=None,
504 cafile=None, capath=None, cadata=None):
505 """Create a SSLContext object for Python stdlib modules
506
507 All Python stdlib modules shall use this function to create SSLContext
508 objects in order to keep common settings in one place. The configuration
509 is less restrict than create_default_context()'s to increase backward
510 compatibility.
511 """
512 if not isinstance(purpose, _ASN1Object):
513 raise TypeError(purpose)
514
Christian Heimes358cfd42016-09-10 22:43:48 +0200515 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
516 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
517 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100518 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100519
Christian Heimesa170fa12017-09-15 20:27:30 +0200520 if not check_hostname:
521 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100522 if cert_reqs is not None:
523 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200524 if check_hostname:
525 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100526
527 if keyfile and not certfile:
528 raise ValueError("certfile must be specified")
529 if certfile or keyfile:
530 context.load_cert_chain(certfile, keyfile)
531
532 # load CA root certs
533 if cafile or capath or cadata:
534 context.load_verify_locations(cafile, capath, cadata)
535 elif context.verify_mode != CERT_NONE:
536 # no explicit cafile, capath or cadata but the verify mode is
537 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
538 # root CA certificates for the given purpose. This may fail silently.
539 context.load_default_certs(purpose)
540
541 return context
542
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500543# Used by http.client if no context is explicitly passed.
544_create_default_https_context = create_default_context
545
546
547# Backwards compatibility alias, even though it's not a public name.
548_create_stdlib_context = _create_unverified_context
549
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200550
551class SSLObject:
552 """This class implements an interface on top of a low-level SSL object as
553 implemented by OpenSSL. This object captures the state of an SSL connection
554 but does not provide any network IO itself. IO needs to be performed
555 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
556
557 This class does not have a public constructor. Instances are returned by
558 ``SSLContext.wrap_bio``. This class is typically used by framework authors
559 that want to implement asynchronous IO for SSL through memory buffers.
560
561 When compared to ``SSLSocket``, this object lacks the following features:
562
563 * Any form of network IO incluging methods such as ``recv`` and ``send``.
564 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
565 """
566
Christian Heimes99a65702016-09-10 23:44:53 +0200567 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200568 self._sslobj = sslobj
569 # Note: _sslobj takes a weak reference to owner
570 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200571 if session is not None:
572 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200573
574 @property
575 def context(self):
576 """The SSLContext that is currently in use."""
577 return self._sslobj.context
578
579 @context.setter
580 def context(self, ctx):
581 self._sslobj.context = ctx
582
583 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200584 def session(self):
585 """The SSLSession for client socket."""
586 return self._sslobj.session
587
588 @session.setter
589 def session(self, session):
590 self._sslobj.session = session
591
592 @property
593 def session_reused(self):
594 """Was the client session reused during handshake"""
595 return self._sslobj.session_reused
596
597 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200598 def server_side(self):
599 """Whether this is a server-side socket."""
600 return self._sslobj.server_side
601
602 @property
603 def server_hostname(self):
604 """The currently set server hostname (for SNI), or ``None`` if no
605 server hostame is set."""
606 return self._sslobj.server_hostname
607
Martin Panterf6b1d662016-03-28 00:22:09 +0000608 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200609 """Read up to 'len' bytes from the SSL object and return them.
610
611 If 'buffer' is provided, read into this buffer and return the number of
612 bytes read.
613 """
614 if buffer is not None:
615 v = self._sslobj.read(len, buffer)
616 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000617 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200618 return v
619
620 def write(self, data):
621 """Write 'data' to the SSL object and return the number of bytes
622 written.
623
624 The 'data' argument must support the buffer interface.
625 """
626 return self._sslobj.write(data)
627
628 def getpeercert(self, binary_form=False):
629 """Returns a formatted version of the data in the certificate provided
630 by the other end of the SSL channel.
631
632 Return None if no certificate was provided, {} if a certificate was
633 provided, but not validated.
634 """
635 return self._sslobj.peer_certificate(binary_form)
636
637 def selected_npn_protocol(self):
638 """Return the currently selected NPN protocol as a string, or ``None``
639 if a next protocol was not negotiated or if NPN is not supported by one
640 of the peers."""
641 if _ssl.HAS_NPN:
642 return self._sslobj.selected_npn_protocol()
643
Benjamin Petersoncca27322015-01-23 16:35:37 -0500644 def selected_alpn_protocol(self):
645 """Return the currently selected ALPN protocol as a string, or ``None``
646 if a next protocol was not negotiated or if ALPN is not supported by one
647 of the peers."""
648 if _ssl.HAS_ALPN:
649 return self._sslobj.selected_alpn_protocol()
650
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200651 def cipher(self):
652 """Return the currently selected cipher as a 3-tuple ``(name,
653 ssl_version, secret_bits)``."""
654 return self._sslobj.cipher()
655
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600656 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500657 """Return a list of ciphers shared by the client during the handshake or
658 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600659 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600660 return self._sslobj.shared_ciphers()
661
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200662 def compression(self):
663 """Return the current compression algorithm in use, or ``None`` if
664 compression was not negotiated or not supported by one of the peers."""
665 return self._sslobj.compression()
666
667 def pending(self):
668 """Return the number of bytes that can be read immediately."""
669 return self._sslobj.pending()
670
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200671 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200672 """Start the SSL/TLS handshake."""
673 self._sslobj.do_handshake()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200674
675 def unwrap(self):
676 """Start the SSL shutdown handshake."""
677 return self._sslobj.shutdown()
678
679 def get_channel_binding(self, cb_type="tls-unique"):
680 """Get channel binding data for current connection. Raise ValueError
681 if the requested `cb_type` is not supported. Return bytes of the data
682 or None if the data is not available (e.g. before the handshake)."""
683 if cb_type not in CHANNEL_BINDING_TYPES:
684 raise ValueError("Unsupported channel binding type")
685 if cb_type != "tls-unique":
686 raise NotImplementedError(
687 "{0} channel binding type not implemented"
688 .format(cb_type))
689 return self._sslobj.tls_unique_cb()
690
691 def version(self):
692 """Return a string identifying the protocol version used by the
693 current SSL channel. """
694 return self._sslobj.version()
695
696
Antoine Pitrou152efa22010-05-16 18:19:27 +0000697class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000698 """This class implements a subtype of socket.socket that wraps
699 the underlying OS socket in an SSL context when necessary, and
700 provides read and write methods over that channel."""
701
Bill Janssen6e027db2007-11-15 22:23:56 +0000702 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000703 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200704 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000705 do_handshake_on_connect=True,
706 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100707 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000708 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200709 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000710
Antoine Pitrou152efa22010-05-16 18:19:27 +0000711 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100712 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000713 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000714 if server_side and not certfile:
715 raise ValueError("certfile must be specified for server-side "
716 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000717 if keyfile and not certfile:
718 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000719 if certfile and not keyfile:
720 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100721 self._context = SSLContext(ssl_version)
722 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000723 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100724 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000725 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100726 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100727 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100728 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000729 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100730 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000731 self.keyfile = keyfile
732 self.certfile = certfile
733 self.cert_reqs = cert_reqs
734 self.ssl_version = ssl_version
735 self.ca_certs = ca_certs
736 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100737 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
738 # mixed in.
739 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
740 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200741 if server_side:
742 if server_hostname:
743 raise ValueError("server_hostname can only be specified "
744 "in client mode")
745 if _session is not None:
746 raise ValueError("session can only be specified in "
747 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100748 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600749 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200750 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000751 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000752 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000753 self.do_handshake_on_connect = do_handshake_on_connect
754 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000755 if sock is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100756 super().__init__(family=sock.family,
757 type=sock.type,
758 proto=sock.proto,
759 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000760 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000761 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000762 elif fileno is not None:
Mads Jensen746cc752018-01-27 13:34:28 +0100763 super().__init__(fileno=fileno)
Bill Janssen6e027db2007-11-15 22:23:56 +0000764 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100765 super().__init__(family=family, type=type, proto=proto)
Bill Janssen6e027db2007-11-15 22:23:56 +0000766
Antoine Pitrou242db722013-05-01 20:52:07 +0200767 # See if we are connected
768 try:
769 self.getpeername()
770 except OSError as e:
771 if e.errno != errno.ENOTCONN:
772 raise
773 connected = False
774 else:
775 connected = True
776
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000777 self._closed = False
778 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000779 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000780 if connected:
781 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000782 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200783 sslobj = self._context._wrap_socket(self, server_side,
784 server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200785 self._sslobj = SSLObject(sslobj, owner=self,
786 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000787 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000788 timeout = self.gettimeout()
789 if timeout == 0.0:
790 # non-blocking
791 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000792 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000793
Christian Heimes1aa9a752013-12-02 02:41:19 +0100794 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000795 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100796 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200797
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100798 @property
799 def context(self):
800 return self._context
801
802 @context.setter
803 def context(self, ctx):
804 self._context = ctx
805 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000806
Christian Heimes99a65702016-09-10 23:44:53 +0200807 @property
808 def session(self):
809 """The SSLSession for client socket."""
810 if self._sslobj is not None:
811 return self._sslobj.session
812
813 @session.setter
814 def session(self, session):
815 self._session = session
816 if self._sslobj is not None:
817 self._sslobj.session = session
818
819 @property
820 def session_reused(self):
821 """Was the client session reused during handshake"""
822 if self._sslobj is not None:
823 return self._sslobj.session_reused
824
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000825 def dup(self):
826 raise NotImplemented("Can't dup() %s instances" %
827 self.__class__.__name__)
828
Bill Janssen6e027db2007-11-15 22:23:56 +0000829 def _checkClosed(self, msg=None):
830 # raise an exception here if you wish to check for spurious closes
831 pass
832
Antoine Pitrou242db722013-05-01 20:52:07 +0200833 def _check_connected(self):
834 if not self._connected:
835 # getpeername() will raise ENOTCONN if the socket is really
836 # not connected; note that we can be connected even without
837 # _connected being set, e.g. if connect() first returned
838 # EAGAIN.
839 self.getpeername()
840
Martin Panterf6b1d662016-03-28 00:22:09 +0000841 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000842 """Read up to LEN bytes and return them.
843 Return zero-length string on EOF."""
844
Bill Janssen6e027db2007-11-15 22:23:56 +0000845 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200846 if not self._sslobj:
847 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000848 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200849 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000850 except SSLError as x:
851 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000852 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000853 return 0
854 else:
855 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000856 else:
857 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000858
859 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000860 """Write DATA to the underlying SSL channel. Returns
861 number of bytes of DATA actually transmitted."""
862
Bill Janssen6e027db2007-11-15 22:23:56 +0000863 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200864 if not self._sslobj:
865 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000866 return self._sslobj.write(data)
867
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000869 """Returns a formatted version of the data in the
870 certificate provided by the other end of the SSL channel.
871 Return None if no certificate was provided, {} if a
872 certificate was provided, but not validated."""
873
Bill Janssen6e027db2007-11-15 22:23:56 +0000874 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200875 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200876 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100878 def selected_npn_protocol(self):
879 self._checkClosed()
880 if not self._sslobj or not _ssl.HAS_NPN:
881 return None
882 else:
883 return self._sslobj.selected_npn_protocol()
884
Benjamin Petersoncca27322015-01-23 16:35:37 -0500885 def selected_alpn_protocol(self):
886 self._checkClosed()
887 if not self._sslobj or not _ssl.HAS_ALPN:
888 return None
889 else:
890 return self._sslobj.selected_alpn_protocol()
891
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000892 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000893 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894 if not self._sslobj:
895 return None
896 else:
897 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000898
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600899 def shared_ciphers(self):
900 self._checkClosed()
901 if not self._sslobj:
902 return None
903 return self._sslobj.shared_ciphers()
904
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100905 def compression(self):
906 self._checkClosed()
907 if not self._sslobj:
908 return None
909 else:
910 return self._sslobj.compression()
911
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000912 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000913 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000914 if self._sslobj:
915 if flags != 0:
916 raise ValueError(
917 "non-zero flags not allowed in calls to send() on %s" %
918 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200919 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000920 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100921 return super().send(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000922
Antoine Pitroua468adc2010-09-14 14:43:44 +0000923 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000924 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000925 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000926 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000927 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000928 elif addr is None:
Mads Jensen746cc752018-01-27 13:34:28 +0100929 return super().sendto(data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000930 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100931 return super().sendto(data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000932
Nick Coghlan513886a2011-08-28 00:00:27 +1000933 def sendmsg(self, *args, **kwargs):
934 # Ensure programs don't send data unencrypted if they try to
935 # use this method.
936 raise NotImplementedError("sendmsg not allowed on instances of %s" %
937 self.__class__)
938
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000939 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000940 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000941 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000942 if flags != 0:
943 raise ValueError(
944 "non-zero flags not allowed in calls to sendall() on %s" %
945 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000946 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700947 with memoryview(data) as view, view.cast("B") as byte_view:
948 amount = len(byte_view)
949 while count < amount:
950 v = self.send(byte_view[count:])
951 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000952 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100953 return super().sendall(data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000954
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200955 def sendfile(self, file, offset=0, count=None):
956 """Send a file, possibly by using os.sendfile() if this is a
957 clear-text socket. Return the total number of bytes sent.
958 """
959 if self._sslobj is None:
960 # os.sendfile() works with plain sockets only
961 return super().sendfile(file, offset, count)
962 else:
963 return self._sendfile_use_send(file, offset, count)
964
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000965 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000966 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000967 if self._sslobj:
968 if flags != 0:
969 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000970 "non-zero flags not allowed in calls to recv() on %s" %
971 self.__class__)
972 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000973 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100974 return super().recv(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000975
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000976 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000977 self._checkClosed()
978 if buffer and (nbytes is None):
979 nbytes = len(buffer)
980 elif nbytes is None:
981 nbytes = 1024
982 if self._sslobj:
983 if flags != 0:
984 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000985 "non-zero flags not allowed in calls to recv_into() on %s" %
986 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000987 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000988 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100989 return super().recv_into(buffer, nbytes, flags)
Bill Janssen6e027db2007-11-15 22:23:56 +0000990
Antoine Pitroua468adc2010-09-14 14:43:44 +0000991 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000992 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000993 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000994 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000995 self.__class__)
996 else:
Mads Jensen746cc752018-01-27 13:34:28 +0100997 return super().recvfrom(buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000998
Bill Janssen58afe4c2008-09-08 16:45:19 +0000999 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1000 self._checkClosed()
1001 if self._sslobj:
1002 raise ValueError("recvfrom_into not allowed on instances of %s" %
1003 self.__class__)
1004 else:
Mads Jensen746cc752018-01-27 13:34:28 +01001005 return super().recvfrom_into(buffer, nbytes, flags)
Bill Janssen58afe4c2008-09-08 16:45:19 +00001006
Nick Coghlan513886a2011-08-28 00:00:27 +10001007 def recvmsg(self, *args, **kwargs):
1008 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1009 self.__class__)
1010
1011 def recvmsg_into(self, *args, **kwargs):
1012 raise NotImplementedError("recvmsg_into not allowed on instances of "
1013 "%s" % self.__class__)
1014
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001015 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001016 self._checkClosed()
1017 if self._sslobj:
1018 return self._sslobj.pending()
1019 else:
1020 return 0
1021
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001022 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001023 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001025 super().shutdown(how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001026
Ezio Melottidc55e672010-01-18 09:15:14 +00001027 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001028 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001029 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001030 self._sslobj = None
1031 return s
1032 else:
1033 raise ValueError("No SSL wrapper around " + str(self))
1034
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001035 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036 self._sslobj = None
Mads Jensen746cc752018-01-27 13:34:28 +01001037 super()._real_close()
Bill Janssen6e027db2007-11-15 22:23:56 +00001038
Bill Janssen48dc27c2007-12-05 03:38:10 +00001039 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001040 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001041 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001042 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001043 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001044 if timeout == 0.0 and block:
1045 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001046 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001047 finally:
1048 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001049
Antoine Pitroub4410db2011-05-18 18:51:06 +02001050 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001051 if self.server_side:
1052 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001053 # Here we assume that the socket is client-side, and not
1054 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001055 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001057 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001058 self._sslobj = SSLObject(sslobj, owner=self,
1059 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001060 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001061 if connect_ex:
Mads Jensen746cc752018-01-27 13:34:28 +01001062 rc = super().connect_ex(addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001063 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001064 rc = None
Mads Jensen746cc752018-01-27 13:34:28 +01001065 super().connect(addr)
Antoine Pitroub4410db2011-05-18 18:51:06 +02001066 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001067 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001068 if self.do_handshake_on_connect:
1069 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001070 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001071 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001072 self._sslobj = None
1073 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001074
1075 def connect(self, addr):
1076 """Connects to remote ADDR, and then wraps the connection in
1077 an SSL channel."""
1078 self._real_connect(addr, False)
1079
1080 def connect_ex(self, addr):
1081 """Connects to remote ADDR, and then wraps the connection in
1082 an SSL channel."""
1083 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001084
1085 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001086 """Accepts a new connection from a remote client, and returns
1087 a tuple containing that new connection wrapped with a server-side
1088 SSL channel, and the address of the remote client."""
1089
Mads Jensen746cc752018-01-27 13:34:28 +01001090 newsock, addr = super().accept()
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001091 newsock = self.context.wrap_socket(newsock,
1092 do_handshake_on_connect=self.do_handshake_on_connect,
1093 suppress_ragged_eofs=self.suppress_ragged_eofs,
1094 server_side=True)
1095 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001096
Antoine Pitroud6494802011-07-21 01:11:30 +02001097 def get_channel_binding(self, cb_type="tls-unique"):
1098 """Get channel binding data for current connection. Raise ValueError
1099 if the requested `cb_type` is not supported. Return bytes of the data
1100 or None if the data is not available (e.g. before the handshake).
1101 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001102 if self._sslobj is None:
1103 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001104 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001105
Antoine Pitrou47e40422014-09-04 21:00:10 +02001106 def version(self):
1107 """
1108 Return a string identifying the protocol version used by the
1109 current SSL channel, or None if there is no established channel.
1110 """
1111 if self._sslobj is None:
1112 return None
1113 return self._sslobj.version()
1114
Bill Janssen54cc54c2007-12-14 22:08:56 +00001115
Christian Heimes4df60f12017-09-15 20:26:05 +02001116# Python does not support forward declaration of types.
1117SSLContext.sslsocket_class = SSLSocket
1118SSLContext.sslobject_class = SSLObject
1119
1120
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121def wrap_socket(sock, keyfile=None, certfile=None,
1122 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001123 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001124 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001125 suppress_ragged_eofs=True,
1126 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001127 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001129 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001130 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001131 suppress_ragged_eofs=suppress_ragged_eofs,
1132 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Thomas Woutersed03b412007-08-28 21:37:11 +00001134# some utility functions
1135
1136def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001137 """Return the time in seconds since the Epoch, given the timestring
1138 representing the "notBefore" or "notAfter" date from a certificate
1139 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001140
Antoine Pitrouc695c952014-04-28 20:57:36 +02001141 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1142
1143 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1144 UTC should be specified as GMT (see ASN1_TIME_print())
1145 """
1146 from time import strptime
1147 from calendar import timegm
1148
1149 months = (
1150 "Jan","Feb","Mar","Apr","May","Jun",
1151 "Jul","Aug","Sep","Oct","Nov","Dec"
1152 )
1153 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1154 try:
1155 month_number = months.index(cert_time[:3].title()) + 1
1156 except ValueError:
1157 raise ValueError('time data %r does not match '
1158 'format "%%b%s"' % (cert_time, time_format))
1159 else:
1160 # found valid month
1161 tt = strptime(cert_time[3:], time_format)
1162 # return an integer, the previous mktime()-based implementation
1163 # returned a float (fractional seconds are always zero here).
1164 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001165
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1167PEM_FOOTER = "-----END CERTIFICATE-----"
1168
1169def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170 """Takes a certificate in binary DER format and returns the
1171 PEM version of it as a string."""
1172
Bill Janssen6e027db2007-11-15 22:23:56 +00001173 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001174 ss = [PEM_HEADER]
1175 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1176 ss.append(PEM_FOOTER + '\n')
1177 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178
1179def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180 """Takes a certificate in ASCII PEM format and returns the
1181 DER-encoded version of it as a byte sequence"""
1182
1183 if not pem_cert_string.startswith(PEM_HEADER):
1184 raise ValueError("Invalid PEM encoding; must start with %s"
1185 % PEM_HEADER)
1186 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1187 raise ValueError("Invalid PEM encoding; must end with %s"
1188 % PEM_FOOTER)
1189 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001190 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191
Christian Heimes598894f2016-09-05 23:19:05 +02001192def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 """Retrieve the certificate from the server at the specified address,
1194 and return it as a PEM-encoded string.
1195 If 'ca_certs' is specified, validate the server cert against it.
1196 If 'ssl_version' is specified, use it in the connection attempt."""
1197
1198 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001199 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200 cert_reqs = CERT_REQUIRED
1201 else:
1202 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001203 context = _create_stdlib_context(ssl_version,
1204 cert_reqs=cert_reqs,
1205 cafile=ca_certs)
1206 with create_connection(addr) as sock:
1207 with context.wrap_socket(sock) as sslsock:
1208 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 return DER_cert_to_PEM_cert(dercert)
1210
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001211def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001212 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')