blob: 062e8021180ef6bfe3aa486c8ef147db4a5b9b5a [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
Christian Heimes05e8be12008-02-23 18:30:17 +000094import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000095import re
Christian Heimes46bebee2013-06-09 19:03:31 +020096import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020097import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010098from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020099from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +0000100
101import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000102
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000103from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200104from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200105from _ssl import (
106 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700107 SSLSyscallError, SSLEOFError, SSLCertVerificationError
Antoine Pitrou41032a62011-10-27 23:56:55 +0200108 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100109from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100110from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
111try:
112 from _ssl import RAND_egd
113except ImportError:
114 # LibreSSL does not provide RAND_egd
115 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100116
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100117
Christian Heimescb5b68a2017-09-07 18:07:00 -0700118from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
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
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100152
Christian Heimes598894f2016-09-05 23:19:05 +0200153PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200154_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
155
Christian Heimes3aeacad2016-09-10 00:19:35 +0200156_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
157
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100158
Christian Heimes46bebee2013-06-09 19:03:31 +0200159if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100160 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200161
Antoine Pitrou15399c32011-04-28 19:23:55 +0200162from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100163from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000164import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000165import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700166import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000167
Andrew Svetlov0832af62012-12-18 23:10:48 +0200168
169socket_error = OSError # keep that public name in module namespace
170
Antoine Pitroud6494802011-07-21 01:11:30 +0200171if _ssl.HAS_TLS_UNIQUE:
172 CHANNEL_BINDING_TYPES = ['tls-unique']
173else:
174 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
Christian Heimes03d13c02016-09-06 20:06:47 +0200176
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100177# Disable weak or insecure ciphers by default
178# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400179# Enable a better set of ciphers by default
180# This list has been explicitly chosen to:
Christian Heimescb5b68a2017-09-07 18:07:00 -0700181# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
Donald Stufft79ccaa22014-03-21 21:33:34 -0400182# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
183# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200184# * Prefer AEAD over CBC for better performance and security
185# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
186# (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
187# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
188# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400189# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200190# * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
191# for security reasons
Donald Stufft79ccaa22014-03-21 21:33:34 -0400192_DEFAULT_CIPHERS = (
Christian Heimescb5b68a2017-09-07 18:07:00 -0700193 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
194 'TLS13-AES-128-GCM-SHA256:'
Christian Heimes03d13c02016-09-06 20:06:47 +0200195 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
196 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
197 '!aNULL:!eNULL:!MD5:!3DES'
198 )
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100199
Donald Stufft6a2ba942014-03-23 19:05:28 -0400200# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400201# This list has been explicitly chosen to:
Christian Heimescb5b68a2017-09-07 18:07:00 -0700202# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
Donald Stufft79ccaa22014-03-21 21:33:34 -0400203# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
204# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200205# * Prefer AEAD over CBC for better performance and security
206# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
207# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
208# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400209# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200210# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
211# 3DES for security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400212_RESTRICTED_SERVER_CIPHERS = (
Christian Heimescb5b68a2017-09-07 18:07:00 -0700213 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
214 'TLS13-AES-128-GCM-SHA256:'
Christian Heimes03d13c02016-09-06 20:06:47 +0200215 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
216 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
217 '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400218)
Christian Heimes4c05b472013-11-23 15:58:30 +0100219
Thomas Woutersed03b412007-08-28 21:37:11 +0000220
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000221class CertificateError(ValueError):
222 pass
223
224
Georg Brandl72c98d32013-10-27 07:16:53 +0100225def _dnsname_match(dn, hostname, max_wildcards=1):
226 """Matching according to RFC 6125, section 6.4.3
227
228 http://tools.ietf.org/html/rfc6125#section-6.4.3
229 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000230 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100231 if not dn:
232 return False
233
234 leftmost, *remainder = dn.split(r'.')
235
236 wildcards = leftmost.count('*')
237 if wildcards > max_wildcards:
238 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300239 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100240 # policy among SSL implementations showed it to be a
241 # reasonable choice.
242 raise CertificateError(
243 "too many wildcards in certificate DNS name: " + repr(dn))
244
245 # speed up common case w/o wildcards
246 if not wildcards:
247 return dn.lower() == hostname.lower()
248
249 # RFC 6125, section 6.4.3, subitem 1.
250 # The client SHOULD NOT attempt to match a presented identifier in which
251 # the wildcard character comprises a label other than the left-most label.
252 if leftmost == '*':
253 # When '*' is a fragment by itself, it matches a non-empty dotless
254 # fragment.
255 pats.append('[^.]+')
256 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
257 # RFC 6125, section 6.4.3, subitem 3.
258 # The client SHOULD NOT attempt to match a presented identifier
259 # where the wildcard character is embedded within an A-label or
260 # U-label of an internationalized domain name.
261 pats.append(re.escape(leftmost))
262 else:
263 # Otherwise, '*' matches any dotless string, e.g. www*
264 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
265
266 # add the remaining fragments, ignore any wildcards
267 for frag in remainder:
268 pats.append(re.escape(frag))
269
270 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
271 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000272
273
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100274def _ipaddress_match(ipname, host_ip):
275 """Exact matching of IP addresses.
276
277 RFC 6125 explicitly doesn't define an algorithm for this
278 (section 1.7.2 - "Out of Scope").
279 """
280 # OpenSSL may add a trailing newline to a subjectAltName's IP address
281 ip = ipaddress.ip_address(ipname.rstrip())
282 return ip == host_ip
283
284
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000285def match_hostname(cert, hostname):
286 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100287 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
288 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000289
290 CertificateError is raised on failure. On success, the function
291 returns nothing.
292 """
293 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100294 raise ValueError("empty or no certificate, match_hostname needs a "
295 "SSL socket or SSL context with either "
296 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100297 try:
298 host_ip = ipaddress.ip_address(hostname)
299 except ValueError:
300 # Not an IP address (common case)
301 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000302 dnsnames = []
303 san = cert.get('subjectAltName', ())
304 for key, value in san:
305 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100306 if host_ip is None and _dnsname_match(value, hostname):
307 return
308 dnsnames.append(value)
309 elif key == 'IP Address':
310 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000311 return
312 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200313 if not dnsnames:
314 # The subject is only checked when there is no dNSName entry
315 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000316 for sub in cert.get('subject', ()):
317 for key, value in sub:
318 # XXX according to RFC 2818, the most specific Common Name
319 # must be used.
320 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100321 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000322 return
323 dnsnames.append(value)
324 if len(dnsnames) > 1:
325 raise CertificateError("hostname %r "
326 "doesn't match either of %s"
327 % (hostname, ', '.join(map(repr, dnsnames))))
328 elif len(dnsnames) == 1:
329 raise CertificateError("hostname %r "
330 "doesn't match %r"
331 % (hostname, dnsnames[0]))
332 else:
333 raise CertificateError("no appropriate commonName or "
334 "subjectAltName fields were found")
335
336
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100337DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200338 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
339 "openssl_capath")
340
341def get_default_verify_paths():
342 """Return paths to default cafile and capath.
343 """
344 parts = _ssl.get_default_verify_paths()
345
346 # environment vars shadow paths
347 cafile = os.environ.get(parts[0], parts[1])
348 capath = os.environ.get(parts[2], parts[3])
349
350 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
351 capath if os.path.isdir(capath) else None,
352 *parts)
353
354
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100355class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
356 """ASN.1 object identifier lookup
357 """
358 __slots__ = ()
359
360 def __new__(cls, oid):
361 return super().__new__(cls, *_txt2obj(oid, name=False))
362
363 @classmethod
364 def fromnid(cls, nid):
365 """Create _ASN1Object from OpenSSL numeric ID
366 """
367 return super().__new__(cls, *_nid2obj(nid))
368
369 @classmethod
370 def fromname(cls, name):
371 """Create _ASN1Object from short name, long name or OID
372 """
373 return super().__new__(cls, *_txt2obj(name, name=True))
374
375
Christian Heimes72d28502013-11-23 13:56:58 +0100376class Purpose(_ASN1Object, _Enum):
377 """SSLContext purpose flags with X509v3 Extended Key Usage objects
378 """
379 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
380 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
381
382
Antoine Pitrou152efa22010-05-16 18:19:27 +0000383class SSLContext(_SSLContext):
384 """An SSLContext holds various SSL-related configuration options and
385 data, such as certificates and possibly a private key."""
386
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100387 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100388 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000389
Christian Heimes598894f2016-09-05 23:19:05 +0200390 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100391 self = _SSLContext.__new__(cls, protocol)
392 if protocol != _SSLv2_IF_EXISTS:
393 self.set_ciphers(_DEFAULT_CIPHERS)
394 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000395
Christian Heimes598894f2016-09-05 23:19:05 +0200396 def __init__(self, protocol=PROTOCOL_TLS):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000397 self.protocol = protocol
398
399 def wrap_socket(self, sock, server_side=False,
400 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000401 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200402 server_hostname=None, session=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000403 return SSLSocket(sock=sock, server_side=server_side,
404 do_handshake_on_connect=do_handshake_on_connect,
405 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000406 server_hostname=server_hostname,
Christian Heimes99a65702016-09-10 23:44:53 +0200407 _context=self, _session=session)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000408
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200409 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200410 server_hostname=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200411 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
412 server_hostname=server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200413 return SSLObject(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200414
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100415 def set_npn_protocols(self, npn_protocols):
416 protos = bytearray()
417 for protocol in npn_protocols:
418 b = bytes(protocol, 'ascii')
419 if len(b) == 0 or len(b) > 255:
420 raise SSLError('NPN protocols must be 1 to 255 in length')
421 protos.append(len(b))
422 protos.extend(b)
423
424 self._set_npn_protocols(protos)
425
Benjamin Petersoncca27322015-01-23 16:35:37 -0500426 def set_alpn_protocols(self, alpn_protocols):
427 protos = bytearray()
428 for protocol in alpn_protocols:
429 b = bytes(protocol, 'ascii')
430 if len(b) == 0 or len(b) > 255:
431 raise SSLError('ALPN protocols must be 1 to 255 in length')
432 protos.append(len(b))
433 protos.extend(b)
434
435 self._set_alpn_protocols(protos)
436
Christian Heimes72d28502013-11-23 13:56:58 +0100437 def _load_windows_store_certs(self, storename, purpose):
438 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700439 try:
440 for cert, encoding, trust in enum_certificates(storename):
441 # CA certs are never PKCS#7 encoded
442 if encoding == "x509_asn":
443 if trust is True or purpose.oid in trust:
444 certs.extend(cert)
445 except PermissionError:
446 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700447 if certs:
448 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100449 return certs
450
451 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
452 if not isinstance(purpose, _ASN1Object):
453 raise TypeError(purpose)
454 if sys.platform == "win32":
455 for storename in self._windows_cert_stores:
456 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400457 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100458
Christian Heimes3aeacad2016-09-10 00:19:35 +0200459 @property
460 def options(self):
461 return Options(super().options)
462
463 @options.setter
464 def options(self, value):
465 super(SSLContext, SSLContext).options.__set__(self, value)
466
467 @property
468 def verify_flags(self):
469 return VerifyFlags(super().verify_flags)
470
471 @verify_flags.setter
472 def verify_flags(self, value):
473 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
474
475 @property
476 def verify_mode(self):
477 value = super().verify_mode
478 try:
479 return VerifyMode(value)
480 except ValueError:
481 return value
482
483 @verify_mode.setter
484 def verify_mode(self, value):
485 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
486
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487
Christian Heimes4c05b472013-11-23 15:58:30 +0100488def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
489 capath=None, cadata=None):
490 """Create a SSLContext object with default settings.
491
492 NOTE: The protocol and settings may change anytime without prior
493 deprecation. The values represent a fair balance between maximum
494 compatibility and security.
495 """
496 if not isinstance(purpose, _ASN1Object):
497 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400498
Christian Heimes358cfd42016-09-10 22:43:48 +0200499 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
500 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
501 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200502 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400503
Christian Heimes4c05b472013-11-23 15:58:30 +0100504 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400505 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100506 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100507 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400508 elif purpose == Purpose.CLIENT_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400509 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
510
Christian Heimes4c05b472013-11-23 15:58:30 +0100511 if cafile or capath or cadata:
512 context.load_verify_locations(cafile, capath, cadata)
513 elif context.verify_mode != CERT_NONE:
514 # no explicit cafile, capath or cadata but the verify mode is
515 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
516 # root CA certificates for the given purpose. This may fail silently.
517 context.load_default_certs(purpose)
518 return context
519
Christian Heimes598894f2016-09-05 23:19:05 +0200520def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100521 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100522 certfile=None, keyfile=None,
523 cafile=None, capath=None, cadata=None):
524 """Create a SSLContext object for Python stdlib modules
525
526 All Python stdlib modules shall use this function to create SSLContext
527 objects in order to keep common settings in one place. The configuration
528 is less restrict than create_default_context()'s to increase backward
529 compatibility.
530 """
531 if not isinstance(purpose, _ASN1Object):
532 raise TypeError(purpose)
533
Christian Heimes358cfd42016-09-10 22:43:48 +0200534 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
535 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
536 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100537 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100538
539 if cert_reqs is not None:
540 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100541 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100542
543 if keyfile and not certfile:
544 raise ValueError("certfile must be specified")
545 if certfile or keyfile:
546 context.load_cert_chain(certfile, keyfile)
547
548 # load CA root certs
549 if cafile or capath or cadata:
550 context.load_verify_locations(cafile, capath, cadata)
551 elif context.verify_mode != CERT_NONE:
552 # no explicit cafile, capath or cadata but the verify mode is
553 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
554 # root CA certificates for the given purpose. This may fail silently.
555 context.load_default_certs(purpose)
556
557 return context
558
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500559# Used by http.client if no context is explicitly passed.
560_create_default_https_context = create_default_context
561
562
563# Backwards compatibility alias, even though it's not a public name.
564_create_stdlib_context = _create_unverified_context
565
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200566
567class SSLObject:
568 """This class implements an interface on top of a low-level SSL object as
569 implemented by OpenSSL. This object captures the state of an SSL connection
570 but does not provide any network IO itself. IO needs to be performed
571 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
572
573 This class does not have a public constructor. Instances are returned by
574 ``SSLContext.wrap_bio``. This class is typically used by framework authors
575 that want to implement asynchronous IO for SSL through memory buffers.
576
577 When compared to ``SSLSocket``, this object lacks the following features:
578
579 * Any form of network IO incluging methods such as ``recv`` and ``send``.
580 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
581 """
582
Christian Heimes99a65702016-09-10 23:44:53 +0200583 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200584 self._sslobj = sslobj
585 # Note: _sslobj takes a weak reference to owner
586 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200587 if session is not None:
588 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200589
590 @property
591 def context(self):
592 """The SSLContext that is currently in use."""
593 return self._sslobj.context
594
595 @context.setter
596 def context(self, ctx):
597 self._sslobj.context = ctx
598
599 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200600 def session(self):
601 """The SSLSession for client socket."""
602 return self._sslobj.session
603
604 @session.setter
605 def session(self, session):
606 self._sslobj.session = session
607
608 @property
609 def session_reused(self):
610 """Was the client session reused during handshake"""
611 return self._sslobj.session_reused
612
613 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200614 def server_side(self):
615 """Whether this is a server-side socket."""
616 return self._sslobj.server_side
617
618 @property
619 def server_hostname(self):
620 """The currently set server hostname (for SNI), or ``None`` if no
621 server hostame is set."""
622 return self._sslobj.server_hostname
623
Martin Panterf6b1d662016-03-28 00:22:09 +0000624 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200625 """Read up to 'len' bytes from the SSL object and return them.
626
627 If 'buffer' is provided, read into this buffer and return the number of
628 bytes read.
629 """
630 if buffer is not None:
631 v = self._sslobj.read(len, buffer)
632 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000633 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200634 return v
635
636 def write(self, data):
637 """Write 'data' to the SSL object and return the number of bytes
638 written.
639
640 The 'data' argument must support the buffer interface.
641 """
642 return self._sslobj.write(data)
643
644 def getpeercert(self, binary_form=False):
645 """Returns a formatted version of the data in the certificate provided
646 by the other end of the SSL channel.
647
648 Return None if no certificate was provided, {} if a certificate was
649 provided, but not validated.
650 """
651 return self._sslobj.peer_certificate(binary_form)
652
653 def selected_npn_protocol(self):
654 """Return the currently selected NPN protocol as a string, or ``None``
655 if a next protocol was not negotiated or if NPN is not supported by one
656 of the peers."""
657 if _ssl.HAS_NPN:
658 return self._sslobj.selected_npn_protocol()
659
Benjamin Petersoncca27322015-01-23 16:35:37 -0500660 def selected_alpn_protocol(self):
661 """Return the currently selected ALPN protocol as a string, or ``None``
662 if a next protocol was not negotiated or if ALPN is not supported by one
663 of the peers."""
664 if _ssl.HAS_ALPN:
665 return self._sslobj.selected_alpn_protocol()
666
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200667 def cipher(self):
668 """Return the currently selected cipher as a 3-tuple ``(name,
669 ssl_version, secret_bits)``."""
670 return self._sslobj.cipher()
671
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600672 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500673 """Return a list of ciphers shared by the client during the handshake or
674 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600675 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600676 return self._sslobj.shared_ciphers()
677
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200678 def compression(self):
679 """Return the current compression algorithm in use, or ``None`` if
680 compression was not negotiated or not supported by one of the peers."""
681 return self._sslobj.compression()
682
683 def pending(self):
684 """Return the number of bytes that can be read immediately."""
685 return self._sslobj.pending()
686
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200687 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200688 """Start the SSL/TLS handshake."""
689 self._sslobj.do_handshake()
690 if self.context.check_hostname:
691 if not self.server_hostname:
692 raise ValueError("check_hostname needs server_hostname "
693 "argument")
694 match_hostname(self.getpeercert(), self.server_hostname)
695
696 def unwrap(self):
697 """Start the SSL shutdown handshake."""
698 return self._sslobj.shutdown()
699
700 def get_channel_binding(self, cb_type="tls-unique"):
701 """Get channel binding data for current connection. Raise ValueError
702 if the requested `cb_type` is not supported. Return bytes of the data
703 or None if the data is not available (e.g. before the handshake)."""
704 if cb_type not in CHANNEL_BINDING_TYPES:
705 raise ValueError("Unsupported channel binding type")
706 if cb_type != "tls-unique":
707 raise NotImplementedError(
708 "{0} channel binding type not implemented"
709 .format(cb_type))
710 return self._sslobj.tls_unique_cb()
711
712 def version(self):
713 """Return a string identifying the protocol version used by the
714 current SSL channel. """
715 return self._sslobj.version()
716
717
Antoine Pitrou152efa22010-05-16 18:19:27 +0000718class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000719 """This class implements a subtype of socket.socket that wraps
720 the underlying OS socket in an SSL context when necessary, and
721 provides read and write methods over that channel."""
722
Bill Janssen6e027db2007-11-15 22:23:56 +0000723 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000724 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200725 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000726 do_handshake_on_connect=True,
727 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100728 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000729 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200730 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000731
Antoine Pitrou152efa22010-05-16 18:19:27 +0000732 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100733 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000734 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000735 if server_side and not certfile:
736 raise ValueError("certfile must be specified for server-side "
737 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000738 if keyfile and not certfile:
739 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000740 if certfile and not keyfile:
741 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100742 self._context = SSLContext(ssl_version)
743 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000744 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100745 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000746 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100747 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100748 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100749 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000750 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100751 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000752 self.keyfile = keyfile
753 self.certfile = certfile
754 self.cert_reqs = cert_reqs
755 self.ssl_version = ssl_version
756 self.ca_certs = ca_certs
757 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100758 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
759 # mixed in.
760 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
761 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200762 if server_side:
763 if server_hostname:
764 raise ValueError("server_hostname can only be specified "
765 "in client mode")
766 if _session is not None:
767 raise ValueError("session can only be specified in "
768 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100769 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600770 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200771 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000772 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000773 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000774 self.do_handshake_on_connect = do_handshake_on_connect
775 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000776 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000777 socket.__init__(self,
778 family=sock.family,
779 type=sock.type,
780 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000781 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000782 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000783 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000784 elif fileno is not None:
785 socket.__init__(self, fileno=fileno)
786 else:
787 socket.__init__(self, family=family, type=type, proto=proto)
788
Antoine Pitrou242db722013-05-01 20:52:07 +0200789 # See if we are connected
790 try:
791 self.getpeername()
792 except OSError as e:
793 if e.errno != errno.ENOTCONN:
794 raise
795 connected = False
796 else:
797 connected = True
798
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000799 self._closed = False
800 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000801 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000802 if connected:
803 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000804 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200805 sslobj = self._context._wrap_socket(self, server_side,
806 server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200807 self._sslobj = SSLObject(sslobj, owner=self,
808 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000809 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000810 timeout = self.gettimeout()
811 if timeout == 0.0:
812 # non-blocking
813 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000814 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000815
Christian Heimes1aa9a752013-12-02 02:41:19 +0100816 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000817 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100818 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200819
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100820 @property
821 def context(self):
822 return self._context
823
824 @context.setter
825 def context(self, ctx):
826 self._context = ctx
827 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000828
Christian Heimes99a65702016-09-10 23:44:53 +0200829 @property
830 def session(self):
831 """The SSLSession for client socket."""
832 if self._sslobj is not None:
833 return self._sslobj.session
834
835 @session.setter
836 def session(self, session):
837 self._session = session
838 if self._sslobj is not None:
839 self._sslobj.session = session
840
841 @property
842 def session_reused(self):
843 """Was the client session reused during handshake"""
844 if self._sslobj is not None:
845 return self._sslobj.session_reused
846
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000847 def dup(self):
848 raise NotImplemented("Can't dup() %s instances" %
849 self.__class__.__name__)
850
Bill Janssen6e027db2007-11-15 22:23:56 +0000851 def _checkClosed(self, msg=None):
852 # raise an exception here if you wish to check for spurious closes
853 pass
854
Antoine Pitrou242db722013-05-01 20:52:07 +0200855 def _check_connected(self):
856 if not self._connected:
857 # getpeername() will raise ENOTCONN if the socket is really
858 # not connected; note that we can be connected even without
859 # _connected being set, e.g. if connect() first returned
860 # EAGAIN.
861 self.getpeername()
862
Martin Panterf6b1d662016-03-28 00:22:09 +0000863 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000864 """Read up to LEN bytes and return them.
865 Return zero-length string on EOF."""
866
Bill Janssen6e027db2007-11-15 22:23:56 +0000867 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200868 if not self._sslobj:
869 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000870 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200871 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000872 except SSLError as x:
873 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000874 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000875 return 0
876 else:
877 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000878 else:
879 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000880
881 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000882 """Write DATA to the underlying SSL channel. Returns
883 number of bytes of DATA actually transmitted."""
884
Bill Janssen6e027db2007-11-15 22:23:56 +0000885 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200886 if not self._sslobj:
887 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000888 return self._sslobj.write(data)
889
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000891 """Returns a formatted version of the data in the
892 certificate provided by the other end of the SSL channel.
893 Return None if no certificate was provided, {} if a
894 certificate was provided, but not validated."""
895
Bill Janssen6e027db2007-11-15 22:23:56 +0000896 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200897 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200898 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100900 def selected_npn_protocol(self):
901 self._checkClosed()
902 if not self._sslobj or not _ssl.HAS_NPN:
903 return None
904 else:
905 return self._sslobj.selected_npn_protocol()
906
Benjamin Petersoncca27322015-01-23 16:35:37 -0500907 def selected_alpn_protocol(self):
908 self._checkClosed()
909 if not self._sslobj or not _ssl.HAS_ALPN:
910 return None
911 else:
912 return self._sslobj.selected_alpn_protocol()
913
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000914 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000915 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000916 if not self._sslobj:
917 return None
918 else:
919 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000920
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600921 def shared_ciphers(self):
922 self._checkClosed()
923 if not self._sslobj:
924 return None
925 return self._sslobj.shared_ciphers()
926
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100927 def compression(self):
928 self._checkClosed()
929 if not self._sslobj:
930 return None
931 else:
932 return self._sslobj.compression()
933
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000934 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000935 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000936 if self._sslobj:
937 if flags != 0:
938 raise ValueError(
939 "non-zero flags not allowed in calls to send() on %s" %
940 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200941 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000942 else:
943 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000944
Antoine Pitroua468adc2010-09-14 14:43:44 +0000945 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000946 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000947 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000948 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000949 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000950 elif addr is None:
951 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000952 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000953 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000954
Nick Coghlan513886a2011-08-28 00:00:27 +1000955 def sendmsg(self, *args, **kwargs):
956 # Ensure programs don't send data unencrypted if they try to
957 # use this method.
958 raise NotImplementedError("sendmsg not allowed on instances of %s" %
959 self.__class__)
960
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000961 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000962 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000963 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000964 if flags != 0:
965 raise ValueError(
966 "non-zero flags not allowed in calls to sendall() on %s" %
967 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000968 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700969 with memoryview(data) as view, view.cast("B") as byte_view:
970 amount = len(byte_view)
971 while count < amount:
972 v = self.send(byte_view[count:])
973 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000974 else:
975 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000976
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200977 def sendfile(self, file, offset=0, count=None):
978 """Send a file, possibly by using os.sendfile() if this is a
979 clear-text socket. Return the total number of bytes sent.
980 """
981 if self._sslobj is None:
982 # os.sendfile() works with plain sockets only
983 return super().sendfile(file, offset, count)
984 else:
985 return self._sendfile_use_send(file, offset, count)
986
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000987 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000988 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000989 if self._sslobj:
990 if flags != 0:
991 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000992 "non-zero flags not allowed in calls to recv() on %s" %
993 self.__class__)
994 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000995 else:
996 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000997
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000998 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000999 self._checkClosed()
1000 if buffer and (nbytes is None):
1001 nbytes = len(buffer)
1002 elif nbytes is None:
1003 nbytes = 1024
1004 if self._sslobj:
1005 if flags != 0:
1006 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001007 "non-zero flags not allowed in calls to recv_into() on %s" %
1008 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001009 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001010 else:
1011 return socket.recv_into(self, buffer, nbytes, flags)
1012
Antoine Pitroua468adc2010-09-14 14:43:44 +00001013 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001014 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001015 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001016 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001017 self.__class__)
1018 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +00001019 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001020
Bill Janssen58afe4c2008-09-08 16:45:19 +00001021 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1022 self._checkClosed()
1023 if self._sslobj:
1024 raise ValueError("recvfrom_into not allowed on instances of %s" %
1025 self.__class__)
1026 else:
1027 return socket.recvfrom_into(self, buffer, nbytes, flags)
1028
Nick Coghlan513886a2011-08-28 00:00:27 +10001029 def recvmsg(self, *args, **kwargs):
1030 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1031 self.__class__)
1032
1033 def recvmsg_into(self, *args, **kwargs):
1034 raise NotImplementedError("recvmsg_into not allowed on instances of "
1035 "%s" % self.__class__)
1036
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001037 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001038 self._checkClosed()
1039 if self._sslobj:
1040 return self._sslobj.pending()
1041 else:
1042 return 0
1043
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001044 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001045 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001046 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001047 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001048
Ezio Melottidc55e672010-01-18 09:15:14 +00001049 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001050 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001051 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001052 self._sslobj = None
1053 return s
1054 else:
1055 raise ValueError("No SSL wrapper around " + str(self))
1056
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001057 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +00001059 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001060
Bill Janssen48dc27c2007-12-05 03:38:10 +00001061 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001062 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001063 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001064 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001065 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001066 if timeout == 0.0 and block:
1067 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001068 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001069 finally:
1070 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001071
Antoine Pitroub4410db2011-05-18 18:51:06 +02001072 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001073 if self.server_side:
1074 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001075 # Here we assume that the socket is client-side, and not
1076 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001077 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001079 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001080 self._sslobj = SSLObject(sslobj, owner=self,
1081 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001082 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001083 if connect_ex:
1084 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001085 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001086 rc = None
1087 socket.connect(self, addr)
1088 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001089 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001090 if self.do_handshake_on_connect:
1091 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001092 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001093 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001094 self._sslobj = None
1095 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001096
1097 def connect(self, addr):
1098 """Connects to remote ADDR, and then wraps the connection in
1099 an SSL channel."""
1100 self._real_connect(addr, False)
1101
1102 def connect_ex(self, addr):
1103 """Connects to remote ADDR, and then wraps the connection in
1104 an SSL channel."""
1105 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001106
1107 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001108 """Accepts a new connection from a remote client, and returns
1109 a tuple containing that new connection wrapped with a server-side
1110 SSL channel, and the address of the remote client."""
1111
1112 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001113 newsock = self.context.wrap_socket(newsock,
1114 do_handshake_on_connect=self.do_handshake_on_connect,
1115 suppress_ragged_eofs=self.suppress_ragged_eofs,
1116 server_side=True)
1117 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroud6494802011-07-21 01:11:30 +02001119 def get_channel_binding(self, cb_type="tls-unique"):
1120 """Get channel binding data for current connection. Raise ValueError
1121 if the requested `cb_type` is not supported. Return bytes of the data
1122 or None if the data is not available (e.g. before the handshake).
1123 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001124 if self._sslobj is None:
1125 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001126 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001127
Antoine Pitrou47e40422014-09-04 21:00:10 +02001128 def version(self):
1129 """
1130 Return a string identifying the protocol version used by the
1131 current SSL channel, or None if there is no established channel.
1132 """
1133 if self._sslobj is None:
1134 return None
1135 return self._sslobj.version()
1136
Bill Janssen54cc54c2007-12-14 22:08:56 +00001137
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138def wrap_socket(sock, keyfile=None, certfile=None,
1139 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001140 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001141 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001142 suppress_ragged_eofs=True,
1143 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001144 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001146 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001147 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001148 suppress_ragged_eofs=suppress_ragged_eofs,
1149 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150
Thomas Woutersed03b412007-08-28 21:37:11 +00001151# some utility functions
1152
1153def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001154 """Return the time in seconds since the Epoch, given the timestring
1155 representing the "notBefore" or "notAfter" date from a certificate
1156 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001157
Antoine Pitrouc695c952014-04-28 20:57:36 +02001158 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1159
1160 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1161 UTC should be specified as GMT (see ASN1_TIME_print())
1162 """
1163 from time import strptime
1164 from calendar import timegm
1165
1166 months = (
1167 "Jan","Feb","Mar","Apr","May","Jun",
1168 "Jul","Aug","Sep","Oct","Nov","Dec"
1169 )
1170 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1171 try:
1172 month_number = months.index(cert_time[:3].title()) + 1
1173 except ValueError:
1174 raise ValueError('time data %r does not match '
1175 'format "%%b%s"' % (cert_time, time_format))
1176 else:
1177 # found valid month
1178 tt = strptime(cert_time[3:], time_format)
1179 # return an integer, the previous mktime()-based implementation
1180 # returned a float (fractional seconds are always zero here).
1181 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001182
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1184PEM_FOOTER = "-----END CERTIFICATE-----"
1185
1186def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187 """Takes a certificate in binary DER format and returns the
1188 PEM version of it as a string."""
1189
Bill Janssen6e027db2007-11-15 22:23:56 +00001190 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1191 return (PEM_HEADER + '\n' +
1192 textwrap.fill(f, 64) + '\n' +
1193 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194
1195def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196 """Takes a certificate in ASCII PEM format and returns the
1197 DER-encoded version of it as a byte sequence"""
1198
1199 if not pem_cert_string.startswith(PEM_HEADER):
1200 raise ValueError("Invalid PEM encoding; must start with %s"
1201 % PEM_HEADER)
1202 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1203 raise ValueError("Invalid PEM encoding; must end with %s"
1204 % PEM_FOOTER)
1205 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001206 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Christian Heimes598894f2016-09-05 23:19:05 +02001208def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 """Retrieve the certificate from the server at the specified address,
1210 and return it as a PEM-encoded string.
1211 If 'ca_certs' is specified, validate the server cert against it.
1212 If 'ssl_version' is specified, use it in the connection attempt."""
1213
1214 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001215 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216 cert_reqs = CERT_REQUIRED
1217 else:
1218 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001219 context = _create_stdlib_context(ssl_version,
1220 cert_reqs=cert_reqs,
1221 cafile=ca_certs)
1222 with create_connection(addr) as sock:
1223 with context.wrap_socket(sock) as sslsock:
1224 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225 return DER_cert_to_PEM_cert(dercert)
1226
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001227def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001228 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')