blob: fa83606e7cd5a57eddeeb226603759bf5baa8ceb [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Guido van Rossum5b8b1552007-11-16 00:06:11 +00004"""This module provides some more Pythonic support for SSL.
Thomas Woutersed03b412007-08-28 21:37:11 +00005
6Object types:
7
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Thomas Woutersed03b412007-08-28 21:37:11 +00009
10Exceptions:
11
Thomas Wouters1b7f8912007-09-19 03:06:30 +000012 SSLError -- exception raised for I/O errors
Thomas Woutersed03b412007-08-28 21:37:11 +000013
14Functions:
15
16 cert_time_to_seconds -- convert time string used for certificate
17 notBefore and notAfter functions to integer
18 seconds past the Epoch (the time values
19 returned from time.time())
20
21 fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
22 by the server running on HOST at port PORT. No
23 validation of the certificate is performed.
24
25Integer constants:
26
27SSL_ERROR_ZERO_RETURN
28SSL_ERROR_WANT_READ
29SSL_ERROR_WANT_WRITE
30SSL_ERROR_WANT_X509_LOOKUP
31SSL_ERROR_SYSCALL
32SSL_ERROR_SSL
33SSL_ERROR_WANT_CONNECT
34
35SSL_ERROR_EOF
36SSL_ERROR_INVALID_ERROR_CODE
37
38The following group define certificate requirements that one side is
39allowing/requiring from the other side:
40
41CERT_NONE - no certificates from the other side are required (or will
42 be looked at if provided)
43CERT_OPTIONAL - certificates are not required, but if provided will be
44 validated, and if validation fails, the connection will
45 also fail
46CERT_REQUIRED - certificates are required, and will be validated, and
47 if validation fails, the connection will also fail
48
49The following constants identify various SSL protocol variants:
50
51PROTOCOL_SSLv2
52PROTOCOL_SSLv3
53PROTOCOL_SSLv23
Christian Heimes598894f2016-09-05 23:19:05 +020054PROTOCOL_TLS
Christian Heimes5fe668c2016-09-12 00:01:11 +020055PROTOCOL_TLS_CLIENT
56PROTOCOL_TLS_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010058PROTOCOL_TLSv1_1
59PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010060
61The following constants identify various SSL alert message descriptions as per
62http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
63
64ALERT_DESCRIPTION_CLOSE_NOTIFY
65ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
66ALERT_DESCRIPTION_BAD_RECORD_MAC
67ALERT_DESCRIPTION_RECORD_OVERFLOW
68ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
69ALERT_DESCRIPTION_HANDSHAKE_FAILURE
70ALERT_DESCRIPTION_BAD_CERTIFICATE
71ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
72ALERT_DESCRIPTION_CERTIFICATE_REVOKED
73ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
74ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
75ALERT_DESCRIPTION_ILLEGAL_PARAMETER
76ALERT_DESCRIPTION_UNKNOWN_CA
77ALERT_DESCRIPTION_ACCESS_DENIED
78ALERT_DESCRIPTION_DECODE_ERROR
79ALERT_DESCRIPTION_DECRYPT_ERROR
80ALERT_DESCRIPTION_PROTOCOL_VERSION
81ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
82ALERT_DESCRIPTION_INTERNAL_ERROR
83ALERT_DESCRIPTION_USER_CANCELLED
84ALERT_DESCRIPTION_NO_RENEGOTIATION
85ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
86ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
87ALERT_DESCRIPTION_UNRECOGNIZED_NAME
88ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
89ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
90ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000091"""
92
Antoine Pitrouc481bfb2015-02-15 18:12:20 +010093import ipaddress
Antoine Pitrou59fdd672010-10-08 10:37:08 +000094import re
Christian Heimes46bebee2013-06-09 19:03:31 +020095import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020096import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010097from collections import namedtuple
Christian Heimes3aeacad2016-09-10 00:19:35 +020098from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
Thomas Woutersed03b412007-08-28 21:37:11 +000099
100import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000101
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000102from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Christian Heimes99a65702016-09-10 23:44:53 +0200103from _ssl import _SSLContext, MemoryBIO, SSLSession
Antoine Pitrou41032a62011-10-27 23:56:55 +0200104from _ssl import (
105 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700106 SSLSyscallError, SSLEOFError, SSLCertVerificationError
Antoine Pitrou41032a62011-10-27 23:56:55 +0200107 )
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100109from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
110try:
111 from _ssl import RAND_egd
112except ImportError:
113 # LibreSSL does not provide RAND_egd
114 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100115
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100116
Christian Heimescb5b68a2017-09-07 18:07:00 -0700117from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200118from _ssl import _OPENSSL_API_VERSION
119
Christian Heimes3aeacad2016-09-10 00:19:35 +0200120
Ethan Furman24e837f2015-03-18 17:27:57 -0700121_IntEnum._convert(
Christian Heimes3aeacad2016-09-10 00:19:35 +0200122 '_SSLMethod', __name__,
123 lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
124 source=_ssl)
125
126_IntFlag._convert(
127 'Options', __name__,
128 lambda name: name.startswith('OP_'),
129 source=_ssl)
130
131_IntEnum._convert(
132 'AlertDescription', __name__,
133 lambda name: name.startswith('ALERT_DESCRIPTION_'),
134 source=_ssl)
135
136_IntEnum._convert(
137 'SSLErrorNumber', __name__,
138 lambda name: name.startswith('SSL_ERROR_'),
139 source=_ssl)
140
141_IntFlag._convert(
142 'VerifyFlags', __name__,
143 lambda name: name.startswith('VERIFY_'),
144 source=_ssl)
145
146_IntEnum._convert(
147 'VerifyMode', __name__,
148 lambda name: name.startswith('CERT_'),
149 source=_ssl)
150
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100151
Christian Heimes598894f2016-09-05 23:19:05 +0200152PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
Antoine Pitrou172f0252014-04-18 20:33:08 +0200153_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
154
Christian Heimes3aeacad2016-09-10 00:19:35 +0200155_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
156
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100157
Christian Heimes46bebee2013-06-09 19:03:31 +0200158if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100159 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200160
Antoine Pitrou15399c32011-04-28 19:23:55 +0200161from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100162from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000164import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700165import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000166
Andrew Svetlov0832af62012-12-18 23:10:48 +0200167
168socket_error = OSError # keep that public name in module namespace
169
Antoine Pitroud6494802011-07-21 01:11:30 +0200170if _ssl.HAS_TLS_UNIQUE:
171 CHANNEL_BINDING_TYPES = ['tls-unique']
172else:
173 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000174
Christian Heimes03d13c02016-09-06 20:06:47 +0200175
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100176# Disable weak or insecure ciphers by default
177# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400178# Enable a better set of ciphers by default
179# This list has been explicitly chosen to:
Christian Heimescb5b68a2017-09-07 18:07:00 -0700180# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
Donald Stufft79ccaa22014-03-21 21:33:34 -0400181# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
182# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200183# * Prefer AEAD over CBC for better performance and security
184# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
185# (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
186# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
187# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400188# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200189# * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
190# for security reasons
Donald Stufft79ccaa22014-03-21 21:33:34 -0400191_DEFAULT_CIPHERS = (
Christian Heimescb5b68a2017-09-07 18:07:00 -0700192 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
193 'TLS13-AES-128-GCM-SHA256:'
Christian Heimes03d13c02016-09-06 20:06:47 +0200194 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
195 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
196 '!aNULL:!eNULL:!MD5:!3DES'
197 )
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100198
Donald Stufft6a2ba942014-03-23 19:05:28 -0400199# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400200# This list has been explicitly chosen to:
Christian Heimescb5b68a2017-09-07 18:07:00 -0700201# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
Donald Stufft79ccaa22014-03-21 21:33:34 -0400202# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
203# * Prefer ECDHE over DHE for better performance
Christian Heimes03d13c02016-09-06 20:06:47 +0200204# * Prefer AEAD over CBC for better performance and security
205# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
206# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
207# performance and security
Donald Stufft79ccaa22014-03-21 21:33:34 -0400208# * Then Use HIGH cipher suites as a fallback
Christian Heimes03d13c02016-09-06 20:06:47 +0200209# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
210# 3DES for security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400211_RESTRICTED_SERVER_CIPHERS = (
Christian Heimescb5b68a2017-09-07 18:07:00 -0700212 'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
213 'TLS13-AES-128-GCM-SHA256:'
Christian Heimes03d13c02016-09-06 20:06:47 +0200214 'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
215 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
216 '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400217)
Christian Heimes4c05b472013-11-23 15:58:30 +0100218
Thomas Woutersed03b412007-08-28 21:37:11 +0000219
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000220class CertificateError(ValueError):
221 pass
222
223
Mandeep Singhede2ac92017-11-27 04:01:27 +0530224def _dnsname_match(dn, hostname):
Georg Brandl72c98d32013-10-27 07:16:53 +0100225 """Matching according to RFC 6125, section 6.4.3
226
227 http://tools.ietf.org/html/rfc6125#section-6.4.3
228 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000229 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100230 if not dn:
231 return False
232
233 leftmost, *remainder = dn.split(r'.')
234
235 wildcards = leftmost.count('*')
Mandeep Singhede2ac92017-11-27 04:01:27 +0530236 if wildcards == 1 and len(leftmost) > 1:
237 # Only match wildcard in leftmost segment.
238 raise CertificateError(
239 "wildcard can only be present in the leftmost segment: " + repr(dn))
240
241 if wildcards > 1:
Georg Brandl72c98d32013-10-27 07:16:53 +0100242 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300243 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100244 # policy among SSL implementations showed it to be a
245 # reasonable choice.
246 raise CertificateError(
247 "too many wildcards in certificate DNS name: " + repr(dn))
248
249 # speed up common case w/o wildcards
250 if not wildcards:
251 return dn.lower() == hostname.lower()
252
253 # RFC 6125, section 6.4.3, subitem 1.
254 # The client SHOULD NOT attempt to match a presented identifier in which
255 # the wildcard character comprises a label other than the left-most label.
256 if leftmost == '*':
257 # When '*' is a fragment by itself, it matches a non-empty dotless
258 # fragment.
259 pats.append('[^.]+')
260 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
261 # RFC 6125, section 6.4.3, subitem 3.
262 # The client SHOULD NOT attempt to match a presented identifier
263 # where the wildcard character is embedded within an A-label or
264 # U-label of an internationalized domain name.
265 pats.append(re.escape(leftmost))
266 else:
267 # Otherwise, '*' matches any dotless string, e.g. www*
268 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
269
270 # add the remaining fragments, ignore any wildcards
271 for frag in remainder:
272 pats.append(re.escape(frag))
273
274 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
275 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000276
277
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100278def _ipaddress_match(ipname, host_ip):
279 """Exact matching of IP addresses.
280
281 RFC 6125 explicitly doesn't define an algorithm for this
282 (section 1.7.2 - "Out of Scope").
283 """
284 # OpenSSL may add a trailing newline to a subjectAltName's IP address
285 ip = ipaddress.ip_address(ipname.rstrip())
286 return ip == host_ip
287
288
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000289def match_hostname(cert, hostname):
290 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100291 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
292 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000293
294 CertificateError is raised on failure. On success, the function
295 returns nothing.
296 """
297 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100298 raise ValueError("empty or no certificate, match_hostname needs a "
299 "SSL socket or SSL context with either "
300 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100301 try:
302 host_ip = ipaddress.ip_address(hostname)
303 except ValueError:
304 # Not an IP address (common case)
305 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000306 dnsnames = []
307 san = cert.get('subjectAltName', ())
308 for key, value in san:
309 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100310 if host_ip is None and _dnsname_match(value, hostname):
311 return
312 dnsnames.append(value)
313 elif key == 'IP Address':
314 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000315 return
316 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200317 if not dnsnames:
318 # The subject is only checked when there is no dNSName entry
319 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000320 for sub in cert.get('subject', ()):
321 for key, value in sub:
322 # XXX according to RFC 2818, the most specific Common Name
323 # must be used.
324 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100325 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000326 return
327 dnsnames.append(value)
328 if len(dnsnames) > 1:
329 raise CertificateError("hostname %r "
330 "doesn't match either of %s"
331 % (hostname, ', '.join(map(repr, dnsnames))))
332 elif len(dnsnames) == 1:
333 raise CertificateError("hostname %r "
334 "doesn't match %r"
335 % (hostname, dnsnames[0]))
336 else:
337 raise CertificateError("no appropriate commonName or "
338 "subjectAltName fields were found")
339
340
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100341DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200342 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
343 "openssl_capath")
344
345def get_default_verify_paths():
346 """Return paths to default cafile and capath.
347 """
348 parts = _ssl.get_default_verify_paths()
349
350 # environment vars shadow paths
351 cafile = os.environ.get(parts[0], parts[1])
352 capath = os.environ.get(parts[2], parts[3])
353
354 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
355 capath if os.path.isdir(capath) else None,
356 *parts)
357
358
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100359class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
360 """ASN.1 object identifier lookup
361 """
362 __slots__ = ()
363
364 def __new__(cls, oid):
365 return super().__new__(cls, *_txt2obj(oid, name=False))
366
367 @classmethod
368 def fromnid(cls, nid):
369 """Create _ASN1Object from OpenSSL numeric ID
370 """
371 return super().__new__(cls, *_nid2obj(nid))
372
373 @classmethod
374 def fromname(cls, name):
375 """Create _ASN1Object from short name, long name or OID
376 """
377 return super().__new__(cls, *_txt2obj(name, name=True))
378
379
Christian Heimes72d28502013-11-23 13:56:58 +0100380class Purpose(_ASN1Object, _Enum):
381 """SSLContext purpose flags with X509v3 Extended Key Usage objects
382 """
383 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
384 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
385
386
Antoine Pitrou152efa22010-05-16 18:19:27 +0000387class SSLContext(_SSLContext):
388 """An SSLContext holds various SSL-related configuration options and
389 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100390 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000391
Christian Heimes4df60f12017-09-15 20:26:05 +0200392 sslsocket_class = None # SSLSocket is assigned later.
393 sslobject_class = None # SSLObject is assigned later.
394
Christian Heimes598894f2016-09-05 23:19:05 +0200395 def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100396 self = _SSLContext.__new__(cls, protocol)
397 if protocol != _SSLv2_IF_EXISTS:
398 self.set_ciphers(_DEFAULT_CIPHERS)
399 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000400
Christian Heimes598894f2016-09-05 23:19:05 +0200401 def __init__(self, protocol=PROTOCOL_TLS):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000402 self.protocol = protocol
403
404 def wrap_socket(self, sock, server_side=False,
405 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000406 suppress_ragged_eofs=True,
Christian Heimes99a65702016-09-10 23:44:53 +0200407 server_hostname=None, session=None):
Christian Heimes4df60f12017-09-15 20:26:05 +0200408 return self.sslsocket_class(
409 sock=sock,
410 server_side=server_side,
411 do_handshake_on_connect=do_handshake_on_connect,
412 suppress_ragged_eofs=suppress_ragged_eofs,
413 server_hostname=server_hostname,
414 _context=self,
415 _session=session
416 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000417
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200418 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200419 server_hostname=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200420 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
421 server_hostname=server_hostname)
Christian Heimes4df60f12017-09-15 20:26:05 +0200422 return self.sslobject_class(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200423
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100424 def set_npn_protocols(self, npn_protocols):
425 protos = bytearray()
426 for protocol in npn_protocols:
427 b = bytes(protocol, 'ascii')
428 if len(b) == 0 or len(b) > 255:
429 raise SSLError('NPN protocols must be 1 to 255 in length')
430 protos.append(len(b))
431 protos.extend(b)
432
433 self._set_npn_protocols(protos)
434
Benjamin Petersoncca27322015-01-23 16:35:37 -0500435 def set_alpn_protocols(self, alpn_protocols):
436 protos = bytearray()
437 for protocol in alpn_protocols:
438 b = bytes(protocol, 'ascii')
439 if len(b) == 0 or len(b) > 255:
440 raise SSLError('ALPN protocols must be 1 to 255 in length')
441 protos.append(len(b))
442 protos.extend(b)
443
444 self._set_alpn_protocols(protos)
445
Christian Heimes72d28502013-11-23 13:56:58 +0100446 def _load_windows_store_certs(self, storename, purpose):
447 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700448 try:
449 for cert, encoding, trust in enum_certificates(storename):
450 # CA certs are never PKCS#7 encoded
451 if encoding == "x509_asn":
452 if trust is True or purpose.oid in trust:
453 certs.extend(cert)
454 except PermissionError:
455 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700456 if certs:
457 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100458 return certs
459
460 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
461 if not isinstance(purpose, _ASN1Object):
462 raise TypeError(purpose)
463 if sys.platform == "win32":
464 for storename in self._windows_cert_stores:
465 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400466 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100467
Christian Heimes3aeacad2016-09-10 00:19:35 +0200468 @property
469 def options(self):
470 return Options(super().options)
471
472 @options.setter
473 def options(self, value):
474 super(SSLContext, SSLContext).options.__set__(self, value)
475
476 @property
477 def verify_flags(self):
478 return VerifyFlags(super().verify_flags)
479
480 @verify_flags.setter
481 def verify_flags(self, value):
482 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
483
484 @property
485 def verify_mode(self):
486 value = super().verify_mode
487 try:
488 return VerifyMode(value)
489 except ValueError:
490 return value
491
492 @verify_mode.setter
493 def verify_mode(self, value):
494 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
495
Antoine Pitrou152efa22010-05-16 18:19:27 +0000496
Christian Heimes4c05b472013-11-23 15:58:30 +0100497def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
498 capath=None, cadata=None):
499 """Create a SSLContext object with default settings.
500
501 NOTE: The protocol and settings may change anytime without prior
502 deprecation. The values represent a fair balance between maximum
503 compatibility and security.
504 """
505 if not isinstance(purpose, _ASN1Object):
506 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400507
Christian Heimes358cfd42016-09-10 22:43:48 +0200508 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
509 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
510 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200511 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400512
Christian Heimes4c05b472013-11-23 15:58:30 +0100513 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400514 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100515 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100516 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400517 elif purpose == Purpose.CLIENT_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400518 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
519
Christian Heimes4c05b472013-11-23 15:58:30 +0100520 if cafile or capath or cadata:
521 context.load_verify_locations(cafile, capath, cadata)
522 elif context.verify_mode != CERT_NONE:
523 # no explicit cafile, capath or cadata but the verify mode is
524 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
525 # root CA certificates for the given purpose. This may fail silently.
526 context.load_default_certs(purpose)
527 return context
528
Christian Heimesa170fa12017-09-15 20:27:30 +0200529def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100530 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100531 certfile=None, keyfile=None,
532 cafile=None, capath=None, cadata=None):
533 """Create a SSLContext object for Python stdlib modules
534
535 All Python stdlib modules shall use this function to create SSLContext
536 objects in order to keep common settings in one place. The configuration
537 is less restrict than create_default_context()'s to increase backward
538 compatibility.
539 """
540 if not isinstance(purpose, _ASN1Object):
541 raise TypeError(purpose)
542
Christian Heimes358cfd42016-09-10 22:43:48 +0200543 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
544 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
545 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100546 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100547
Christian Heimesa170fa12017-09-15 20:27:30 +0200548 if not check_hostname:
549 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100550 if cert_reqs is not None:
551 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200552 if check_hostname:
553 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100554
555 if keyfile and not certfile:
556 raise ValueError("certfile must be specified")
557 if certfile or keyfile:
558 context.load_cert_chain(certfile, keyfile)
559
560 # load CA root certs
561 if cafile or capath or cadata:
562 context.load_verify_locations(cafile, capath, cadata)
563 elif context.verify_mode != CERT_NONE:
564 # no explicit cafile, capath or cadata but the verify mode is
565 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
566 # root CA certificates for the given purpose. This may fail silently.
567 context.load_default_certs(purpose)
568
569 return context
570
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500571# Used by http.client if no context is explicitly passed.
572_create_default_https_context = create_default_context
573
574
575# Backwards compatibility alias, even though it's not a public name.
576_create_stdlib_context = _create_unverified_context
577
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200578
579class SSLObject:
580 """This class implements an interface on top of a low-level SSL object as
581 implemented by OpenSSL. This object captures the state of an SSL connection
582 but does not provide any network IO itself. IO needs to be performed
583 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
584
585 This class does not have a public constructor. Instances are returned by
586 ``SSLContext.wrap_bio``. This class is typically used by framework authors
587 that want to implement asynchronous IO for SSL through memory buffers.
588
589 When compared to ``SSLSocket``, this object lacks the following features:
590
591 * Any form of network IO incluging methods such as ``recv`` and ``send``.
592 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
593 """
594
Christian Heimes99a65702016-09-10 23:44:53 +0200595 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 self._sslobj = sslobj
597 # Note: _sslobj takes a weak reference to owner
598 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200599 if session is not None:
600 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200601
602 @property
603 def context(self):
604 """The SSLContext that is currently in use."""
605 return self._sslobj.context
606
607 @context.setter
608 def context(self, ctx):
609 self._sslobj.context = ctx
610
611 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200612 def session(self):
613 """The SSLSession for client socket."""
614 return self._sslobj.session
615
616 @session.setter
617 def session(self, session):
618 self._sslobj.session = session
619
620 @property
621 def session_reused(self):
622 """Was the client session reused during handshake"""
623 return self._sslobj.session_reused
624
625 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200626 def server_side(self):
627 """Whether this is a server-side socket."""
628 return self._sslobj.server_side
629
630 @property
631 def server_hostname(self):
632 """The currently set server hostname (for SNI), or ``None`` if no
633 server hostame is set."""
634 return self._sslobj.server_hostname
635
Martin Panterf6b1d662016-03-28 00:22:09 +0000636 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200637 """Read up to 'len' bytes from the SSL object and return them.
638
639 If 'buffer' is provided, read into this buffer and return the number of
640 bytes read.
641 """
642 if buffer is not None:
643 v = self._sslobj.read(len, buffer)
644 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000645 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200646 return v
647
648 def write(self, data):
649 """Write 'data' to the SSL object and return the number of bytes
650 written.
651
652 The 'data' argument must support the buffer interface.
653 """
654 return self._sslobj.write(data)
655
656 def getpeercert(self, binary_form=False):
657 """Returns a formatted version of the data in the certificate provided
658 by the other end of the SSL channel.
659
660 Return None if no certificate was provided, {} if a certificate was
661 provided, but not validated.
662 """
663 return self._sslobj.peer_certificate(binary_form)
664
665 def selected_npn_protocol(self):
666 """Return the currently selected NPN protocol as a string, or ``None``
667 if a next protocol was not negotiated or if NPN is not supported by one
668 of the peers."""
669 if _ssl.HAS_NPN:
670 return self._sslobj.selected_npn_protocol()
671
Benjamin Petersoncca27322015-01-23 16:35:37 -0500672 def selected_alpn_protocol(self):
673 """Return the currently selected ALPN protocol as a string, or ``None``
674 if a next protocol was not negotiated or if ALPN is not supported by one
675 of the peers."""
676 if _ssl.HAS_ALPN:
677 return self._sslobj.selected_alpn_protocol()
678
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200679 def cipher(self):
680 """Return the currently selected cipher as a 3-tuple ``(name,
681 ssl_version, secret_bits)``."""
682 return self._sslobj.cipher()
683
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600684 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500685 """Return a list of ciphers shared by the client during the handshake or
686 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600687 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600688 return self._sslobj.shared_ciphers()
689
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200690 def compression(self):
691 """Return the current compression algorithm in use, or ``None`` if
692 compression was not negotiated or not supported by one of the peers."""
693 return self._sslobj.compression()
694
695 def pending(self):
696 """Return the number of bytes that can be read immediately."""
697 return self._sslobj.pending()
698
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200699 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200700 """Start the SSL/TLS handshake."""
701 self._sslobj.do_handshake()
702 if self.context.check_hostname:
703 if not self.server_hostname:
704 raise ValueError("check_hostname needs server_hostname "
705 "argument")
706 match_hostname(self.getpeercert(), self.server_hostname)
707
708 def unwrap(self):
709 """Start the SSL shutdown handshake."""
710 return self._sslobj.shutdown()
711
712 def get_channel_binding(self, cb_type="tls-unique"):
713 """Get channel binding data for current connection. Raise ValueError
714 if the requested `cb_type` is not supported. Return bytes of the data
715 or None if the data is not available (e.g. before the handshake)."""
716 if cb_type not in CHANNEL_BINDING_TYPES:
717 raise ValueError("Unsupported channel binding type")
718 if cb_type != "tls-unique":
719 raise NotImplementedError(
720 "{0} channel binding type not implemented"
721 .format(cb_type))
722 return self._sslobj.tls_unique_cb()
723
724 def version(self):
725 """Return a string identifying the protocol version used by the
726 current SSL channel. """
727 return self._sslobj.version()
728
729
Antoine Pitrou152efa22010-05-16 18:19:27 +0000730class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000731 """This class implements a subtype of socket.socket that wraps
732 the underlying OS socket in an SSL context when necessary, and
733 provides read and write methods over that channel."""
734
Bill Janssen6e027db2007-11-15 22:23:56 +0000735 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000736 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200737 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000738 do_handshake_on_connect=True,
739 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100740 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000741 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200742 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000743
Antoine Pitrou152efa22010-05-16 18:19:27 +0000744 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100745 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000746 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000747 if server_side and not certfile:
748 raise ValueError("certfile must be specified for server-side "
749 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000750 if keyfile and not certfile:
751 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000752 if certfile and not keyfile:
753 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100754 self._context = SSLContext(ssl_version)
755 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000756 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100757 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000758 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100759 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100760 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100761 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000762 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100763 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000764 self.keyfile = keyfile
765 self.certfile = certfile
766 self.cert_reqs = cert_reqs
767 self.ssl_version = ssl_version
768 self.ca_certs = ca_certs
769 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100770 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
771 # mixed in.
772 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
773 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200774 if server_side:
775 if server_hostname:
776 raise ValueError("server_hostname can only be specified "
777 "in client mode")
778 if _session is not None:
779 raise ValueError("session can only be specified in "
780 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100781 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600782 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200783 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000784 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000785 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000786 self.do_handshake_on_connect = do_handshake_on_connect
787 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000788 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000789 socket.__init__(self,
790 family=sock.family,
791 type=sock.type,
792 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000793 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000794 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000795 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000796 elif fileno is not None:
797 socket.__init__(self, fileno=fileno)
798 else:
799 socket.__init__(self, family=family, type=type, proto=proto)
800
Antoine Pitrou242db722013-05-01 20:52:07 +0200801 # See if we are connected
802 try:
803 self.getpeername()
804 except OSError as e:
805 if e.errno != errno.ENOTCONN:
806 raise
807 connected = False
808 else:
809 connected = True
810
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000811 self._closed = False
812 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000813 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000814 if connected:
815 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000816 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200817 sslobj = self._context._wrap_socket(self, server_side,
818 server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200819 self._sslobj = SSLObject(sslobj, owner=self,
820 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000821 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000822 timeout = self.gettimeout()
823 if timeout == 0.0:
824 # non-blocking
825 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000826 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000827
Christian Heimes1aa9a752013-12-02 02:41:19 +0100828 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000829 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100830 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200831
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100832 @property
833 def context(self):
834 return self._context
835
836 @context.setter
837 def context(self, ctx):
838 self._context = ctx
839 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000840
Christian Heimes99a65702016-09-10 23:44:53 +0200841 @property
842 def session(self):
843 """The SSLSession for client socket."""
844 if self._sslobj is not None:
845 return self._sslobj.session
846
847 @session.setter
848 def session(self, session):
849 self._session = session
850 if self._sslobj is not None:
851 self._sslobj.session = session
852
853 @property
854 def session_reused(self):
855 """Was the client session reused during handshake"""
856 if self._sslobj is not None:
857 return self._sslobj.session_reused
858
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000859 def dup(self):
860 raise NotImplemented("Can't dup() %s instances" %
861 self.__class__.__name__)
862
Bill Janssen6e027db2007-11-15 22:23:56 +0000863 def _checkClosed(self, msg=None):
864 # raise an exception here if you wish to check for spurious closes
865 pass
866
Antoine Pitrou242db722013-05-01 20:52:07 +0200867 def _check_connected(self):
868 if not self._connected:
869 # getpeername() will raise ENOTCONN if the socket is really
870 # not connected; note that we can be connected even without
871 # _connected being set, e.g. if connect() first returned
872 # EAGAIN.
873 self.getpeername()
874
Martin Panterf6b1d662016-03-28 00:22:09 +0000875 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000876 """Read up to LEN bytes and return them.
877 Return zero-length string on EOF."""
878
Bill Janssen6e027db2007-11-15 22:23:56 +0000879 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200880 if not self._sslobj:
881 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000882 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200883 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000884 except SSLError as x:
885 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000886 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000887 return 0
888 else:
889 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000890 else:
891 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000892
893 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000894 """Write DATA to the underlying SSL channel. Returns
895 number of bytes of DATA actually transmitted."""
896
Bill Janssen6e027db2007-11-15 22:23:56 +0000897 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200898 if not self._sslobj:
899 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000900 return self._sslobj.write(data)
901
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000903 """Returns a formatted version of the data in the
904 certificate provided by the other end of the SSL channel.
905 Return None if no certificate was provided, {} if a
906 certificate was provided, but not validated."""
907
Bill Janssen6e027db2007-11-15 22:23:56 +0000908 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200909 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200910 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100912 def selected_npn_protocol(self):
913 self._checkClosed()
914 if not self._sslobj or not _ssl.HAS_NPN:
915 return None
916 else:
917 return self._sslobj.selected_npn_protocol()
918
Benjamin Petersoncca27322015-01-23 16:35:37 -0500919 def selected_alpn_protocol(self):
920 self._checkClosed()
921 if not self._sslobj or not _ssl.HAS_ALPN:
922 return None
923 else:
924 return self._sslobj.selected_alpn_protocol()
925
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000926 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000927 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928 if not self._sslobj:
929 return None
930 else:
931 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000932
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600933 def shared_ciphers(self):
934 self._checkClosed()
935 if not self._sslobj:
936 return None
937 return self._sslobj.shared_ciphers()
938
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100939 def compression(self):
940 self._checkClosed()
941 if not self._sslobj:
942 return None
943 else:
944 return self._sslobj.compression()
945
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000946 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000947 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000948 if self._sslobj:
949 if flags != 0:
950 raise ValueError(
951 "non-zero flags not allowed in calls to send() on %s" %
952 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200953 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000954 else:
955 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000956
Antoine Pitroua468adc2010-09-14 14:43:44 +0000957 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000958 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000959 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000960 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000961 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000962 elif addr is None:
963 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000964 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000965 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000966
Nick Coghlan513886a2011-08-28 00:00:27 +1000967 def sendmsg(self, *args, **kwargs):
968 # Ensure programs don't send data unencrypted if they try to
969 # use this method.
970 raise NotImplementedError("sendmsg not allowed on instances of %s" %
971 self.__class__)
972
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000973 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000974 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000975 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000976 if flags != 0:
977 raise ValueError(
978 "non-zero flags not allowed in calls to sendall() on %s" %
979 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000980 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700981 with memoryview(data) as view, view.cast("B") as byte_view:
982 amount = len(byte_view)
983 while count < amount:
984 v = self.send(byte_view[count:])
985 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000986 else:
987 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000988
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200989 def sendfile(self, file, offset=0, count=None):
990 """Send a file, possibly by using os.sendfile() if this is a
991 clear-text socket. Return the total number of bytes sent.
992 """
993 if self._sslobj is None:
994 # os.sendfile() works with plain sockets only
995 return super().sendfile(file, offset, count)
996 else:
997 return self._sendfile_use_send(file, offset, count)
998
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000999 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001000 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001001 if self._sslobj:
1002 if flags != 0:
1003 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +00001004 "non-zero flags not allowed in calls to recv() on %s" %
1005 self.__class__)
1006 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001007 else:
1008 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001009
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001010 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001011 self._checkClosed()
1012 if buffer and (nbytes is None):
1013 nbytes = len(buffer)
1014 elif nbytes is None:
1015 nbytes = 1024
1016 if self._sslobj:
1017 if flags != 0:
1018 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001019 "non-zero flags not allowed in calls to recv_into() on %s" %
1020 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001021 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001022 else:
1023 return socket.recv_into(self, buffer, nbytes, flags)
1024
Antoine Pitroua468adc2010-09-14 14:43:44 +00001025 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001026 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001027 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001028 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001029 self.__class__)
1030 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +00001031 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001032
Bill Janssen58afe4c2008-09-08 16:45:19 +00001033 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1034 self._checkClosed()
1035 if self._sslobj:
1036 raise ValueError("recvfrom_into not allowed on instances of %s" %
1037 self.__class__)
1038 else:
1039 return socket.recvfrom_into(self, buffer, nbytes, flags)
1040
Nick Coghlan513886a2011-08-28 00:00:27 +10001041 def recvmsg(self, *args, **kwargs):
1042 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1043 self.__class__)
1044
1045 def recvmsg_into(self, *args, **kwargs):
1046 raise NotImplementedError("recvmsg_into not allowed on instances of "
1047 "%s" % self.__class__)
1048
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001049 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001050 self._checkClosed()
1051 if self._sslobj:
1052 return self._sslobj.pending()
1053 else:
1054 return 0
1055
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001056 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001057 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001059 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001060
Ezio Melottidc55e672010-01-18 09:15:14 +00001061 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001062 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001063 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001064 self._sslobj = None
1065 return s
1066 else:
1067 raise ValueError("No SSL wrapper around " + str(self))
1068
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001069 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +00001071 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001072
Bill Janssen48dc27c2007-12-05 03:38:10 +00001073 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001074 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001075 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001076 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001077 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001078 if timeout == 0.0 and block:
1079 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001080 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001081 finally:
1082 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001083
Antoine Pitroub4410db2011-05-18 18:51:06 +02001084 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001085 if self.server_side:
1086 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001087 # Here we assume that the socket is client-side, and not
1088 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001089 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001091 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001092 self._sslobj = SSLObject(sslobj, owner=self,
1093 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001094 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001095 if connect_ex:
1096 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001097 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001098 rc = None
1099 socket.connect(self, addr)
1100 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001101 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001102 if self.do_handshake_on_connect:
1103 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001104 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001105 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001106 self._sslobj = None
1107 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001108
1109 def connect(self, addr):
1110 """Connects to remote ADDR, and then wraps the connection in
1111 an SSL channel."""
1112 self._real_connect(addr, False)
1113
1114 def connect_ex(self, addr):
1115 """Connects to remote ADDR, and then wraps the connection in
1116 an SSL channel."""
1117 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001118
1119 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001120 """Accepts a new connection from a remote client, and returns
1121 a tuple containing that new connection wrapped with a server-side
1122 SSL channel, and the address of the remote client."""
1123
1124 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001125 newsock = self.context.wrap_socket(newsock,
1126 do_handshake_on_connect=self.do_handshake_on_connect,
1127 suppress_ragged_eofs=self.suppress_ragged_eofs,
1128 server_side=True)
1129 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroud6494802011-07-21 01:11:30 +02001131 def get_channel_binding(self, cb_type="tls-unique"):
1132 """Get channel binding data for current connection. Raise ValueError
1133 if the requested `cb_type` is not supported. Return bytes of the data
1134 or None if the data is not available (e.g. before the handshake).
1135 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001136 if self._sslobj is None:
1137 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001138 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001139
Antoine Pitrou47e40422014-09-04 21:00:10 +02001140 def version(self):
1141 """
1142 Return a string identifying the protocol version used by the
1143 current SSL channel, or None if there is no established channel.
1144 """
1145 if self._sslobj is None:
1146 return None
1147 return self._sslobj.version()
1148
Bill Janssen54cc54c2007-12-14 22:08:56 +00001149
Christian Heimes4df60f12017-09-15 20:26:05 +02001150# Python does not support forward declaration of types.
1151SSLContext.sslsocket_class = SSLSocket
1152SSLContext.sslobject_class = SSLObject
1153
1154
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001155def wrap_socket(sock, keyfile=None, certfile=None,
1156 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001157 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001158 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001159 suppress_ragged_eofs=True,
1160 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001161 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001163 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001164 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001165 suppress_ragged_eofs=suppress_ragged_eofs,
1166 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167
Thomas Woutersed03b412007-08-28 21:37:11 +00001168# some utility functions
1169
1170def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001171 """Return the time in seconds since the Epoch, given the timestring
1172 representing the "notBefore" or "notAfter" date from a certificate
1173 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001174
Antoine Pitrouc695c952014-04-28 20:57:36 +02001175 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1176
1177 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1178 UTC should be specified as GMT (see ASN1_TIME_print())
1179 """
1180 from time import strptime
1181 from calendar import timegm
1182
1183 months = (
1184 "Jan","Feb","Mar","Apr","May","Jun",
1185 "Jul","Aug","Sep","Oct","Nov","Dec"
1186 )
1187 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1188 try:
1189 month_number = months.index(cert_time[:3].title()) + 1
1190 except ValueError:
1191 raise ValueError('time data %r does not match '
1192 'format "%%b%s"' % (cert_time, time_format))
1193 else:
1194 # found valid month
1195 tt = strptime(cert_time[3:], time_format)
1196 # return an integer, the previous mktime()-based implementation
1197 # returned a float (fractional seconds are always zero here).
1198 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001199
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1201PEM_FOOTER = "-----END CERTIFICATE-----"
1202
1203def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204 """Takes a certificate in binary DER format and returns the
1205 PEM version of it as a string."""
1206
Bill Janssen6e027db2007-11-15 22:23:56 +00001207 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001208 ss = [PEM_HEADER]
1209 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1210 ss.append(PEM_FOOTER + '\n')
1211 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212
1213def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214 """Takes a certificate in ASCII PEM format and returns the
1215 DER-encoded version of it as a byte sequence"""
1216
1217 if not pem_cert_string.startswith(PEM_HEADER):
1218 raise ValueError("Invalid PEM encoding; must start with %s"
1219 % PEM_HEADER)
1220 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1221 raise ValueError("Invalid PEM encoding; must end with %s"
1222 % PEM_FOOTER)
1223 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001224 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225
Christian Heimes598894f2016-09-05 23:19:05 +02001226def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001227 """Retrieve the certificate from the server at the specified address,
1228 and return it as a PEM-encoded string.
1229 If 'ca_certs' is specified, validate the server cert against it.
1230 If 'ssl_version' is specified, use it in the connection attempt."""
1231
1232 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001233 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234 cert_reqs = CERT_REQUIRED
1235 else:
1236 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001237 context = _create_stdlib_context(ssl_version,
1238 cert_reqs=cert_reqs,
1239 cafile=ca_certs)
1240 with create_connection(addr) as sock:
1241 with context.wrap_socket(sock) as sslsock:
1242 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243 return DER_cert_to_PEM_cert(dercert)
1244
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001245def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001246 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')