blob: df5e98efc7bc405dcd633c639def00088d4dba03 [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
Thomas Woutersed03b412007-08-28 21:37:11 +000055PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056PROTOCOL_TLSv1_1
57PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010058
59The following constants identify various SSL alert message descriptions as per
60http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
61
62ALERT_DESCRIPTION_CLOSE_NOTIFY
63ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
64ALERT_DESCRIPTION_BAD_RECORD_MAC
65ALERT_DESCRIPTION_RECORD_OVERFLOW
66ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
67ALERT_DESCRIPTION_HANDSHAKE_FAILURE
68ALERT_DESCRIPTION_BAD_CERTIFICATE
69ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
70ALERT_DESCRIPTION_CERTIFICATE_REVOKED
71ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
72ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
73ALERT_DESCRIPTION_ILLEGAL_PARAMETER
74ALERT_DESCRIPTION_UNKNOWN_CA
75ALERT_DESCRIPTION_ACCESS_DENIED
76ALERT_DESCRIPTION_DECODE_ERROR
77ALERT_DESCRIPTION_DECRYPT_ERROR
78ALERT_DESCRIPTION_PROTOCOL_VERSION
79ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
80ALERT_DESCRIPTION_INTERNAL_ERROR
81ALERT_DESCRIPTION_USER_CANCELLED
82ALERT_DESCRIPTION_NO_RENEGOTIATION
83ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
84ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
85ALERT_DESCRIPTION_UNRECOGNIZED_NAME
86ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
87ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
88ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000089"""
90
Antoine Pitrouc481bfb2015-02-15 18:12:20 +010091import ipaddress
Christian Heimes05e8be12008-02-23 18:30:17 +000092import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000093import re
Christian Heimes46bebee2013-06-09 19:03:31 +020094import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020095import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010096from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020097from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +000098
99import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000100
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000101from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200102from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200103from _ssl import (
104 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
105 SSLSyscallError, SSLEOFError,
106 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100107from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100108from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
109try:
110 from _ssl import RAND_egd
111except ImportError:
112 # LibreSSL does not provide RAND_egd
113 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100114
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100115
Benjamin Petersoncca27322015-01-23 16:35:37 -0500116from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
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
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100150
Christian Heimes598894f2016-09-05 23:19:05 +0200151PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200152_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
153
Christian Heimes3aeacad2016-09-10 00:19:35 +0200154_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
155
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100156
Christian Heimes46bebee2013-06-09 19:03:31 +0200157if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100158 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200159
Antoine Pitrou15399c32011-04-28 19:23:55 +0200160from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100161from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000163import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700164import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000165
Andrew Svetlov0832af62012-12-18 23:10:48 +0200166
167socket_error = OSError # keep that public name in module namespace
168
Antoine Pitroud6494802011-07-21 01:11:30 +0200169if _ssl.HAS_TLS_UNIQUE:
170 CHANNEL_BINDING_TYPES = ['tls-unique']
171else:
172 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000173
Christian Heimes03d13c02016-09-06 20:06:47 +0200174
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100175# Disable weak or insecure ciphers by default
176# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400177# Enable a better set of ciphers by default
178# This list has been explicitly chosen to:
179# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
180# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200181# * Prefer AEAD over CBC for better performance and security
182# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
183# (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
184# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
185# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400186# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200187# * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
188# for security reasons
Donald Stufft79ccaa22014-03-21 21:33:34 -0400189_DEFAULT_CIPHERS = (
Christian Heimes03d13c02016-09-06 20:06:47 +0200190 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
191 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
192 '!aNULL:!eNULL:!MD5:!3DES'
193 )
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100194
Donald Stufft6a2ba942014-03-23 19:05:28 -0400195# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400196# This list has been explicitly chosen to:
197# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
198# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200199# * Prefer AEAD over CBC for better performance and security
200# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
201# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
202# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400203# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200204# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
205# 3DES for security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400206_RESTRICTED_SERVER_CIPHERS = (
Christian Heimes03d13c02016-09-06 20:06:47 +0200207 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
208 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
209 '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400210)
Christian Heimes4c05b472013-11-23 15:58:30 +0100211
Thomas Woutersed03b412007-08-28 21:37:11 +0000212
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000213class CertificateError(ValueError):
214 pass
215
216
Georg Brandl72c98d32013-10-27 07:16:53 +0100217def _dnsname_match(dn, hostname, max_wildcards=1):
218 """Matching according to RFC 6125, section 6.4.3
219
220 http://tools.ietf.org/html/rfc6125#section-6.4.3
221 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000222 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100223 if not dn:
224 return False
225
226 leftmost, *remainder = dn.split(r'.')
227
228 wildcards = leftmost.count('*')
229 if wildcards > max_wildcards:
230 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300231 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100232 # policy among SSL implementations showed it to be a
233 # reasonable choice.
234 raise CertificateError(
235 "too many wildcards in certificate DNS name: " + repr(dn))
236
237 # speed up common case w/o wildcards
238 if not wildcards:
239 return dn.lower() == hostname.lower()
240
241 # RFC 6125, section 6.4.3, subitem 1.
242 # The client SHOULD NOT attempt to match a presented identifier in which
243 # the wildcard character comprises a label other than the left-most label.
244 if leftmost == '*':
245 # When '*' is a fragment by itself, it matches a non-empty dotless
246 # fragment.
247 pats.append('[^.]+')
248 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
249 # RFC 6125, section 6.4.3, subitem 3.
250 # The client SHOULD NOT attempt to match a presented identifier
251 # where the wildcard character is embedded within an A-label or
252 # U-label of an internationalized domain name.
253 pats.append(re.escape(leftmost))
254 else:
255 # Otherwise, '*' matches any dotless string, e.g. www*
256 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
257
258 # add the remaining fragments, ignore any wildcards
259 for frag in remainder:
260 pats.append(re.escape(frag))
261
262 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
263 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000264
265
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100266def _ipaddress_match(ipname, host_ip):
267 """Exact matching of IP addresses.
268
269 RFC 6125 explicitly doesn't define an algorithm for this
270 (section 1.7.2 - "Out of Scope").
271 """
272 # OpenSSL may add a trailing newline to a subjectAltName's IP address
273 ip = ipaddress.ip_address(ipname.rstrip())
274 return ip == host_ip
275
276
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000277def match_hostname(cert, hostname):
278 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100279 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
280 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000281
282 CertificateError is raised on failure. On success, the function
283 returns nothing.
284 """
285 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100286 raise ValueError("empty or no certificate, match_hostname needs a "
287 "SSL socket or SSL context with either "
288 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100289 try:
290 host_ip = ipaddress.ip_address(hostname)
291 except ValueError:
292 # Not an IP address (common case)
293 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000294 dnsnames = []
295 san = cert.get('subjectAltName', ())
296 for key, value in san:
297 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100298 if host_ip is None and _dnsname_match(value, hostname):
299 return
300 dnsnames.append(value)
301 elif key == 'IP Address':
302 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000303 return
304 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200305 if not dnsnames:
306 # The subject is only checked when there is no dNSName entry
307 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000308 for sub in cert.get('subject', ()):
309 for key, value in sub:
310 # XXX according to RFC 2818, the most specific Common Name
311 # must be used.
312 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100313 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000314 return
315 dnsnames.append(value)
316 if len(dnsnames) > 1:
317 raise CertificateError("hostname %r "
318 "doesn't match either of %s"
319 % (hostname, ', '.join(map(repr, dnsnames))))
320 elif len(dnsnames) == 1:
321 raise CertificateError("hostname %r "
322 "doesn't match %r"
323 % (hostname, dnsnames[0]))
324 else:
325 raise CertificateError("no appropriate commonName or "
326 "subjectAltName fields were found")
327
328
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100329DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200330 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
331 "openssl_capath")
332
333def get_default_verify_paths():
334 """Return paths to default cafile and capath.
335 """
336 parts = _ssl.get_default_verify_paths()
337
338 # environment vars shadow paths
339 cafile = os.environ.get(parts[0], parts[1])
340 capath = os.environ.get(parts[2], parts[3])
341
342 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
343 capath if os.path.isdir(capath) else None,
344 *parts)
345
346
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100347class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
348 """ASN.1 object identifier lookup
349 """
350 __slots__ = ()
351
352 def __new__(cls, oid):
353 return super().__new__(cls, *_txt2obj(oid, name=False))
354
355 @classmethod
356 def fromnid(cls, nid):
357 """Create _ASN1Object from OpenSSL numeric ID
358 """
359 return super().__new__(cls, *_nid2obj(nid))
360
361 @classmethod
362 def fromname(cls, name):
363 """Create _ASN1Object from short name, long name or OID
364 """
365 return super().__new__(cls, *_txt2obj(name, name=True))
366
367
Christian Heimes72d28502013-11-23 13:56:58 +0100368class Purpose(_ASN1Object, _Enum):
369 """SSLContext purpose flags with X509v3 Extended Key Usage objects
370 """
371 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
372 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
373
374
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375class SSLContext(_SSLContext):
376 """An SSLContext holds various SSL-related configuration options and
377 data, such as certificates and possibly a private key."""
378
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100379 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100380 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381
Christian Heimes598894f2016-09-05 23:19:05 +0200382 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100383 self = _SSLContext.__new__(cls, protocol)
384 if protocol != _SSLv2_IF_EXISTS:
385 self.set_ciphers(_DEFAULT_CIPHERS)
386 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000387
Christian Heimes598894f2016-09-05 23:19:05 +0200388 def __init__(self, protocol=PROTOCOL_TLS):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000389 self.protocol = protocol
390
391 def wrap_socket(self, sock, server_side=False,
392 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000393 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200394 server_hostname=None, session=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000395 return SSLSocket(sock=sock, server_side=server_side,
396 do_handshake_on_connect=do_handshake_on_connect,
397 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000398 server_hostname=server_hostname,
Christian Heimes99a65702016-09-10 23:44:53 +0200399 _context=self, _session=session)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000400
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200401 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200402 server_hostname=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200403 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
404 server_hostname=server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200405 return SSLObject(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200406
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100407 def set_npn_protocols(self, npn_protocols):
408 protos = bytearray()
409 for protocol in npn_protocols:
410 b = bytes(protocol, 'ascii')
411 if len(b) == 0 or len(b) > 255:
412 raise SSLError('NPN protocols must be 1 to 255 in length')
413 protos.append(len(b))
414 protos.extend(b)
415
416 self._set_npn_protocols(protos)
417
Benjamin Petersoncca27322015-01-23 16:35:37 -0500418 def set_alpn_protocols(self, alpn_protocols):
419 protos = bytearray()
420 for protocol in alpn_protocols:
421 b = bytes(protocol, 'ascii')
422 if len(b) == 0 or len(b) > 255:
423 raise SSLError('ALPN protocols must be 1 to 255 in length')
424 protos.append(len(b))
425 protos.extend(b)
426
427 self._set_alpn_protocols(protos)
428
Christian Heimes72d28502013-11-23 13:56:58 +0100429 def _load_windows_store_certs(self, storename, purpose):
430 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700431 try:
432 for cert, encoding, trust in enum_certificates(storename):
433 # CA certs are never PKCS#7 encoded
434 if encoding == "x509_asn":
435 if trust is True or purpose.oid in trust:
436 certs.extend(cert)
437 except PermissionError:
438 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700439 if certs:
440 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100441 return certs
442
443 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
444 if not isinstance(purpose, _ASN1Object):
445 raise TypeError(purpose)
446 if sys.platform == "win32":
447 for storename in self._windows_cert_stores:
448 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400449 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100450
Christian Heimes3aeacad2016-09-10 00:19:35 +0200451 @property
452 def options(self):
453 return Options(super().options)
454
455 @options.setter
456 def options(self, value):
457 super(SSLContext, SSLContext).options.__set__(self, value)
458
459 @property
460 def verify_flags(self):
461 return VerifyFlags(super().verify_flags)
462
463 @verify_flags.setter
464 def verify_flags(self, value):
465 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
466
467 @property
468 def verify_mode(self):
469 value = super().verify_mode
470 try:
471 return VerifyMode(value)
472 except ValueError:
473 return value
474
475 @verify_mode.setter
476 def verify_mode(self, value):
477 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
478
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479
Christian Heimes4c05b472013-11-23 15:58:30 +0100480def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
481 capath=None, cadata=None):
482 """Create a SSLContext object with default settings.
483
484 NOTE: The protocol and settings may change anytime without prior
485 deprecation. The values represent a fair balance between maximum
486 compatibility and security.
487 """
488 if not isinstance(purpose, _ASN1Object):
489 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400490
Christian Heimes358cfd42016-09-10 22:43:48 +0200491 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
492 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
493 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200494 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400495
Christian Heimes4c05b472013-11-23 15:58:30 +0100496 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400497 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100498 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100499 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400500 elif purpose == Purpose.CLIENT_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400501 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
502
Christian Heimes4c05b472013-11-23 15:58:30 +0100503 if cafile or capath or cadata:
504 context.load_verify_locations(cafile, capath, cadata)
505 elif context.verify_mode != CERT_NONE:
506 # no explicit cafile, capath or cadata but the verify mode is
507 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
508 # root CA certificates for the given purpose. This may fail silently.
509 context.load_default_certs(purpose)
510 return context
511
Christian Heimes598894f2016-09-05 23:19:05 +0200512def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100513 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100514 certfile=None, keyfile=None,
515 cafile=None, capath=None, cadata=None):
516 """Create a SSLContext object for Python stdlib modules
517
518 All Python stdlib modules shall use this function to create SSLContext
519 objects in order to keep common settings in one place. The configuration
520 is less restrict than create_default_context()'s to increase backward
521 compatibility.
522 """
523 if not isinstance(purpose, _ASN1Object):
524 raise TypeError(purpose)
525
Christian Heimes358cfd42016-09-10 22:43:48 +0200526 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
527 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
528 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100529 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100530
531 if cert_reqs is not None:
532 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100533 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100534
535 if keyfile and not certfile:
536 raise ValueError("certfile must be specified")
537 if certfile or keyfile:
538 context.load_cert_chain(certfile, keyfile)
539
540 # load CA root certs
541 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
549 return context
550
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500551# Used by http.client if no context is explicitly passed.
552_create_default_https_context = create_default_context
553
554
555# Backwards compatibility alias, even though it's not a public name.
556_create_stdlib_context = _create_unverified_context
557
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200558
559class SSLObject:
560 """This class implements an interface on top of a low-level SSL object as
561 implemented by OpenSSL. This object captures the state of an SSL connection
562 but does not provide any network IO itself. IO needs to be performed
563 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
564
565 This class does not have a public constructor. Instances are returned by
566 ``SSLContext.wrap_bio``. This class is typically used by framework authors
567 that want to implement asynchronous IO for SSL through memory buffers.
568
569 When compared to ``SSLSocket``, this object lacks the following features:
570
571 * Any form of network IO incluging methods such as ``recv`` and ``send``.
572 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
573 """
574
Christian Heimes99a65702016-09-10 23:44:53 +0200575 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200576 self._sslobj = sslobj
577 # Note: _sslobj takes a weak reference to owner
578 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200579 if session is not None:
580 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200581
582 @property
583 def context(self):
584 """The SSLContext that is currently in use."""
585 return self._sslobj.context
586
587 @context.setter
588 def context(self, ctx):
589 self._sslobj.context = ctx
590
591 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200592 def session(self):
593 """The SSLSession for client socket."""
594 return self._sslobj.session
595
596 @session.setter
597 def session(self, session):
598 self._sslobj.session = session
599
600 @property
601 def session_reused(self):
602 """Was the client session reused during handshake"""
603 return self._sslobj.session_reused
604
605 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200606 def server_side(self):
607 """Whether this is a server-side socket."""
608 return self._sslobj.server_side
609
610 @property
611 def server_hostname(self):
612 """The currently set server hostname (for SNI), or ``None`` if no
613 server hostame is set."""
614 return self._sslobj.server_hostname
615
Martin Panterf6b1d662016-03-28 00:22:09 +0000616 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200617 """Read up to 'len' bytes from the SSL object and return them.
618
619 If 'buffer' is provided, read into this buffer and return the number of
620 bytes read.
621 """
622 if buffer is not None:
623 v = self._sslobj.read(len, buffer)
624 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000625 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200626 return v
627
628 def write(self, data):
629 """Write 'data' to the SSL object and return the number of bytes
630 written.
631
632 The 'data' argument must support the buffer interface.
633 """
634 return self._sslobj.write(data)
635
636 def getpeercert(self, binary_form=False):
637 """Returns a formatted version of the data in the certificate provided
638 by the other end of the SSL channel.
639
640 Return None if no certificate was provided, {} if a certificate was
641 provided, but not validated.
642 """
643 return self._sslobj.peer_certificate(binary_form)
644
645 def selected_npn_protocol(self):
646 """Return the currently selected NPN protocol as a string, or ``None``
647 if a next protocol was not negotiated or if NPN is not supported by one
648 of the peers."""
649 if _ssl.HAS_NPN:
650 return self._sslobj.selected_npn_protocol()
651
Benjamin Petersoncca27322015-01-23 16:35:37 -0500652 def selected_alpn_protocol(self):
653 """Return the currently selected ALPN protocol as a string, or ``None``
654 if a next protocol was not negotiated or if ALPN is not supported by one
655 of the peers."""
656 if _ssl.HAS_ALPN:
657 return self._sslobj.selected_alpn_protocol()
658
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200659 def cipher(self):
660 """Return the currently selected cipher as a 3-tuple ``(name,
661 ssl_version, secret_bits)``."""
662 return self._sslobj.cipher()
663
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600664 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500665 """Return a list of ciphers shared by the client during the handshake or
666 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600667 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600668 return self._sslobj.shared_ciphers()
669
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200670 def compression(self):
671 """Return the current compression algorithm in use, or ``None`` if
672 compression was not negotiated or not supported by one of the peers."""
673 return self._sslobj.compression()
674
675 def pending(self):
676 """Return the number of bytes that can be read immediately."""
677 return self._sslobj.pending()
678
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200679 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200680 """Start the SSL/TLS handshake."""
681 self._sslobj.do_handshake()
682 if self.context.check_hostname:
683 if not self.server_hostname:
684 raise ValueError("check_hostname needs server_hostname "
685 "argument")
686 match_hostname(self.getpeercert(), self.server_hostname)
687
688 def unwrap(self):
689 """Start the SSL shutdown handshake."""
690 return self._sslobj.shutdown()
691
692 def get_channel_binding(self, cb_type="tls-unique"):
693 """Get channel binding data for current connection. Raise ValueError
694 if the requested `cb_type` is not supported. Return bytes of the data
695 or None if the data is not available (e.g. before the handshake)."""
696 if cb_type not in CHANNEL_BINDING_TYPES:
697 raise ValueError("Unsupported channel binding type")
698 if cb_type != "tls-unique":
699 raise NotImplementedError(
700 "{0} channel binding type not implemented"
701 .format(cb_type))
702 return self._sslobj.tls_unique_cb()
703
704 def version(self):
705 """Return a string identifying the protocol version used by the
706 current SSL channel. """
707 return self._sslobj.version()
708
709
Antoine Pitrou152efa22010-05-16 18:19:27 +0000710class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000711 """This class implements a subtype of socket.socket that wraps
712 the underlying OS socket in an SSL context when necessary, and
713 provides read and write methods over that channel."""
714
Bill Janssen6e027db2007-11-15 22:23:56 +0000715 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000716 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200717 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000718 do_handshake_on_connect=True,
719 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100720 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000721 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200722 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000723
Antoine Pitrou152efa22010-05-16 18:19:27 +0000724 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100725 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000726 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000727 if server_side and not certfile:
728 raise ValueError("certfile must be specified for server-side "
729 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000730 if keyfile and not certfile:
731 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000732 if certfile and not keyfile:
733 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100734 self._context = SSLContext(ssl_version)
735 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000736 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100737 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000738 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100739 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100740 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100741 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000742 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100743 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000744 self.keyfile = keyfile
745 self.certfile = certfile
746 self.cert_reqs = cert_reqs
747 self.ssl_version = ssl_version
748 self.ca_certs = ca_certs
749 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100750 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
751 # mixed in.
752 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
753 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200754 if server_side:
755 if server_hostname:
756 raise ValueError("server_hostname can only be specified "
757 "in client mode")
758 if _session is not None:
759 raise ValueError("session can only be specified in "
760 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100761 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600762 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200763 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000764 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000765 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000766 self.do_handshake_on_connect = do_handshake_on_connect
767 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000768 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000769 socket.__init__(self,
770 family=sock.family,
771 type=sock.type,
772 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000773 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000774 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000775 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000776 elif fileno is not None:
777 socket.__init__(self, fileno=fileno)
778 else:
779 socket.__init__(self, family=family, type=type, proto=proto)
780
Antoine Pitrou242db722013-05-01 20:52:07 +0200781 # See if we are connected
782 try:
783 self.getpeername()
784 except OSError as e:
785 if e.errno != errno.ENOTCONN:
786 raise
787 connected = False
788 else:
789 connected = True
790
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000791 self._closed = False
792 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000793 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000794 if connected:
795 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000796 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200797 sslobj = self._context._wrap_socket(self, server_side,
798 server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200799 self._sslobj = SSLObject(sslobj, owner=self,
800 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000801 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000802 timeout = self.gettimeout()
803 if timeout == 0.0:
804 # non-blocking
805 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000806 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000807
Christian Heimes1aa9a752013-12-02 02:41:19 +0100808 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000809 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100810 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200811
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100812 @property
813 def context(self):
814 return self._context
815
816 @context.setter
817 def context(self, ctx):
818 self._context = ctx
819 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000820
Christian Heimes99a65702016-09-10 23:44:53 +0200821 @property
822 def session(self):
823 """The SSLSession for client socket."""
824 if self._sslobj is not None:
825 return self._sslobj.session
826
827 @session.setter
828 def session(self, session):
829 self._session = session
830 if self._sslobj is not None:
831 self._sslobj.session = session
832
833 @property
834 def session_reused(self):
835 """Was the client session reused during handshake"""
836 if self._sslobj is not None:
837 return self._sslobj.session_reused
838
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000839 def dup(self):
840 raise NotImplemented("Can't dup() %s instances" %
841 self.__class__.__name__)
842
Bill Janssen6e027db2007-11-15 22:23:56 +0000843 def _checkClosed(self, msg=None):
844 # raise an exception here if you wish to check for spurious closes
845 pass
846
Antoine Pitrou242db722013-05-01 20:52:07 +0200847 def _check_connected(self):
848 if not self._connected:
849 # getpeername() will raise ENOTCONN if the socket is really
850 # not connected; note that we can be connected even without
851 # _connected being set, e.g. if connect() first returned
852 # EAGAIN.
853 self.getpeername()
854
Martin Panterf6b1d662016-03-28 00:22:09 +0000855 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000856 """Read up to LEN bytes and return them.
857 Return zero-length string on EOF."""
858
Bill Janssen6e027db2007-11-15 22:23:56 +0000859 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200860 if not self._sslobj:
861 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000862 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200863 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000864 except SSLError as x:
865 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000866 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000867 return 0
868 else:
869 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000870 else:
871 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000872
873 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000874 """Write DATA to the underlying SSL channel. Returns
875 number of bytes of DATA actually transmitted."""
876
Bill Janssen6e027db2007-11-15 22:23:56 +0000877 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200878 if not self._sslobj:
879 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000880 return self._sslobj.write(data)
881
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000883 """Returns a formatted version of the data in the
884 certificate provided by the other end of the SSL channel.
885 Return None if no certificate was provided, {} if a
886 certificate was provided, but not validated."""
887
Bill Janssen6e027db2007-11-15 22:23:56 +0000888 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200889 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200890 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100892 def selected_npn_protocol(self):
893 self._checkClosed()
894 if not self._sslobj or not _ssl.HAS_NPN:
895 return None
896 else:
897 return self._sslobj.selected_npn_protocol()
898
Benjamin Petersoncca27322015-01-23 16:35:37 -0500899 def selected_alpn_protocol(self):
900 self._checkClosed()
901 if not self._sslobj or not _ssl.HAS_ALPN:
902 return None
903 else:
904 return self._sslobj.selected_alpn_protocol()
905
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000906 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000907 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908 if not self._sslobj:
909 return None
910 else:
911 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000912
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600913 def shared_ciphers(self):
914 self._checkClosed()
915 if not self._sslobj:
916 return None
917 return self._sslobj.shared_ciphers()
918
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100919 def compression(self):
920 self._checkClosed()
921 if not self._sslobj:
922 return None
923 else:
924 return self._sslobj.compression()
925
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000926 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000927 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000928 if self._sslobj:
929 if flags != 0:
930 raise ValueError(
931 "non-zero flags not allowed in calls to send() on %s" %
932 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200933 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000934 else:
935 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000936
Antoine Pitroua468adc2010-09-14 14:43:44 +0000937 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000938 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000939 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000940 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000941 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000942 elif addr is None:
943 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000944 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000945 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000946
Nick Coghlan513886a2011-08-28 00:00:27 +1000947 def sendmsg(self, *args, **kwargs):
948 # Ensure programs don't send data unencrypted if they try to
949 # use this method.
950 raise NotImplementedError("sendmsg not allowed on instances of %s" %
951 self.__class__)
952
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000953 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000954 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000955 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000956 if flags != 0:
957 raise ValueError(
958 "non-zero flags not allowed in calls to sendall() on %s" %
959 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000960 amount = len(data)
961 count = 0
962 while (count < amount):
963 v = self.send(data[count:])
964 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000965 else:
966 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000967
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200968 def sendfile(self, file, offset=0, count=None):
969 """Send a file, possibly by using os.sendfile() if this is a
970 clear-text socket. Return the total number of bytes sent.
971 """
972 if self._sslobj is None:
973 # os.sendfile() works with plain sockets only
974 return super().sendfile(file, offset, count)
975 else:
976 return self._sendfile_use_send(file, offset, count)
977
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000978 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000979 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000980 if self._sslobj:
981 if flags != 0:
982 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000983 "non-zero flags not allowed in calls to recv() on %s" %
984 self.__class__)
985 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000986 else:
987 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000988
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000989 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000990 self._checkClosed()
991 if buffer and (nbytes is None):
992 nbytes = len(buffer)
993 elif nbytes is None:
994 nbytes = 1024
995 if self._sslobj:
996 if flags != 0:
997 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000998 "non-zero flags not allowed in calls to recv_into() on %s" %
999 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001000 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001001 else:
1002 return socket.recv_into(self, buffer, nbytes, flags)
1003
Antoine Pitroua468adc2010-09-14 14:43:44 +00001004 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001005 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001006 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001007 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001008 self.__class__)
1009 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +00001010 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001011
Bill Janssen58afe4c2008-09-08 16:45:19 +00001012 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1013 self._checkClosed()
1014 if self._sslobj:
1015 raise ValueError("recvfrom_into not allowed on instances of %s" %
1016 self.__class__)
1017 else:
1018 return socket.recvfrom_into(self, buffer, nbytes, flags)
1019
Nick Coghlan513886a2011-08-28 00:00:27 +10001020 def recvmsg(self, *args, **kwargs):
1021 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1022 self.__class__)
1023
1024 def recvmsg_into(self, *args, **kwargs):
1025 raise NotImplementedError("recvmsg_into not allowed on instances of "
1026 "%s" % self.__class__)
1027
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001028 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001029 self._checkClosed()
1030 if self._sslobj:
1031 return self._sslobj.pending()
1032 else:
1033 return 0
1034
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001035 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001036 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001038 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001039
Ezio Melottidc55e672010-01-18 09:15:14 +00001040 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001041 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001042 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001043 self._sslobj = None
1044 return s
1045 else:
1046 raise ValueError("No SSL wrapper around " + str(self))
1047
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001048 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +00001050 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001051
Bill Janssen48dc27c2007-12-05 03:38:10 +00001052 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001053 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001054 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001055 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001056 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001057 if timeout == 0.0 and block:
1058 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001059 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001060 finally:
1061 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001062
Antoine Pitroub4410db2011-05-18 18:51:06 +02001063 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001064 if self.server_side:
1065 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001066 # Here we assume that the socket is client-side, and not
1067 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001068 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001069 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001070 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001071 self._sslobj = SSLObject(sslobj, owner=self,
1072 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001073 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001074 if connect_ex:
1075 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001076 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001077 rc = None
1078 socket.connect(self, addr)
1079 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001080 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001081 if self.do_handshake_on_connect:
1082 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001083 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001084 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001085 self._sslobj = None
1086 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001087
1088 def connect(self, addr):
1089 """Connects to remote ADDR, and then wraps the connection in
1090 an SSL channel."""
1091 self._real_connect(addr, False)
1092
1093 def connect_ex(self, addr):
1094 """Connects to remote ADDR, and then wraps the connection in
1095 an SSL channel."""
1096 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001097
1098 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001099 """Accepts a new connection from a remote client, and returns
1100 a tuple containing that new connection wrapped with a server-side
1101 SSL channel, and the address of the remote client."""
1102
1103 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001104 newsock = self.context.wrap_socket(newsock,
1105 do_handshake_on_connect=self.do_handshake_on_connect,
1106 suppress_ragged_eofs=self.suppress_ragged_eofs,
1107 server_side=True)
1108 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
Antoine Pitroud6494802011-07-21 01:11:30 +02001110 def get_channel_binding(self, cb_type="tls-unique"):
1111 """Get channel binding data for current connection. Raise ValueError
1112 if the requested `cb_type` is not supported. Return bytes of the data
1113 or None if the data is not available (e.g. before the handshake).
1114 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001115 if self._sslobj is None:
1116 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001117 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001118
Antoine Pitrou47e40422014-09-04 21:00:10 +02001119 def version(self):
1120 """
1121 Return a string identifying the protocol version used by the
1122 current SSL channel, or None if there is no established channel.
1123 """
1124 if self._sslobj is None:
1125 return None
1126 return self._sslobj.version()
1127
Bill Janssen54cc54c2007-12-14 22:08:56 +00001128
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129def wrap_socket(sock, keyfile=None, certfile=None,
1130 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001131 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001132 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001133 suppress_ragged_eofs=True,
1134 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001135 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001137 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001138 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001139 suppress_ragged_eofs=suppress_ragged_eofs,
1140 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141
Thomas Woutersed03b412007-08-28 21:37:11 +00001142# some utility functions
1143
1144def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001145 """Return the time in seconds since the Epoch, given the timestring
1146 representing the "notBefore" or "notAfter" date from a certificate
1147 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001148
Antoine Pitrouc695c952014-04-28 20:57:36 +02001149 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1150
1151 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1152 UTC should be specified as GMT (see ASN1_TIME_print())
1153 """
1154 from time import strptime
1155 from calendar import timegm
1156
1157 months = (
1158 "Jan","Feb","Mar","Apr","May","Jun",
1159 "Jul","Aug","Sep","Oct","Nov","Dec"
1160 )
1161 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1162 try:
1163 month_number = months.index(cert_time[:3].title()) + 1
1164 except ValueError:
1165 raise ValueError('time data %r does not match '
1166 'format "%%b%s"' % (cert_time, time_format))
1167 else:
1168 # found valid month
1169 tt = strptime(cert_time[3:], time_format)
1170 # return an integer, the previous mktime()-based implementation
1171 # returned a float (fractional seconds are always zero here).
1172 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001173
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1175PEM_FOOTER = "-----END CERTIFICATE-----"
1176
1177def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178 """Takes a certificate in binary DER format and returns the
1179 PEM version of it as a string."""
1180
Bill Janssen6e027db2007-11-15 22:23:56 +00001181 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1182 return (PEM_HEADER + '\n' +
1183 textwrap.fill(f, 64) + '\n' +
1184 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001185
1186def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 """Takes a certificate in ASCII PEM format and returns the
1188 DER-encoded version of it as a byte sequence"""
1189
1190 if not pem_cert_string.startswith(PEM_HEADER):
1191 raise ValueError("Invalid PEM encoding; must start with %s"
1192 % PEM_HEADER)
1193 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1194 raise ValueError("Invalid PEM encoding; must end with %s"
1195 % PEM_FOOTER)
1196 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001197 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Christian Heimes598894f2016-09-05 23:19:05 +02001199def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200 """Retrieve the certificate from the server at the specified address,
1201 and return it as a PEM-encoded string.
1202 If 'ca_certs' is specified, validate the server cert against it.
1203 If 'ssl_version' is specified, use it in the connection attempt."""
1204
1205 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001206 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207 cert_reqs = CERT_REQUIRED
1208 else:
1209 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001210 context = _create_stdlib_context(ssl_version,
1211 cert_reqs=cert_reqs,
1212 cafile=ca_certs)
1213 with create_connection(addr) as sock:
1214 with context.wrap_socket(sock) as sslsock:
1215 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216 return DER_cert_to_PEM_cert(dercert)
1217
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001218def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001219 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')