blob: 3f5c3c4d07aab37f450e45488e7db4eadd467927 [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
54PROTOCOL_TLSv1
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010055PROTOCOL_TLSv1_1
56PROTOCOL_TLSv1_2
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +010057
58The following constants identify various SSL alert message descriptions as per
59http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
60
61ALERT_DESCRIPTION_CLOSE_NOTIFY
62ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
63ALERT_DESCRIPTION_BAD_RECORD_MAC
64ALERT_DESCRIPTION_RECORD_OVERFLOW
65ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
66ALERT_DESCRIPTION_HANDSHAKE_FAILURE
67ALERT_DESCRIPTION_BAD_CERTIFICATE
68ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
69ALERT_DESCRIPTION_CERTIFICATE_REVOKED
70ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
71ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
72ALERT_DESCRIPTION_ILLEGAL_PARAMETER
73ALERT_DESCRIPTION_UNKNOWN_CA
74ALERT_DESCRIPTION_ACCESS_DENIED
75ALERT_DESCRIPTION_DECODE_ERROR
76ALERT_DESCRIPTION_DECRYPT_ERROR
77ALERT_DESCRIPTION_PROTOCOL_VERSION
78ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
79ALERT_DESCRIPTION_INTERNAL_ERROR
80ALERT_DESCRIPTION_USER_CANCELLED
81ALERT_DESCRIPTION_NO_RENEGOTIATION
82ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
83ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
84ALERT_DESCRIPTION_UNRECOGNIZED_NAME
85ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
86ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
87ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
Thomas Woutersed03b412007-08-28 21:37:11 +000088"""
89
Antoine Pitrouc481bfb2015-02-15 18:12:20 +010090import ipaddress
Christian Heimes05e8be12008-02-23 18:30:17 +000091import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000092import re
Christian Heimes46bebee2013-06-09 19:03:31 +020093import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020094import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010095from collections import namedtuple
Antoine Pitrou172f0252014-04-18 20:33:08 +020096from enum import Enum as _Enum, IntEnum as _IntEnum
Thomas Woutersed03b412007-08-28 21:37:11 +000097
98import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000099
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000100from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200101from _ssl import _SSLContext, MemoryBIO
Antoine Pitrou41032a62011-10-27 23:56:55 +0200102from _ssl import (
103 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
104 SSLSyscallError, SSLEOFError,
105 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000106from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100107from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100108from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
109try:
110 from _ssl import RAND_egd
111except ImportError:
112 # LibreSSL does not provide RAND_egd
113 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100114
115def _import_symbols(prefix):
116 for n in dir(_ssl):
117 if n.startswith(prefix):
118 globals()[n] = getattr(_ssl, n)
119
120_import_symbols('OP_')
121_import_symbols('ALERT_DESCRIPTION_')
122_import_symbols('SSL_ERROR_')
Benjamin Peterson7bcf9a52015-03-04 23:18:57 -0500123_import_symbols('VERIFY_')
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100124
Benjamin Petersoncca27322015-01-23 16:35:37 -0500125from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100126
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200127from _ssl import _OPENSSL_API_VERSION
128
Ethan Furman24e837f2015-03-18 17:27:57 -0700129_IntEnum._convert(
130 '_SSLMethod', __name__,
131 lambda name: name.startswith('PROTOCOL_'),
132 source=_ssl)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100133
Antoine Pitrou172f0252014-04-18 20:33:08 +0200134_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
135
Victor Stinner3de49192011-05-09 00:42:58 +0200136try:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100137 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Antoine Pitrou172f0252014-04-18 20:33:08 +0200138except NameError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100139 _SSLv2_IF_EXISTS = None
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140
Christian Heimes46bebee2013-06-09 19:03:31 +0200141if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100142 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200143
Antoine Pitrou15399c32011-04-28 19:23:55 +0200144from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100145from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000146import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000147import errno
Steve Dower33bc4a22016-05-26 12:18:12 -0700148import warnings
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000149
Andrew Svetlov0832af62012-12-18 23:10:48 +0200150
151socket_error = OSError # keep that public name in module namespace
152
Antoine Pitroud6494802011-07-21 01:11:30 +0200153if _ssl.HAS_TLS_UNIQUE:
154 CHANNEL_BINDING_TYPES = ['tls-unique']
155else:
156 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000157
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100158# Disable weak or insecure ciphers by default
159# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400160# Enable a better set of ciphers by default
161# This list has been explicitly chosen to:
162# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
163# * Prefer ECDHE over DHE for better performance
164# * Prefer any AES-GCM over any AES-CBC for better performance and security
165# * Then Use HIGH cipher suites as a fallback
166# * Then Use 3DES as fallback which is secure but slow
Donald Stufft79ccaa22014-03-21 21:33:34 -0400167# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
168# reasons
169_DEFAULT_CIPHERS = (
170 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
Benjamin Peterson500af332015-02-19 17:57:08 -0500171 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
172 '!eNULL:!MD5'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400173)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100174
Donald Stufft6a2ba942014-03-23 19:05:28 -0400175# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400176# This list has been explicitly chosen to:
177# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
178# * Prefer ECDHE over DHE for better performance
179# * Prefer any AES-GCM over any AES-CBC for better performance and security
180# * Then Use HIGH cipher suites as a fallback
181# * Then Use 3DES as fallback which is secure but slow
182# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
183# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400184_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400185 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
186 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
187 '!eNULL:!MD5:!DSS:!RC4'
188)
Christian Heimes4c05b472013-11-23 15:58:30 +0100189
Thomas Woutersed03b412007-08-28 21:37:11 +0000190
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000191class CertificateError(ValueError):
192 pass
193
194
Georg Brandl72c98d32013-10-27 07:16:53 +0100195def _dnsname_match(dn, hostname, max_wildcards=1):
196 """Matching according to RFC 6125, section 6.4.3
197
198 http://tools.ietf.org/html/rfc6125#section-6.4.3
199 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000200 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100201 if not dn:
202 return False
203
204 leftmost, *remainder = dn.split(r'.')
205
206 wildcards = leftmost.count('*')
207 if wildcards > max_wildcards:
208 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300209 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100210 # policy among SSL implementations showed it to be a
211 # reasonable choice.
212 raise CertificateError(
213 "too many wildcards in certificate DNS name: " + repr(dn))
214
215 # speed up common case w/o wildcards
216 if not wildcards:
217 return dn.lower() == hostname.lower()
218
219 # RFC 6125, section 6.4.3, subitem 1.
220 # The client SHOULD NOT attempt to match a presented identifier in which
221 # the wildcard character comprises a label other than the left-most label.
222 if leftmost == '*':
223 # When '*' is a fragment by itself, it matches a non-empty dotless
224 # fragment.
225 pats.append('[^.]+')
226 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
227 # RFC 6125, section 6.4.3, subitem 3.
228 # The client SHOULD NOT attempt to match a presented identifier
229 # where the wildcard character is embedded within an A-label or
230 # U-label of an internationalized domain name.
231 pats.append(re.escape(leftmost))
232 else:
233 # Otherwise, '*' matches any dotless string, e.g. www*
234 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
235
236 # add the remaining fragments, ignore any wildcards
237 for frag in remainder:
238 pats.append(re.escape(frag))
239
240 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
241 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000242
243
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100244def _ipaddress_match(ipname, host_ip):
245 """Exact matching of IP addresses.
246
247 RFC 6125 explicitly doesn't define an algorithm for this
248 (section 1.7.2 - "Out of Scope").
249 """
250 # OpenSSL may add a trailing newline to a subjectAltName's IP address
251 ip = ipaddress.ip_address(ipname.rstrip())
252 return ip == host_ip
253
254
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000255def match_hostname(cert, hostname):
256 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100257 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
258 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000259
260 CertificateError is raised on failure. On success, the function
261 returns nothing.
262 """
263 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100264 raise ValueError("empty or no certificate, match_hostname needs a "
265 "SSL socket or SSL context with either "
266 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100267 try:
268 host_ip = ipaddress.ip_address(hostname)
269 except ValueError:
270 # Not an IP address (common case)
271 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000272 dnsnames = []
273 san = cert.get('subjectAltName', ())
274 for key, value in san:
275 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100276 if host_ip is None and _dnsname_match(value, hostname):
277 return
278 dnsnames.append(value)
279 elif key == 'IP Address':
280 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000281 return
282 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200283 if not dnsnames:
284 # The subject is only checked when there is no dNSName entry
285 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000286 for sub in cert.get('subject', ()):
287 for key, value in sub:
288 # XXX according to RFC 2818, the most specific Common Name
289 # must be used.
290 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100291 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000292 return
293 dnsnames.append(value)
294 if len(dnsnames) > 1:
295 raise CertificateError("hostname %r "
296 "doesn't match either of %s"
297 % (hostname, ', '.join(map(repr, dnsnames))))
298 elif len(dnsnames) == 1:
299 raise CertificateError("hostname %r "
300 "doesn't match %r"
301 % (hostname, dnsnames[0]))
302 else:
303 raise CertificateError("no appropriate commonName or "
304 "subjectAltName fields were found")
305
306
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100307DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200308 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
309 "openssl_capath")
310
311def get_default_verify_paths():
312 """Return paths to default cafile and capath.
313 """
314 parts = _ssl.get_default_verify_paths()
315
316 # environment vars shadow paths
317 cafile = os.environ.get(parts[0], parts[1])
318 capath = os.environ.get(parts[2], parts[3])
319
320 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
321 capath if os.path.isdir(capath) else None,
322 *parts)
323
324
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100325class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
326 """ASN.1 object identifier lookup
327 """
328 __slots__ = ()
329
330 def __new__(cls, oid):
331 return super().__new__(cls, *_txt2obj(oid, name=False))
332
333 @classmethod
334 def fromnid(cls, nid):
335 """Create _ASN1Object from OpenSSL numeric ID
336 """
337 return super().__new__(cls, *_nid2obj(nid))
338
339 @classmethod
340 def fromname(cls, name):
341 """Create _ASN1Object from short name, long name or OID
342 """
343 return super().__new__(cls, *_txt2obj(name, name=True))
344
345
Christian Heimes72d28502013-11-23 13:56:58 +0100346class Purpose(_ASN1Object, _Enum):
347 """SSLContext purpose flags with X509v3 Extended Key Usage objects
348 """
349 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
350 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
351
352
Antoine Pitrou152efa22010-05-16 18:19:27 +0000353class SSLContext(_SSLContext):
354 """An SSLContext holds various SSL-related configuration options and
355 data, such as certificates and possibly a private key."""
356
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100357 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100358 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000359
360 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100361 self = _SSLContext.__new__(cls, protocol)
362 if protocol != _SSLv2_IF_EXISTS:
363 self.set_ciphers(_DEFAULT_CIPHERS)
364 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000365
366 def __init__(self, protocol):
367 self.protocol = protocol
368
369 def wrap_socket(self, sock, server_side=False,
370 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000371 suppress_ragged_eofs=True,
372 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000373 return SSLSocket(sock=sock, server_side=server_side,
374 do_handshake_on_connect=do_handshake_on_connect,
375 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000376 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377 _context=self)
378
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200379 def wrap_bio(self, incoming, outgoing, server_side=False,
380 server_hostname=None):
381 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
382 server_hostname=server_hostname)
383 return SSLObject(sslobj)
384
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100385 def set_npn_protocols(self, npn_protocols):
386 protos = bytearray()
387 for protocol in npn_protocols:
388 b = bytes(protocol, 'ascii')
389 if len(b) == 0 or len(b) > 255:
390 raise SSLError('NPN protocols must be 1 to 255 in length')
391 protos.append(len(b))
392 protos.extend(b)
393
394 self._set_npn_protocols(protos)
395
Benjamin Petersoncca27322015-01-23 16:35:37 -0500396 def set_alpn_protocols(self, alpn_protocols):
397 protos = bytearray()
398 for protocol in alpn_protocols:
399 b = bytes(protocol, 'ascii')
400 if len(b) == 0 or len(b) > 255:
401 raise SSLError('ALPN protocols must be 1 to 255 in length')
402 protos.append(len(b))
403 protos.extend(b)
404
405 self._set_alpn_protocols(protos)
406
Christian Heimes72d28502013-11-23 13:56:58 +0100407 def _load_windows_store_certs(self, storename, purpose):
408 certs = bytearray()
Steve Dower33bc4a22016-05-26 12:18:12 -0700409 try:
410 for cert, encoding, trust in enum_certificates(storename):
411 # CA certs are never PKCS#7 encoded
412 if encoding == "x509_asn":
413 if trust is True or purpose.oid in trust:
414 certs.extend(cert)
415 except PermissionError:
416 warnings.warn("unable to enumerate Windows certificate store")
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700417 if certs:
418 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100419 return certs
420
421 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
422 if not isinstance(purpose, _ASN1Object):
423 raise TypeError(purpose)
424 if sys.platform == "win32":
425 for storename in self._windows_cert_stores:
426 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400427 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100428
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429
Christian Heimes4c05b472013-11-23 15:58:30 +0100430def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
431 capath=None, cadata=None):
432 """Create a SSLContext object with default settings.
433
434 NOTE: The protocol and settings may change anytime without prior
435 deprecation. The values represent a fair balance between maximum
436 compatibility and security.
437 """
438 if not isinstance(purpose, _ASN1Object):
439 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400440
441 context = SSLContext(PROTOCOL_SSLv23)
442
Christian Heimes4c05b472013-11-23 15:58:30 +0100443 # SSLv2 considered harmful.
444 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400445
446 # SSLv3 has problematic security and is only required for really old
447 # clients such as IE6 on Windows XP
448 context.options |= OP_NO_SSLv3
449
Christian Heimesdec813f2013-11-28 08:06:54 +0100450 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
451 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400452
Christian Heimes4c05b472013-11-23 15:58:30 +0100453 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400454 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100455 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100456 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400457 elif purpose == Purpose.CLIENT_AUTH:
458 # Prefer the server's ciphers by default so that we get stronger
459 # encryption
460 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
461
462 # Use single use keys in order to improve forward secrecy
463 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
464 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
465
466 # disallow ciphers with known vulnerabilities
467 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
468
Christian Heimes4c05b472013-11-23 15:58:30 +0100469 if cafile or capath or cadata:
470 context.load_verify_locations(cafile, capath, cadata)
471 elif context.verify_mode != CERT_NONE:
472 # no explicit cafile, capath or cadata but the verify mode is
473 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
474 # root CA certificates for the given purpose. This may fail silently.
475 context.load_default_certs(purpose)
476 return context
477
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500478def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100479 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100480 certfile=None, keyfile=None,
481 cafile=None, capath=None, cadata=None):
482 """Create a SSLContext object for Python stdlib modules
483
484 All Python stdlib modules shall use this function to create SSLContext
485 objects in order to keep common settings in one place. The configuration
486 is less restrict than create_default_context()'s to increase backward
487 compatibility.
488 """
489 if not isinstance(purpose, _ASN1Object):
490 raise TypeError(purpose)
491
492 context = SSLContext(protocol)
493 # SSLv2 considered harmful.
494 context.options |= OP_NO_SSLv2
Antoine Pitroue4eda4d2014-10-17 19:28:30 +0200495 # SSLv3 has problematic security and is only required for really old
496 # clients such as IE6 on Windows XP
497 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100498
499 if cert_reqs is not None:
500 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100501 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100502
503 if keyfile and not certfile:
504 raise ValueError("certfile must be specified")
505 if certfile or keyfile:
506 context.load_cert_chain(certfile, keyfile)
507
508 # load CA root certs
509 if cafile or capath or cadata:
510 context.load_verify_locations(cafile, capath, cadata)
511 elif context.verify_mode != CERT_NONE:
512 # no explicit cafile, capath or cadata but the verify mode is
513 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
514 # root CA certificates for the given purpose. This may fail silently.
515 context.load_default_certs(purpose)
516
517 return context
518
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500519# Used by http.client if no context is explicitly passed.
520_create_default_https_context = create_default_context
521
522
523# Backwards compatibility alias, even though it's not a public name.
524_create_stdlib_context = _create_unverified_context
525
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200526
527class SSLObject:
528 """This class implements an interface on top of a low-level SSL object as
529 implemented by OpenSSL. This object captures the state of an SSL connection
530 but does not provide any network IO itself. IO needs to be performed
531 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
532
533 This class does not have a public constructor. Instances are returned by
534 ``SSLContext.wrap_bio``. This class is typically used by framework authors
535 that want to implement asynchronous IO for SSL through memory buffers.
536
537 When compared to ``SSLSocket``, this object lacks the following features:
538
539 * Any form of network IO incluging methods such as ``recv`` and ``send``.
540 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
541 """
542
543 def __init__(self, sslobj, owner=None):
544 self._sslobj = sslobj
545 # Note: _sslobj takes a weak reference to owner
546 self._sslobj.owner = owner or self
547
548 @property
549 def context(self):
550 """The SSLContext that is currently in use."""
551 return self._sslobj.context
552
553 @context.setter
554 def context(self, ctx):
555 self._sslobj.context = ctx
556
557 @property
558 def server_side(self):
559 """Whether this is a server-side socket."""
560 return self._sslobj.server_side
561
562 @property
563 def server_hostname(self):
564 """The currently set server hostname (for SNI), or ``None`` if no
565 server hostame is set."""
566 return self._sslobj.server_hostname
567
Martin Panterf6b1d662016-03-28 00:22:09 +0000568 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200569 """Read up to 'len' bytes from the SSL object and return them.
570
571 If 'buffer' is provided, read into this buffer and return the number of
572 bytes read.
573 """
574 if buffer is not None:
575 v = self._sslobj.read(len, buffer)
576 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000577 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200578 return v
579
580 def write(self, data):
581 """Write 'data' to the SSL object and return the number of bytes
582 written.
583
584 The 'data' argument must support the buffer interface.
585 """
586 return self._sslobj.write(data)
587
588 def getpeercert(self, binary_form=False):
589 """Returns a formatted version of the data in the certificate provided
590 by the other end of the SSL channel.
591
592 Return None if no certificate was provided, {} if a certificate was
593 provided, but not validated.
594 """
595 return self._sslobj.peer_certificate(binary_form)
596
597 def selected_npn_protocol(self):
598 """Return the currently selected NPN protocol as a string, or ``None``
599 if a next protocol was not negotiated or if NPN is not supported by one
600 of the peers."""
601 if _ssl.HAS_NPN:
602 return self._sslobj.selected_npn_protocol()
603
Benjamin Petersoncca27322015-01-23 16:35:37 -0500604 def selected_alpn_protocol(self):
605 """Return the currently selected ALPN protocol as a string, or ``None``
606 if a next protocol was not negotiated or if ALPN is not supported by one
607 of the peers."""
608 if _ssl.HAS_ALPN:
609 return self._sslobj.selected_alpn_protocol()
610
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200611 def cipher(self):
612 """Return the currently selected cipher as a 3-tuple ``(name,
613 ssl_version, secret_bits)``."""
614 return self._sslobj.cipher()
615
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600616 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500617 """Return a list of ciphers shared by the client during the handshake or
618 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600619 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600620 return self._sslobj.shared_ciphers()
621
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200622 def compression(self):
623 """Return the current compression algorithm in use, or ``None`` if
624 compression was not negotiated or not supported by one of the peers."""
625 return self._sslobj.compression()
626
627 def pending(self):
628 """Return the number of bytes that can be read immediately."""
629 return self._sslobj.pending()
630
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200631 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 """Start the SSL/TLS handshake."""
633 self._sslobj.do_handshake()
634 if self.context.check_hostname:
635 if not self.server_hostname:
636 raise ValueError("check_hostname needs server_hostname "
637 "argument")
638 match_hostname(self.getpeercert(), self.server_hostname)
639
640 def unwrap(self):
641 """Start the SSL shutdown handshake."""
642 return self._sslobj.shutdown()
643
644 def get_channel_binding(self, cb_type="tls-unique"):
645 """Get channel binding data for current connection. Raise ValueError
646 if the requested `cb_type` is not supported. Return bytes of the data
647 or None if the data is not available (e.g. before the handshake)."""
648 if cb_type not in CHANNEL_BINDING_TYPES:
649 raise ValueError("Unsupported channel binding type")
650 if cb_type != "tls-unique":
651 raise NotImplementedError(
652 "{0} channel binding type not implemented"
653 .format(cb_type))
654 return self._sslobj.tls_unique_cb()
655
656 def version(self):
657 """Return a string identifying the protocol version used by the
658 current SSL channel. """
659 return self._sslobj.version()
660
661
Antoine Pitrou152efa22010-05-16 18:19:27 +0000662class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000663 """This class implements a subtype of socket.socket that wraps
664 the underlying OS socket in an SSL context when necessary, and
665 provides read and write methods over that channel."""
666
Bill Janssen6e027db2007-11-15 22:23:56 +0000667 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000668 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000669 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
670 do_handshake_on_connect=True,
671 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100672 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000673 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000674 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000675
Antoine Pitrou152efa22010-05-16 18:19:27 +0000676 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100677 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000678 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000679 if server_side and not certfile:
680 raise ValueError("certfile must be specified for server-side "
681 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000682 if keyfile and not certfile:
683 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000684 if certfile and not keyfile:
685 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100686 self._context = SSLContext(ssl_version)
687 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000688 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100689 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000690 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100691 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100692 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100693 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000694 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100695 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000696 self.keyfile = keyfile
697 self.certfile = certfile
698 self.cert_reqs = cert_reqs
699 self.ssl_version = ssl_version
700 self.ca_certs = ca_certs
701 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100702 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
703 # mixed in.
704 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
705 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000706 if server_side and server_hostname:
707 raise ValueError("server_hostname can only be specified "
708 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100709 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600710 raise ValueError("check_hostname requires server_hostname")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000711 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000712 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000713 self.do_handshake_on_connect = do_handshake_on_connect
714 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000715 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000716 socket.__init__(self,
717 family=sock.family,
718 type=sock.type,
719 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000720 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000721 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000722 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000723 elif fileno is not None:
724 socket.__init__(self, fileno=fileno)
725 else:
726 socket.__init__(self, family=family, type=type, proto=proto)
727
Antoine Pitrou242db722013-05-01 20:52:07 +0200728 # See if we are connected
729 try:
730 self.getpeername()
731 except OSError as e:
732 if e.errno != errno.ENOTCONN:
733 raise
734 connected = False
735 else:
736 connected = True
737
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000738 self._closed = False
739 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000740 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000741 if connected:
742 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000743 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200744 sslobj = self._context._wrap_socket(self, server_side,
745 server_hostname)
746 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000747 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000748 timeout = self.gettimeout()
749 if timeout == 0.0:
750 # non-blocking
751 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000752 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000753
Christian Heimes1aa9a752013-12-02 02:41:19 +0100754 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000755 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100756 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200757
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100758 @property
759 def context(self):
760 return self._context
761
762 @context.setter
763 def context(self, ctx):
764 self._context = ctx
765 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000766
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000767 def dup(self):
768 raise NotImplemented("Can't dup() %s instances" %
769 self.__class__.__name__)
770
Bill Janssen6e027db2007-11-15 22:23:56 +0000771 def _checkClosed(self, msg=None):
772 # raise an exception here if you wish to check for spurious closes
773 pass
774
Antoine Pitrou242db722013-05-01 20:52:07 +0200775 def _check_connected(self):
776 if not self._connected:
777 # getpeername() will raise ENOTCONN if the socket is really
778 # not connected; note that we can be connected even without
779 # _connected being set, e.g. if connect() first returned
780 # EAGAIN.
781 self.getpeername()
782
Martin Panterf6b1d662016-03-28 00:22:09 +0000783 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000784 """Read up to LEN bytes and return them.
785 Return zero-length string on EOF."""
786
Bill Janssen6e027db2007-11-15 22:23:56 +0000787 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200788 if not self._sslobj:
789 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000790 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200791 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000792 except SSLError as x:
793 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000794 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000795 return 0
796 else:
797 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000798 else:
799 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000800
801 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000802 """Write DATA to the underlying SSL channel. Returns
803 number of bytes of DATA actually transmitted."""
804
Bill Janssen6e027db2007-11-15 22:23:56 +0000805 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200806 if not self._sslobj:
807 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000808 return self._sslobj.write(data)
809
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000811 """Returns a formatted version of the data in the
812 certificate provided by the other end of the SSL channel.
813 Return None if no certificate was provided, {} if a
814 certificate was provided, but not validated."""
815
Bill Janssen6e027db2007-11-15 22:23:56 +0000816 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200817 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200818 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100820 def selected_npn_protocol(self):
821 self._checkClosed()
822 if not self._sslobj or not _ssl.HAS_NPN:
823 return None
824 else:
825 return self._sslobj.selected_npn_protocol()
826
Benjamin Petersoncca27322015-01-23 16:35:37 -0500827 def selected_alpn_protocol(self):
828 self._checkClosed()
829 if not self._sslobj or not _ssl.HAS_ALPN:
830 return None
831 else:
832 return self._sslobj.selected_alpn_protocol()
833
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000834 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000835 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836 if not self._sslobj:
837 return None
838 else:
839 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000840
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600841 def shared_ciphers(self):
842 self._checkClosed()
843 if not self._sslobj:
844 return None
845 return self._sslobj.shared_ciphers()
846
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100847 def compression(self):
848 self._checkClosed()
849 if not self._sslobj:
850 return None
851 else:
852 return self._sslobj.compression()
853
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000854 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000855 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000856 if self._sslobj:
857 if flags != 0:
858 raise ValueError(
859 "non-zero flags not allowed in calls to send() on %s" %
860 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200861 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000862 else:
863 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000864
Antoine Pitroua468adc2010-09-14 14:43:44 +0000865 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000866 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000867 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000868 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000869 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000870 elif addr is None:
871 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000872 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000873 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000874
Nick Coghlan513886a2011-08-28 00:00:27 +1000875 def sendmsg(self, *args, **kwargs):
876 # Ensure programs don't send data unencrypted if they try to
877 # use this method.
878 raise NotImplementedError("sendmsg not allowed on instances of %s" %
879 self.__class__)
880
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000881 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000882 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000883 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000884 if flags != 0:
885 raise ValueError(
886 "non-zero flags not allowed in calls to sendall() on %s" %
887 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000888 amount = len(data)
889 count = 0
890 while (count < amount):
891 v = self.send(data[count:])
892 count += v
893 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000894 else:
895 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000896
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200897 def sendfile(self, file, offset=0, count=None):
898 """Send a file, possibly by using os.sendfile() if this is a
899 clear-text socket. Return the total number of bytes sent.
900 """
901 if self._sslobj is None:
902 # os.sendfile() works with plain sockets only
903 return super().sendfile(file, offset, count)
904 else:
905 return self._sendfile_use_send(file, offset, count)
906
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000907 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000908 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000909 if self._sslobj:
910 if flags != 0:
911 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000912 "non-zero flags not allowed in calls to recv() on %s" %
913 self.__class__)
914 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000915 else:
916 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000917
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000918 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000919 self._checkClosed()
920 if buffer and (nbytes is None):
921 nbytes = len(buffer)
922 elif nbytes is None:
923 nbytes = 1024
924 if self._sslobj:
925 if flags != 0:
926 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000927 "non-zero flags not allowed in calls to recv_into() on %s" %
928 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000929 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000930 else:
931 return socket.recv_into(self, buffer, nbytes, flags)
932
Antoine Pitroua468adc2010-09-14 14:43:44 +0000933 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000934 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000935 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000936 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000937 self.__class__)
938 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000939 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000940
Bill Janssen58afe4c2008-09-08 16:45:19 +0000941 def recvfrom_into(self, buffer, nbytes=None, flags=0):
942 self._checkClosed()
943 if self._sslobj:
944 raise ValueError("recvfrom_into not allowed on instances of %s" %
945 self.__class__)
946 else:
947 return socket.recvfrom_into(self, buffer, nbytes, flags)
948
Nick Coghlan513886a2011-08-28 00:00:27 +1000949 def recvmsg(self, *args, **kwargs):
950 raise NotImplementedError("recvmsg not allowed on instances of %s" %
951 self.__class__)
952
953 def recvmsg_into(self, *args, **kwargs):
954 raise NotImplementedError("recvmsg_into not allowed on instances of "
955 "%s" % self.__class__)
956
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000957 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000958 self._checkClosed()
959 if self._sslobj:
960 return self._sslobj.pending()
961 else:
962 return 0
963
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000964 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000965 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000967 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000968
Ezio Melottidc55e672010-01-18 09:15:14 +0000969 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000970 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200971 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +0000972 self._sslobj = None
973 return s
974 else:
975 raise ValueError("No SSL wrapper around " + str(self))
976
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000977 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000979 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000980
Bill Janssen48dc27c2007-12-05 03:38:10 +0000981 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000982 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200983 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000984 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000985 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000986 if timeout == 0.0 and block:
987 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000988 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000989 finally:
990 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000991
Antoine Pitroub4410db2011-05-18 18:51:06 +0200992 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000993 if self.server_side:
994 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000995 # Here we assume that the socket is client-side, and not
996 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000997 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200999 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
1000 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen54cc54c2007-12-14 22:08:56 +00001001 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001002 if connect_ex:
1003 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001004 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001005 rc = None
1006 socket.connect(self, addr)
1007 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001008 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001009 if self.do_handshake_on_connect:
1010 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001011 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001012 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001013 self._sslobj = None
1014 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001015
1016 def connect(self, addr):
1017 """Connects to remote ADDR, and then wraps the connection in
1018 an SSL channel."""
1019 self._real_connect(addr, False)
1020
1021 def connect_ex(self, addr):
1022 """Connects to remote ADDR, and then wraps the connection in
1023 an SSL channel."""
1024 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001025
1026 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001027 """Accepts a new connection from a remote client, and returns
1028 a tuple containing that new connection wrapped with a server-side
1029 SSL channel, and the address of the remote client."""
1030
1031 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001032 newsock = self.context.wrap_socket(newsock,
1033 do_handshake_on_connect=self.do_handshake_on_connect,
1034 suppress_ragged_eofs=self.suppress_ragged_eofs,
1035 server_side=True)
1036 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037
Antoine Pitroud6494802011-07-21 01:11:30 +02001038 def get_channel_binding(self, cb_type="tls-unique"):
1039 """Get channel binding data for current connection. Raise ValueError
1040 if the requested `cb_type` is not supported. Return bytes of the data
1041 or None if the data is not available (e.g. before the handshake).
1042 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001043 if self._sslobj is None:
1044 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001045 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001046
Antoine Pitrou47e40422014-09-04 21:00:10 +02001047 def version(self):
1048 """
1049 Return a string identifying the protocol version used by the
1050 current SSL channel, or None if there is no established channel.
1051 """
1052 if self._sslobj is None:
1053 return None
1054 return self._sslobj.version()
1055
Bill Janssen54cc54c2007-12-14 22:08:56 +00001056
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057def wrap_socket(sock, keyfile=None, certfile=None,
1058 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +00001059 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001060 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001061 suppress_ragged_eofs=True,
1062 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Bill Janssen6e027db2007-11-15 22:23:56 +00001064 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001066 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001067 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001068 suppress_ragged_eofs=suppress_ragged_eofs,
1069 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Thomas Woutersed03b412007-08-28 21:37:11 +00001071# some utility functions
1072
1073def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001074 """Return the time in seconds since the Epoch, given the timestring
1075 representing the "notBefore" or "notAfter" date from a certificate
1076 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001077
Antoine Pitrouc695c952014-04-28 20:57:36 +02001078 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1079
1080 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1081 UTC should be specified as GMT (see ASN1_TIME_print())
1082 """
1083 from time import strptime
1084 from calendar import timegm
1085
1086 months = (
1087 "Jan","Feb","Mar","Apr","May","Jun",
1088 "Jul","Aug","Sep","Oct","Nov","Dec"
1089 )
1090 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1091 try:
1092 month_number = months.index(cert_time[:3].title()) + 1
1093 except ValueError:
1094 raise ValueError('time data %r does not match '
1095 'format "%%b%s"' % (cert_time, time_format))
1096 else:
1097 # found valid month
1098 tt = strptime(cert_time[3:], time_format)
1099 # return an integer, the previous mktime()-based implementation
1100 # returned a float (fractional seconds are always zero here).
1101 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001102
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1104PEM_FOOTER = "-----END CERTIFICATE-----"
1105
1106def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001107 """Takes a certificate in binary DER format and returns the
1108 PEM version of it as a string."""
1109
Bill Janssen6e027db2007-11-15 22:23:56 +00001110 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1111 return (PEM_HEADER + '\n' +
1112 textwrap.fill(f, 64) + '\n' +
1113 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
1115def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001116 """Takes a certificate in ASCII PEM format and returns the
1117 DER-encoded version of it as a byte sequence"""
1118
1119 if not pem_cert_string.startswith(PEM_HEADER):
1120 raise ValueError("Invalid PEM encoding; must start with %s"
1121 % PEM_HEADER)
1122 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1123 raise ValueError("Invalid PEM encoding; must end with %s"
1124 % PEM_FOOTER)
1125 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001126 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127
Antoine Pitrou94a5b662014-04-16 18:56:28 +02001128def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129 """Retrieve the certificate from the server at the specified address,
1130 and return it as a PEM-encoded string.
1131 If 'ca_certs' is specified, validate the server cert against it.
1132 If 'ssl_version' is specified, use it in the connection attempt."""
1133
1134 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001135 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 cert_reqs = CERT_REQUIRED
1137 else:
1138 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001139 context = _create_stdlib_context(ssl_version,
1140 cert_reqs=cert_reqs,
1141 cafile=ca_certs)
1142 with create_connection(addr) as sock:
1143 with context.wrap_socket(sock) as sslsock:
1144 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145 return DER_cert_to_PEM_cert(dercert)
1146
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001147def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001148 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')