blob: 75caae0c440566cc8dbe45b9fa36e8c97852d37d [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
Georg Brandl72c98d32013-10-27 07:16:53 +0100224def _dnsname_match(dn, hostname, max_wildcards=1):
225 """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('*')
236 if wildcards > max_wildcards:
237 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300238 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100239 # policy among SSL implementations showed it to be a
240 # reasonable choice.
241 raise CertificateError(
242 "too many wildcards in certificate DNS name: " + repr(dn))
243
244 # speed up common case w/o wildcards
245 if not wildcards:
246 return dn.lower() == hostname.lower()
247
248 # RFC 6125, section 6.4.3, subitem 1.
249 # The client SHOULD NOT attempt to match a presented identifier in which
250 # the wildcard character comprises a label other than the left-most label.
251 if leftmost == '*':
252 # When '*' is a fragment by itself, it matches a non-empty dotless
253 # fragment.
254 pats.append('[^.]+')
255 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
256 # RFC 6125, section 6.4.3, subitem 3.
257 # The client SHOULD NOT attempt to match a presented identifier
258 # where the wildcard character is embedded within an A-label or
259 # U-label of an internationalized domain name.
260 pats.append(re.escape(leftmost))
261 else:
262 # Otherwise, '*' matches any dotless string, e.g. www*
263 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
264
265 # add the remaining fragments, ignore any wildcards
266 for frag in remainder:
267 pats.append(re.escape(frag))
268
269 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
270 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000271
272
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100273def _ipaddress_match(ipname, host_ip):
274 """Exact matching of IP addresses.
275
276 RFC 6125 explicitly doesn't define an algorithm for this
277 (section 1.7.2 - "Out of Scope").
278 """
279 # OpenSSL may add a trailing newline to a subjectAltName's IP address
280 ip = ipaddress.ip_address(ipname.rstrip())
281 return ip == host_ip
282
283
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000284def match_hostname(cert, hostname):
285 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100286 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
287 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000288
289 CertificateError is raised on failure. On success, the function
290 returns nothing.
291 """
292 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100293 raise ValueError("empty or no certificate, match_hostname needs a "
294 "SSL socket or SSL context with either "
295 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100296 try:
297 host_ip = ipaddress.ip_address(hostname)
298 except ValueError:
299 # Not an IP address (common case)
300 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000301 dnsnames = []
302 san = cert.get('subjectAltName', ())
303 for key, value in san:
304 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100305 if host_ip is None and _dnsname_match(value, hostname):
306 return
307 dnsnames.append(value)
308 elif key == 'IP Address':
309 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000310 return
311 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200312 if not dnsnames:
313 # The subject is only checked when there is no dNSName entry
314 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000315 for sub in cert.get('subject', ()):
316 for key, value in sub:
317 # XXX according to RFC 2818, the most specific Common Name
318 # must be used.
319 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100320 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000321 return
322 dnsnames.append(value)
323 if len(dnsnames) > 1:
324 raise CertificateError("hostname %r "
325 "doesn't match either of %s"
326 % (hostname, ', '.join(map(repr, dnsnames))))
327 elif len(dnsnames) == 1:
328 raise CertificateError("hostname %r "
329 "doesn't match %r"
330 % (hostname, dnsnames[0]))
331 else:
332 raise CertificateError("no appropriate commonName or "
333 "subjectAltName fields were found")
334
335
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100336DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200337 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
338 "openssl_capath")
339
340def get_default_verify_paths():
341 """Return paths to default cafile and capath.
342 """
343 parts = _ssl.get_default_verify_paths()
344
345 # environment vars shadow paths
346 cafile = os.environ.get(parts[0], parts[1])
347 capath = os.environ.get(parts[2], parts[3])
348
349 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
350 capath if os.path.isdir(capath) else None,
351 *parts)
352
353
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100354class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
355 """ASN.1 object identifier lookup
356 """
357 __slots__ = ()
358
359 def __new__(cls, oid):
360 return super().__new__(cls, *_txt2obj(oid, name=False))
361
362 @classmethod
363 def fromnid(cls, nid):
364 """Create _ASN1Object from OpenSSL numeric ID
365 """
366 return super().__new__(cls, *_nid2obj(nid))
367
368 @classmethod
369 def fromname(cls, name):
370 """Create _ASN1Object from short name, long name or OID
371 """
372 return super().__new__(cls, *_txt2obj(name, name=True))
373
374
Christian Heimes72d28502013-11-23 13:56:58 +0100375class Purpose(_ASN1Object, _Enum):
376 """SSLContext purpose flags with X509v3 Extended Key Usage objects
377 """
378 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
379 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
380
381
Antoine Pitrou152efa22010-05-16 18:19:27 +0000382class SSLContext(_SSLContext):
383 """An SSLContext holds various SSL-related configuration options and
384 data, such as certificates and possibly a private key."""
Christian Heimes72d28502013-11-23 13:56:58 +0100385 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000386
Christian Heimes4df60f12017-09-15 20:26:05 +0200387 sslsocket_class = None # SSLSocket is assigned later.
388 sslobject_class = None # SSLObject is assigned later.
389
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):
Christian Heimes4df60f12017-09-15 20:26:05 +0200403 return self.sslsocket_class(
404 sock=sock,
405 server_side=server_side,
406 do_handshake_on_connect=do_handshake_on_connect,
407 suppress_ragged_eofs=suppress_ragged_eofs,
408 server_hostname=server_hostname,
409 _context=self,
410 _session=session
411 )
Antoine Pitrou152efa22010-05-16 18:19:27 +0000412
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200413 def wrap_bio(self, incoming, outgoing, server_side=False,
Christian Heimes99a65702016-09-10 23:44:53 +0200414 server_hostname=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200415 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
416 server_hostname=server_hostname)
Christian Heimes4df60f12017-09-15 20:26:05 +0200417 return self.sslobject_class(sslobj, session=session)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200418
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100419 def set_npn_protocols(self, npn_protocols):
420 protos = bytearray()
421 for protocol in npn_protocols:
422 b = bytes(protocol, 'ascii')
423 if len(b) == 0 or len(b) > 255:
424 raise SSLError('NPN protocols must be 1 to 255 in length')
425 protos.append(len(b))
426 protos.extend(b)
427
428 self._set_npn_protocols(protos)
429
Benjamin Petersoncca27322015-01-23 16:35:37 -0500430 def set_alpn_protocols(self, alpn_protocols):
431 protos = bytearray()
432 for protocol in alpn_protocols:
433 b = bytes(protocol, 'ascii')
434 if len(b) == 0 or len(b) > 255:
435 raise SSLError('ALPN protocols must be 1 to 255 in length')
436 protos.append(len(b))
437 protos.extend(b)
438
439 self._set_alpn_protocols(protos)
440
Christian Heimes72d28502013-11-23 13:56:58 +0100441 def _load_windows_store_certs(self, storename, purpose):
442 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700443 try:
444 for cert, encoding, trust in enum_certificates(storename):
445 # CA certs are never PKCS#7 encoded
446 if encoding == "x509_asn":
447 if trust is True or purpose.oid in trust:
448 certs.extend(cert)
449 except PermissionError:
450 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700451 if certs:
452 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100453 return certs
454
455 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
456 if not isinstance(purpose, _ASN1Object):
457 raise TypeError(purpose)
458 if sys.platform == "win32":
459 for storename in self._windows_cert_stores:
460 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400461 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100462
Christian Heimes3aeacad2016-09-10 00:19:35 +0200463 @property
464 def options(self):
465 return Options(super().options)
466
467 @options.setter
468 def options(self, value):
469 super(SSLContext, SSLContext).options.__set__(self, value)
470
471 @property
472 def verify_flags(self):
473 return VerifyFlags(super().verify_flags)
474
475 @verify_flags.setter
476 def verify_flags(self, value):
477 super(SSLContext, SSLContext).verify_flags.__set__(self, value)
478
479 @property
480 def verify_mode(self):
481 value = super().verify_mode
482 try:
483 return VerifyMode(value)
484 except ValueError:
485 return value
486
487 @verify_mode.setter
488 def verify_mode(self, value):
489 super(SSLContext, SSLContext).verify_mode.__set__(self, value)
490
Antoine Pitrou152efa22010-05-16 18:19:27 +0000491
Christian Heimes4c05b472013-11-23 15:58:30 +0100492def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
493 capath=None, cadata=None):
494 """Create a SSLContext object with default settings.
495
496 NOTE: The protocol and settings may change anytime without prior
497 deprecation. The values represent a fair balance between maximum
498 compatibility and security.
499 """
500 if not isinstance(purpose, _ASN1Object):
501 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400502
Christian Heimes358cfd42016-09-10 22:43:48 +0200503 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
504 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
505 # by default.
Christian Heimes598894f2016-09-05 23:19:05 +0200506 context = SSLContext(PROTOCOL_TLS)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400507
Christian Heimes4c05b472013-11-23 15:58:30 +0100508 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400509 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100510 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100511 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400512 elif purpose == Purpose.CLIENT_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400513 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
514
Christian Heimes4c05b472013-11-23 15:58:30 +0100515 if cafile or capath or cadata:
516 context.load_verify_locations(cafile, capath, cadata)
517 elif context.verify_mode != CERT_NONE:
518 # no explicit cafile, capath or cadata but the verify mode is
519 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
520 # root CA certificates for the given purpose. This may fail silently.
521 context.load_default_certs(purpose)
522 return context
523
Christian Heimesa170fa12017-09-15 20:27:30 +0200524def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=CERT_NONE,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100525 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100526 certfile=None, keyfile=None,
527 cafile=None, capath=None, cadata=None):
528 """Create a SSLContext object for Python stdlib modules
529
530 All Python stdlib modules shall use this function to create SSLContext
531 objects in order to keep common settings in one place. The configuration
532 is less restrict than create_default_context()'s to increase backward
533 compatibility.
534 """
535 if not isinstance(purpose, _ASN1Object):
536 raise TypeError(purpose)
537
Christian Heimes358cfd42016-09-10 22:43:48 +0200538 # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
539 # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
540 # by default.
Christian Heimes67986f92013-11-23 22:43:47 +0100541 context = SSLContext(protocol)
Christian Heimes67986f92013-11-23 22:43:47 +0100542
Christian Heimesa170fa12017-09-15 20:27:30 +0200543 if not check_hostname:
544 context.check_hostname = False
Christian Heimes67986f92013-11-23 22:43:47 +0100545 if cert_reqs is not None:
546 context.verify_mode = cert_reqs
Christian Heimesa170fa12017-09-15 20:27:30 +0200547 if check_hostname:
548 context.check_hostname = True
Christian Heimes67986f92013-11-23 22:43:47 +0100549
550 if keyfile and not certfile:
551 raise ValueError("certfile must be specified")
552 if certfile or keyfile:
553 context.load_cert_chain(certfile, keyfile)
554
555 # load CA root certs
556 if cafile or capath or cadata:
557 context.load_verify_locations(cafile, capath, cadata)
558 elif context.verify_mode != CERT_NONE:
559 # no explicit cafile, capath or cadata but the verify mode is
560 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
561 # root CA certificates for the given purpose. This may fail silently.
562 context.load_default_certs(purpose)
563
564 return context
565
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500566# Used by http.client if no context is explicitly passed.
567_create_default_https_context = create_default_context
568
569
570# Backwards compatibility alias, even though it's not a public name.
571_create_stdlib_context = _create_unverified_context
572
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200573
574class SSLObject:
575 """This class implements an interface on top of a low-level SSL object as
576 implemented by OpenSSL. This object captures the state of an SSL connection
577 but does not provide any network IO itself. IO needs to be performed
578 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
579
580 This class does not have a public constructor. Instances are returned by
581 ``SSLContext.wrap_bio``. This class is typically used by framework authors
582 that want to implement asynchronous IO for SSL through memory buffers.
583
584 When compared to ``SSLSocket``, this object lacks the following features:
585
586 * Any form of network IO incluging methods such as ``recv`` and ``send``.
587 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
588 """
589
Christian Heimes99a65702016-09-10 23:44:53 +0200590 def __init__(self, sslobj, owner=None, session=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200591 self._sslobj = sslobj
592 # Note: _sslobj takes a weak reference to owner
593 self._sslobj.owner = owner or self
Christian Heimes99a65702016-09-10 23:44:53 +0200594 if session is not None:
595 self._sslobj.session = session
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596
597 @property
598 def context(self):
599 """The SSLContext that is currently in use."""
600 return self._sslobj.context
601
602 @context.setter
603 def context(self, ctx):
604 self._sslobj.context = ctx
605
606 @property
Christian Heimes99a65702016-09-10 23:44:53 +0200607 def session(self):
608 """The SSLSession for client socket."""
609 return self._sslobj.session
610
611 @session.setter
612 def session(self, session):
613 self._sslobj.session = session
614
615 @property
616 def session_reused(self):
617 """Was the client session reused during handshake"""
618 return self._sslobj.session_reused
619
620 @property
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200621 def server_side(self):
622 """Whether this is a server-side socket."""
623 return self._sslobj.server_side
624
625 @property
626 def server_hostname(self):
627 """The currently set server hostname (for SNI), or ``None`` if no
628 server hostame is set."""
629 return self._sslobj.server_hostname
630
Martin Panterf6b1d662016-03-28 00:22:09 +0000631 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 """Read up to 'len' bytes from the SSL object and return them.
633
634 If 'buffer' is provided, read into this buffer and return the number of
635 bytes read.
636 """
637 if buffer is not None:
638 v = self._sslobj.read(len, buffer)
639 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000640 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200641 return v
642
643 def write(self, data):
644 """Write 'data' to the SSL object and return the number of bytes
645 written.
646
647 The 'data' argument must support the buffer interface.
648 """
649 return self._sslobj.write(data)
650
651 def getpeercert(self, binary_form=False):
652 """Returns a formatted version of the data in the certificate provided
653 by the other end of the SSL channel.
654
655 Return None if no certificate was provided, {} if a certificate was
656 provided, but not validated.
657 """
658 return self._sslobj.peer_certificate(binary_form)
659
660 def selected_npn_protocol(self):
661 """Return the currently selected NPN protocol as a string, or ``None``
662 if a next protocol was not negotiated or if NPN is not supported by one
663 of the peers."""
664 if _ssl.HAS_NPN:
665 return self._sslobj.selected_npn_protocol()
666
Benjamin Petersoncca27322015-01-23 16:35:37 -0500667 def selected_alpn_protocol(self):
668 """Return the currently selected ALPN protocol as a string, or ``None``
669 if a next protocol was not negotiated or if ALPN is not supported by one
670 of the peers."""
671 if _ssl.HAS_ALPN:
672 return self._sslobj.selected_alpn_protocol()
673
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200674 def cipher(self):
675 """Return the currently selected cipher as a 3-tuple ``(name,
676 ssl_version, secret_bits)``."""
677 return self._sslobj.cipher()
678
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600679 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500680 """Return a list of ciphers shared by the client during the handshake or
681 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600682 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600683 return self._sslobj.shared_ciphers()
684
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200685 def compression(self):
686 """Return the current compression algorithm in use, or ``None`` if
687 compression was not negotiated or not supported by one of the peers."""
688 return self._sslobj.compression()
689
690 def pending(self):
691 """Return the number of bytes that can be read immediately."""
692 return self._sslobj.pending()
693
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200694 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200695 """Start the SSL/TLS handshake."""
696 self._sslobj.do_handshake()
697 if self.context.check_hostname:
698 if not self.server_hostname:
699 raise ValueError("check_hostname needs server_hostname "
700 "argument")
701 match_hostname(self.getpeercert(), self.server_hostname)
702
703 def unwrap(self):
704 """Start the SSL shutdown handshake."""
705 return self._sslobj.shutdown()
706
707 def get_channel_binding(self, cb_type="tls-unique"):
708 """Get channel binding data for current connection. Raise ValueError
709 if the requested `cb_type` is not supported. Return bytes of the data
710 or None if the data is not available (e.g. before the handshake)."""
711 if cb_type not in CHANNEL_BINDING_TYPES:
712 raise ValueError("Unsupported channel binding type")
713 if cb_type != "tls-unique":
714 raise NotImplementedError(
715 "{0} channel binding type not implemented"
716 .format(cb_type))
717 return self._sslobj.tls_unique_cb()
718
719 def version(self):
720 """Return a string identifying the protocol version used by the
721 current SSL channel. """
722 return self._sslobj.version()
723
724
Antoine Pitrou152efa22010-05-16 18:19:27 +0000725class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000726 """This class implements a subtype of socket.socket that wraps
727 the underlying OS socket in an SSL context when necessary, and
728 provides read and write methods over that channel."""
729
Bill Janssen6e027db2007-11-15 22:23:56 +0000730 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000731 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +0200732 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen6e027db2007-11-15 22:23:56 +0000733 do_handshake_on_connect=True,
734 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100735 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000736 server_hostname=None,
Christian Heimes99a65702016-09-10 23:44:53 +0200737 _context=None, _session=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000738
Antoine Pitrou152efa22010-05-16 18:19:27 +0000739 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100740 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000741 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000742 if server_side and not certfile:
743 raise ValueError("certfile must be specified for server-side "
744 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000745 if keyfile and not certfile:
746 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000747 if certfile and not keyfile:
748 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100749 self._context = SSLContext(ssl_version)
750 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000751 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100752 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000753 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100754 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100755 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000757 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100758 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000759 self.keyfile = keyfile
760 self.certfile = certfile
761 self.cert_reqs = cert_reqs
762 self.ssl_version = ssl_version
763 self.ca_certs = ca_certs
764 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100765 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
766 # mixed in.
767 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
768 raise NotImplementedError("only stream sockets are supported")
Christian Heimes99a65702016-09-10 23:44:53 +0200769 if server_side:
770 if server_hostname:
771 raise ValueError("server_hostname can only be specified "
772 "in client mode")
773 if _session is not None:
774 raise ValueError("session can only be specified in "
775 "client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100776 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600777 raise ValueError("check_hostname requires server_hostname")
Christian Heimes99a65702016-09-10 23:44:53 +0200778 self._session = _session
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000779 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000780 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000781 self.do_handshake_on_connect = do_handshake_on_connect
782 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000783 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000784 socket.__init__(self,
785 family=sock.family,
786 type=sock.type,
787 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000788 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000789 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000790 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000791 elif fileno is not None:
792 socket.__init__(self, fileno=fileno)
793 else:
794 socket.__init__(self, family=family, type=type, proto=proto)
795
Antoine Pitrou242db722013-05-01 20:52:07 +0200796 # See if we are connected
797 try:
798 self.getpeername()
799 except OSError as e:
800 if e.errno != errno.ENOTCONN:
801 raise
802 connected = False
803 else:
804 connected = True
805
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000806 self._closed = False
807 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000808 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000809 if connected:
810 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000811 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200812 sslobj = self._context._wrap_socket(self, server_side,
813 server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +0200814 self._sslobj = SSLObject(sslobj, owner=self,
815 session=self._session)
Bill Janssen6e027db2007-11-15 22:23:56 +0000816 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000817 timeout = self.gettimeout()
818 if timeout == 0.0:
819 # non-blocking
820 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000821 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000822
Christian Heimes1aa9a752013-12-02 02:41:19 +0100823 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000824 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100825 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200826
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100827 @property
828 def context(self):
829 return self._context
830
831 @context.setter
832 def context(self, ctx):
833 self._context = ctx
834 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000835
Christian Heimes99a65702016-09-10 23:44:53 +0200836 @property
837 def session(self):
838 """The SSLSession for client socket."""
839 if self._sslobj is not None:
840 return self._sslobj.session
841
842 @session.setter
843 def session(self, session):
844 self._session = session
845 if self._sslobj is not None:
846 self._sslobj.session = session
847
848 @property
849 def session_reused(self):
850 """Was the client session reused during handshake"""
851 if self._sslobj is not None:
852 return self._sslobj.session_reused
853
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000854 def dup(self):
855 raise NotImplemented("Can't dup() %s instances" %
856 self.__class__.__name__)
857
Bill Janssen6e027db2007-11-15 22:23:56 +0000858 def _checkClosed(self, msg=None):
859 # raise an exception here if you wish to check for spurious closes
860 pass
861
Antoine Pitrou242db722013-05-01 20:52:07 +0200862 def _check_connected(self):
863 if not self._connected:
864 # getpeername() will raise ENOTCONN if the socket is really
865 # not connected; note that we can be connected even without
866 # _connected being set, e.g. if connect() first returned
867 # EAGAIN.
868 self.getpeername()
869
Martin Panterf6b1d662016-03-28 00:22:09 +0000870 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000871 """Read up to LEN bytes and return them.
872 Return zero-length string on EOF."""
873
Bill Janssen6e027db2007-11-15 22:23:56 +0000874 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200875 if not self._sslobj:
876 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000877 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200878 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000879 except SSLError as x:
880 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000881 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000882 return 0
883 else:
884 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000885 else:
886 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000887
888 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000889 """Write DATA to the underlying SSL channel. Returns
890 number of bytes of DATA actually transmitted."""
891
Bill Janssen6e027db2007-11-15 22:23:56 +0000892 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200893 if not self._sslobj:
894 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000895 return self._sslobj.write(data)
896
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000898 """Returns a formatted version of the data in the
899 certificate provided by the other end of the SSL channel.
900 Return None if no certificate was provided, {} if a
901 certificate was provided, but not validated."""
902
Bill Janssen6e027db2007-11-15 22:23:56 +0000903 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200904 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200905 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100907 def selected_npn_protocol(self):
908 self._checkClosed()
909 if not self._sslobj or not _ssl.HAS_NPN:
910 return None
911 else:
912 return self._sslobj.selected_npn_protocol()
913
Benjamin Petersoncca27322015-01-23 16:35:37 -0500914 def selected_alpn_protocol(self):
915 self._checkClosed()
916 if not self._sslobj or not _ssl.HAS_ALPN:
917 return None
918 else:
919 return self._sslobj.selected_alpn_protocol()
920
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000921 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000922 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923 if not self._sslobj:
924 return None
925 else:
926 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000927
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600928 def shared_ciphers(self):
929 self._checkClosed()
930 if not self._sslobj:
931 return None
932 return self._sslobj.shared_ciphers()
933
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100934 def compression(self):
935 self._checkClosed()
936 if not self._sslobj:
937 return None
938 else:
939 return self._sslobj.compression()
940
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000941 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000942 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000943 if self._sslobj:
944 if flags != 0:
945 raise ValueError(
946 "non-zero flags not allowed in calls to send() on %s" %
947 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200948 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000949 else:
950 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000951
Antoine Pitroua468adc2010-09-14 14:43:44 +0000952 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000953 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000954 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000955 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000956 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000957 elif addr is None:
958 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000959 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000960 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000961
Nick Coghlan513886a2011-08-28 00:00:27 +1000962 def sendmsg(self, *args, **kwargs):
963 # Ensure programs don't send data unencrypted if they try to
964 # use this method.
965 raise NotImplementedError("sendmsg not allowed on instances of %s" %
966 self.__class__)
967
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000968 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000969 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000970 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000971 if flags != 0:
972 raise ValueError(
973 "non-zero flags not allowed in calls to sendall() on %s" %
974 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000975 count = 0
Christian Heimes888bbdc2017-09-07 14:18:21 -0700976 with memoryview(data) as view, view.cast("B") as byte_view:
977 amount = len(byte_view)
978 while count < amount:
979 v = self.send(byte_view[count:])
980 count += v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000981 else:
982 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000983
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200984 def sendfile(self, file, offset=0, count=None):
985 """Send a file, possibly by using os.sendfile() if this is a
986 clear-text socket. Return the total number of bytes sent.
987 """
988 if self._sslobj is None:
989 # os.sendfile() works with plain sockets only
990 return super().sendfile(file, offset, count)
991 else:
992 return self._sendfile_use_send(file, offset, count)
993
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000994 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000995 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000996 if self._sslobj:
997 if flags != 0:
998 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000999 "non-zero flags not allowed in calls to recv() on %s" %
1000 self.__class__)
1001 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001002 else:
1003 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001004
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001005 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001006 self._checkClosed()
1007 if buffer and (nbytes is None):
1008 nbytes = len(buffer)
1009 elif nbytes is None:
1010 nbytes = 1024
1011 if self._sslobj:
1012 if flags != 0:
1013 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001014 "non-zero flags not allowed in calls to recv_into() on %s" %
1015 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +00001016 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +00001017 else:
1018 return socket.recv_into(self, buffer, nbytes, flags)
1019
Antoine Pitroua468adc2010-09-14 14:43:44 +00001020 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +00001021 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001022 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +00001023 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001024 self.__class__)
1025 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +00001026 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +00001027
Bill Janssen58afe4c2008-09-08 16:45:19 +00001028 def recvfrom_into(self, buffer, nbytes=None, flags=0):
1029 self._checkClosed()
1030 if self._sslobj:
1031 raise ValueError("recvfrom_into not allowed on instances of %s" %
1032 self.__class__)
1033 else:
1034 return socket.recvfrom_into(self, buffer, nbytes, flags)
1035
Nick Coghlan513886a2011-08-28 00:00:27 +10001036 def recvmsg(self, *args, **kwargs):
1037 raise NotImplementedError("recvmsg not allowed on instances of %s" %
1038 self.__class__)
1039
1040 def recvmsg_into(self, *args, **kwargs):
1041 raise NotImplementedError("recvmsg_into not allowed on instances of "
1042 "%s" % self.__class__)
1043
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001044 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +00001045 self._checkClosed()
1046 if self._sslobj:
1047 return self._sslobj.pending()
1048 else:
1049 return 0
1050
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001051 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +00001052 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001054 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +00001055
Ezio Melottidc55e672010-01-18 09:15:14 +00001056 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +00001057 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001058 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +00001059 self._sslobj = None
1060 return s
1061 else:
1062 raise ValueError("No SSL wrapper around " + str(self))
1063
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001064 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +00001066 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001067
Bill Janssen48dc27c2007-12-05 03:38:10 +00001068 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +00001069 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +02001070 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001071 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +00001072 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +00001073 if timeout == 0.0 and block:
1074 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +00001075 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +00001076 finally:
1077 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +00001078
Antoine Pitroub4410db2011-05-18 18:51:06 +02001079 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001080 if self.server_side:
1081 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +00001082 # Here we assume that the socket is client-side, and not
1083 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001084 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001086 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Christian Heimes99a65702016-09-10 23:44:53 +02001087 self._sslobj = SSLObject(sslobj, owner=self,
1088 session=self._session)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001089 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001090 if connect_ex:
1091 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001092 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001093 rc = None
1094 socket.connect(self, addr)
1095 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001096 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001097 if self.do_handshake_on_connect:
1098 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001099 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001100 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001101 self._sslobj = None
1102 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001103
1104 def connect(self, addr):
1105 """Connects to remote ADDR, and then wraps the connection in
1106 an SSL channel."""
1107 self._real_connect(addr, False)
1108
1109 def connect_ex(self, addr):
1110 """Connects to remote ADDR, and then wraps the connection in
1111 an SSL channel."""
1112 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001113
1114 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001115 """Accepts a new connection from a remote client, and returns
1116 a tuple containing that new connection wrapped with a server-side
1117 SSL channel, and the address of the remote client."""
1118
1119 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001120 newsock = self.context.wrap_socket(newsock,
1121 do_handshake_on_connect=self.do_handshake_on_connect,
1122 suppress_ragged_eofs=self.suppress_ragged_eofs,
1123 server_side=True)
1124 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125
Antoine Pitroud6494802011-07-21 01:11:30 +02001126 def get_channel_binding(self, cb_type="tls-unique"):
1127 """Get channel binding data for current connection. Raise ValueError
1128 if the requested `cb_type` is not supported. Return bytes of the data
1129 or None if the data is not available (e.g. before the handshake).
1130 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001131 if self._sslobj is None:
1132 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001133 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001134
Antoine Pitrou47e40422014-09-04 21:00:10 +02001135 def version(self):
1136 """
1137 Return a string identifying the protocol version used by the
1138 current SSL channel, or None if there is no established channel.
1139 """
1140 if self._sslobj is None:
1141 return None
1142 return self._sslobj.version()
1143
Bill Janssen54cc54c2007-12-14 22:08:56 +00001144
Christian Heimes4df60f12017-09-15 20:26:05 +02001145# Python does not support forward declaration of types.
1146SSLContext.sslsocket_class = SSLSocket
1147SSLContext.sslobject_class = SSLObject
1148
1149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150def wrap_socket(sock, keyfile=None, certfile=None,
1151 server_side=False, cert_reqs=CERT_NONE,
Christian Heimes598894f2016-09-05 23:19:05 +02001152 ssl_version=PROTOCOL_TLS, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001153 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001154 suppress_ragged_eofs=True,
1155 ciphers=None):
Bill Janssen6e027db2007-11-15 22:23:56 +00001156 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001157 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001158 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001159 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001160 suppress_ragged_eofs=suppress_ragged_eofs,
1161 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162
Thomas Woutersed03b412007-08-28 21:37:11 +00001163# some utility functions
1164
1165def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001166 """Return the time in seconds since the Epoch, given the timestring
1167 representing the "notBefore" or "notAfter" date from a certificate
1168 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001169
Antoine Pitrouc695c952014-04-28 20:57:36 +02001170 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1171
1172 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1173 UTC should be specified as GMT (see ASN1_TIME_print())
1174 """
1175 from time import strptime
1176 from calendar import timegm
1177
1178 months = (
1179 "Jan","Feb","Mar","Apr","May","Jun",
1180 "Jul","Aug","Sep","Oct","Nov","Dec"
1181 )
1182 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1183 try:
1184 month_number = months.index(cert_time[:3].title()) + 1
1185 except ValueError:
1186 raise ValueError('time data %r does not match '
1187 'format "%%b%s"' % (cert_time, time_format))
1188 else:
1189 # found valid month
1190 tt = strptime(cert_time[3:], time_format)
1191 # return an integer, the previous mktime()-based implementation
1192 # returned a float (fractional seconds are always zero here).
1193 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1196PEM_FOOTER = "-----END CERTIFICATE-----"
1197
1198def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199 """Takes a certificate in binary DER format and returns the
1200 PEM version of it as a string."""
1201
Bill Janssen6e027db2007-11-15 22:23:56 +00001202 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
INADA Naokib75a2282017-10-02 16:33:42 +09001203 ss = [PEM_HEADER]
1204 ss += [f[i:i+64] for i in range(0, len(f), 64)]
1205 ss.append(PEM_FOOTER + '\n')
1206 return '\n'.join(ss)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
1208def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209 """Takes a certificate in ASCII PEM format and returns the
1210 DER-encoded version of it as a byte sequence"""
1211
1212 if not pem_cert_string.startswith(PEM_HEADER):
1213 raise ValueError("Invalid PEM encoding; must start with %s"
1214 % PEM_HEADER)
1215 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1216 raise ValueError("Invalid PEM encoding; must end with %s"
1217 % PEM_FOOTER)
1218 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001219 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001220
Christian Heimes598894f2016-09-05 23:19:05 +02001221def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222 """Retrieve the certificate from the server at the specified address,
1223 and return it as a PEM-encoded string.
1224 If 'ca_certs' is specified, validate the server cert against it.
1225 If 'ssl_version' is specified, use it in the connection attempt."""
1226
1227 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001228 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229 cert_reqs = CERT_REQUIRED
1230 else:
1231 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001232 context = _create_stdlib_context(ssl_version,
1233 cert_reqs=cert_reqs,
1234 cafile=ca_certs)
1235 with create_connection(addr) as sock:
1236 with context.wrap_socket(sock) as sslsock:
1237 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238 return DER_cert_to_PEM_cert(dercert)
1239
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001240def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001241 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')