blob: 65ad38f899ed4660fe21c20dc9ce6091803e5301 [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
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000148
Andrew Svetlov0832af62012-12-18 23:10:48 +0200149
150socket_error = OSError # keep that public name in module namespace
151
Antoine Pitroud6494802011-07-21 01:11:30 +0200152if _ssl.HAS_TLS_UNIQUE:
153 CHANNEL_BINDING_TYPES = ['tls-unique']
154else:
155 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000156
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100157# Disable weak or insecure ciphers by default
158# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400159# Enable a better set of ciphers by default
160# This list has been explicitly chosen to:
161# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
162# * Prefer ECDHE over DHE for better performance
163# * Prefer any AES-GCM over any AES-CBC for better performance and security
164# * Then Use HIGH cipher suites as a fallback
165# * Then Use 3DES as fallback which is secure but slow
Donald Stufft79ccaa22014-03-21 21:33:34 -0400166# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
167# reasons
168_DEFAULT_CIPHERS = (
169 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
Benjamin Peterson500af332015-02-19 17:57:08 -0500170 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
171 '!eNULL:!MD5'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400172)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100173
Donald Stufft6a2ba942014-03-23 19:05:28 -0400174# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400175# This list has been explicitly chosen to:
176# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
177# * Prefer ECDHE over DHE for better performance
178# * Prefer any AES-GCM over any AES-CBC for better performance and security
179# * Then Use HIGH cipher suites as a fallback
180# * Then Use 3DES as fallback which is secure but slow
181# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
182# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400183_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400184 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
185 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
186 '!eNULL:!MD5:!DSS:!RC4'
187)
Christian Heimes4c05b472013-11-23 15:58:30 +0100188
Thomas Woutersed03b412007-08-28 21:37:11 +0000189
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000190class CertificateError(ValueError):
191 pass
192
193
Georg Brandl72c98d32013-10-27 07:16:53 +0100194def _dnsname_match(dn, hostname, max_wildcards=1):
195 """Matching according to RFC 6125, section 6.4.3
196
197 http://tools.ietf.org/html/rfc6125#section-6.4.3
198 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000199 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100200 if not dn:
201 return False
202
203 leftmost, *remainder = dn.split(r'.')
204
205 wildcards = leftmost.count('*')
206 if wildcards > max_wildcards:
207 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300208 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100209 # policy among SSL implementations showed it to be a
210 # reasonable choice.
211 raise CertificateError(
212 "too many wildcards in certificate DNS name: " + repr(dn))
213
214 # speed up common case w/o wildcards
215 if not wildcards:
216 return dn.lower() == hostname.lower()
217
218 # RFC 6125, section 6.4.3, subitem 1.
219 # The client SHOULD NOT attempt to match a presented identifier in which
220 # the wildcard character comprises a label other than the left-most label.
221 if leftmost == '*':
222 # When '*' is a fragment by itself, it matches a non-empty dotless
223 # fragment.
224 pats.append('[^.]+')
225 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
226 # RFC 6125, section 6.4.3, subitem 3.
227 # The client SHOULD NOT attempt to match a presented identifier
228 # where the wildcard character is embedded within an A-label or
229 # U-label of an internationalized domain name.
230 pats.append(re.escape(leftmost))
231 else:
232 # Otherwise, '*' matches any dotless string, e.g. www*
233 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
234
235 # add the remaining fragments, ignore any wildcards
236 for frag in remainder:
237 pats.append(re.escape(frag))
238
239 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
240 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000241
242
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100243def _ipaddress_match(ipname, host_ip):
244 """Exact matching of IP addresses.
245
246 RFC 6125 explicitly doesn't define an algorithm for this
247 (section 1.7.2 - "Out of Scope").
248 """
249 # OpenSSL may add a trailing newline to a subjectAltName's IP address
250 ip = ipaddress.ip_address(ipname.rstrip())
251 return ip == host_ip
252
253
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000254def match_hostname(cert, hostname):
255 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100256 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
257 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000258
259 CertificateError is raised on failure. On success, the function
260 returns nothing.
261 """
262 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100263 raise ValueError("empty or no certificate, match_hostname needs a "
264 "SSL socket or SSL context with either "
265 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100266 try:
267 host_ip = ipaddress.ip_address(hostname)
268 except ValueError:
269 # Not an IP address (common case)
270 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000271 dnsnames = []
272 san = cert.get('subjectAltName', ())
273 for key, value in san:
274 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100275 if host_ip is None and _dnsname_match(value, hostname):
276 return
277 dnsnames.append(value)
278 elif key == 'IP Address':
279 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000280 return
281 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200282 if not dnsnames:
283 # The subject is only checked when there is no dNSName entry
284 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000285 for sub in cert.get('subject', ()):
286 for key, value in sub:
287 # XXX according to RFC 2818, the most specific Common Name
288 # must be used.
289 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100290 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000291 return
292 dnsnames.append(value)
293 if len(dnsnames) > 1:
294 raise CertificateError("hostname %r "
295 "doesn't match either of %s"
296 % (hostname, ', '.join(map(repr, dnsnames))))
297 elif len(dnsnames) == 1:
298 raise CertificateError("hostname %r "
299 "doesn't match %r"
300 % (hostname, dnsnames[0]))
301 else:
302 raise CertificateError("no appropriate commonName or "
303 "subjectAltName fields were found")
304
305
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100306DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200307 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
308 "openssl_capath")
309
310def get_default_verify_paths():
311 """Return paths to default cafile and capath.
312 """
313 parts = _ssl.get_default_verify_paths()
314
315 # environment vars shadow paths
316 cafile = os.environ.get(parts[0], parts[1])
317 capath = os.environ.get(parts[2], parts[3])
318
319 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
320 capath if os.path.isdir(capath) else None,
321 *parts)
322
323
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100324class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
325 """ASN.1 object identifier lookup
326 """
327 __slots__ = ()
328
329 def __new__(cls, oid):
330 return super().__new__(cls, *_txt2obj(oid, name=False))
331
332 @classmethod
333 def fromnid(cls, nid):
334 """Create _ASN1Object from OpenSSL numeric ID
335 """
336 return super().__new__(cls, *_nid2obj(nid))
337
338 @classmethod
339 def fromname(cls, name):
340 """Create _ASN1Object from short name, long name or OID
341 """
342 return super().__new__(cls, *_txt2obj(name, name=True))
343
344
Christian Heimes72d28502013-11-23 13:56:58 +0100345class Purpose(_ASN1Object, _Enum):
346 """SSLContext purpose flags with X509v3 Extended Key Usage objects
347 """
348 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
349 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
350
351
Antoine Pitrou152efa22010-05-16 18:19:27 +0000352class SSLContext(_SSLContext):
353 """An SSLContext holds various SSL-related configuration options and
354 data, such as certificates and possibly a private key."""
355
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100356 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100357 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000358
359 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100360 self = _SSLContext.__new__(cls, protocol)
361 if protocol != _SSLv2_IF_EXISTS:
362 self.set_ciphers(_DEFAULT_CIPHERS)
363 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364
365 def __init__(self, protocol):
366 self.protocol = protocol
367
368 def wrap_socket(self, sock, server_side=False,
369 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000370 suppress_ragged_eofs=True,
371 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000372 return SSLSocket(sock=sock, server_side=server_side,
373 do_handshake_on_connect=do_handshake_on_connect,
374 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000375 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000376 _context=self)
377
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200378 def wrap_bio(self, incoming, outgoing, server_side=False,
379 server_hostname=None):
380 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
381 server_hostname=server_hostname)
382 return SSLObject(sslobj)
383
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100384 def set_npn_protocols(self, npn_protocols):
385 protos = bytearray()
386 for protocol in npn_protocols:
387 b = bytes(protocol, 'ascii')
388 if len(b) == 0 or len(b) > 255:
389 raise SSLError('NPN protocols must be 1 to 255 in length')
390 protos.append(len(b))
391 protos.extend(b)
392
393 self._set_npn_protocols(protos)
394
Benjamin Petersoncca27322015-01-23 16:35:37 -0500395 def set_alpn_protocols(self, alpn_protocols):
396 protos = bytearray()
397 for protocol in alpn_protocols:
398 b = bytes(protocol, 'ascii')
399 if len(b) == 0 or len(b) > 255:
400 raise SSLError('ALPN protocols must be 1 to 255 in length')
401 protos.append(len(b))
402 protos.extend(b)
403
404 self._set_alpn_protocols(protos)
405
Christian Heimes72d28502013-11-23 13:56:58 +0100406 def _load_windows_store_certs(self, storename, purpose):
407 certs = bytearray()
408 for cert, encoding, trust in enum_certificates(storename):
409 # CA certs are never PKCS#7 encoded
410 if encoding == "x509_asn":
411 if trust is True or purpose.oid in trust:
412 certs.extend(cert)
Steve Dower8dd7aeb2016-03-17 15:02:39 -0700413 if certs:
414 self.load_verify_locations(cadata=certs)
Christian Heimes72d28502013-11-23 13:56:58 +0100415 return certs
416
417 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
418 if not isinstance(purpose, _ASN1Object):
419 raise TypeError(purpose)
420 if sys.platform == "win32":
421 for storename in self._windows_cert_stores:
422 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400423 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100424
Antoine Pitrou152efa22010-05-16 18:19:27 +0000425
Christian Heimes4c05b472013-11-23 15:58:30 +0100426def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
427 capath=None, cadata=None):
428 """Create a SSLContext object with default settings.
429
430 NOTE: The protocol and settings may change anytime without prior
431 deprecation. The values represent a fair balance between maximum
432 compatibility and security.
433 """
434 if not isinstance(purpose, _ASN1Object):
435 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400436
437 context = SSLContext(PROTOCOL_SSLv23)
438
Christian Heimes4c05b472013-11-23 15:58:30 +0100439 # SSLv2 considered harmful.
440 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400441
442 # SSLv3 has problematic security and is only required for really old
443 # clients such as IE6 on Windows XP
444 context.options |= OP_NO_SSLv3
445
Christian Heimesdec813f2013-11-28 08:06:54 +0100446 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
447 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400448
Christian Heimes4c05b472013-11-23 15:58:30 +0100449 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400450 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100451 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100452 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400453 elif purpose == Purpose.CLIENT_AUTH:
454 # Prefer the server's ciphers by default so that we get stronger
455 # encryption
456 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
457
458 # Use single use keys in order to improve forward secrecy
459 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
460 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
461
462 # disallow ciphers with known vulnerabilities
463 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
464
Christian Heimes4c05b472013-11-23 15:58:30 +0100465 if cafile or capath or cadata:
466 context.load_verify_locations(cafile, capath, cadata)
467 elif context.verify_mode != CERT_NONE:
468 # no explicit cafile, capath or cadata but the verify mode is
469 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
470 # root CA certificates for the given purpose. This may fail silently.
471 context.load_default_certs(purpose)
472 return context
473
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500474def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100475 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100476 certfile=None, keyfile=None,
477 cafile=None, capath=None, cadata=None):
478 """Create a SSLContext object for Python stdlib modules
479
480 All Python stdlib modules shall use this function to create SSLContext
481 objects in order to keep common settings in one place. The configuration
482 is less restrict than create_default_context()'s to increase backward
483 compatibility.
484 """
485 if not isinstance(purpose, _ASN1Object):
486 raise TypeError(purpose)
487
488 context = SSLContext(protocol)
489 # SSLv2 considered harmful.
490 context.options |= OP_NO_SSLv2
Antoine Pitroue4eda4d2014-10-17 19:28:30 +0200491 # SSLv3 has problematic security and is only required for really old
492 # clients such as IE6 on Windows XP
493 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100494
495 if cert_reqs is not None:
496 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100497 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100498
499 if keyfile and not certfile:
500 raise ValueError("certfile must be specified")
501 if certfile or keyfile:
502 context.load_cert_chain(certfile, keyfile)
503
504 # load CA root certs
505 if cafile or capath or cadata:
506 context.load_verify_locations(cafile, capath, cadata)
507 elif context.verify_mode != CERT_NONE:
508 # no explicit cafile, capath or cadata but the verify mode is
509 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
510 # root CA certificates for the given purpose. This may fail silently.
511 context.load_default_certs(purpose)
512
513 return context
514
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500515# Used by http.client if no context is explicitly passed.
516_create_default_https_context = create_default_context
517
518
519# Backwards compatibility alias, even though it's not a public name.
520_create_stdlib_context = _create_unverified_context
521
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200522
523class SSLObject:
524 """This class implements an interface on top of a low-level SSL object as
525 implemented by OpenSSL. This object captures the state of an SSL connection
526 but does not provide any network IO itself. IO needs to be performed
527 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
528
529 This class does not have a public constructor. Instances are returned by
530 ``SSLContext.wrap_bio``. This class is typically used by framework authors
531 that want to implement asynchronous IO for SSL through memory buffers.
532
533 When compared to ``SSLSocket``, this object lacks the following features:
534
535 * Any form of network IO incluging methods such as ``recv`` and ``send``.
536 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
537 """
538
539 def __init__(self, sslobj, owner=None):
540 self._sslobj = sslobj
541 # Note: _sslobj takes a weak reference to owner
542 self._sslobj.owner = owner or self
543
544 @property
545 def context(self):
546 """The SSLContext that is currently in use."""
547 return self._sslobj.context
548
549 @context.setter
550 def context(self, ctx):
551 self._sslobj.context = ctx
552
553 @property
554 def server_side(self):
555 """Whether this is a server-side socket."""
556 return self._sslobj.server_side
557
558 @property
559 def server_hostname(self):
560 """The currently set server hostname (for SNI), or ``None`` if no
561 server hostame is set."""
562 return self._sslobj.server_hostname
563
Martin Panterf6b1d662016-03-28 00:22:09 +0000564 def read(self, len=1024, buffer=None):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200565 """Read up to 'len' bytes from the SSL object and return them.
566
567 If 'buffer' is provided, read into this buffer and return the number of
568 bytes read.
569 """
570 if buffer is not None:
571 v = self._sslobj.read(len, buffer)
572 else:
Martin Panterf6b1d662016-03-28 00:22:09 +0000573 v = self._sslobj.read(len)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200574 return v
575
576 def write(self, data):
577 """Write 'data' to the SSL object and return the number of bytes
578 written.
579
580 The 'data' argument must support the buffer interface.
581 """
582 return self._sslobj.write(data)
583
584 def getpeercert(self, binary_form=False):
585 """Returns a formatted version of the data in the certificate provided
586 by the other end of the SSL channel.
587
588 Return None if no certificate was provided, {} if a certificate was
589 provided, but not validated.
590 """
591 return self._sslobj.peer_certificate(binary_form)
592
593 def selected_npn_protocol(self):
594 """Return the currently selected NPN protocol as a string, or ``None``
595 if a next protocol was not negotiated or if NPN is not supported by one
596 of the peers."""
597 if _ssl.HAS_NPN:
598 return self._sslobj.selected_npn_protocol()
599
Benjamin Petersoncca27322015-01-23 16:35:37 -0500600 def selected_alpn_protocol(self):
601 """Return the currently selected ALPN protocol as a string, or ``None``
602 if a next protocol was not negotiated or if ALPN is not supported by one
603 of the peers."""
604 if _ssl.HAS_ALPN:
605 return self._sslobj.selected_alpn_protocol()
606
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200607 def cipher(self):
608 """Return the currently selected cipher as a 3-tuple ``(name,
609 ssl_version, secret_bits)``."""
610 return self._sslobj.cipher()
611
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600612 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500613 """Return a list of ciphers shared by the client during the handshake or
614 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600615 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600616 return self._sslobj.shared_ciphers()
617
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200618 def compression(self):
619 """Return the current compression algorithm in use, or ``None`` if
620 compression was not negotiated or not supported by one of the peers."""
621 return self._sslobj.compression()
622
623 def pending(self):
624 """Return the number of bytes that can be read immediately."""
625 return self._sslobj.pending()
626
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200627 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200628 """Start the SSL/TLS handshake."""
629 self._sslobj.do_handshake()
630 if self.context.check_hostname:
631 if not self.server_hostname:
632 raise ValueError("check_hostname needs server_hostname "
633 "argument")
634 match_hostname(self.getpeercert(), self.server_hostname)
635
636 def unwrap(self):
637 """Start the SSL shutdown handshake."""
638 return self._sslobj.shutdown()
639
640 def get_channel_binding(self, cb_type="tls-unique"):
641 """Get channel binding data for current connection. Raise ValueError
642 if the requested `cb_type` is not supported. Return bytes of the data
643 or None if the data is not available (e.g. before the handshake)."""
644 if cb_type not in CHANNEL_BINDING_TYPES:
645 raise ValueError("Unsupported channel binding type")
646 if cb_type != "tls-unique":
647 raise NotImplementedError(
648 "{0} channel binding type not implemented"
649 .format(cb_type))
650 return self._sslobj.tls_unique_cb()
651
652 def version(self):
653 """Return a string identifying the protocol version used by the
654 current SSL channel. """
655 return self._sslobj.version()
656
657
Antoine Pitrou152efa22010-05-16 18:19:27 +0000658class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000659 """This class implements a subtype of socket.socket that wraps
660 the underlying OS socket in an SSL context when necessary, and
661 provides read and write methods over that channel."""
662
Bill Janssen6e027db2007-11-15 22:23:56 +0000663 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000664 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000665 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
666 do_handshake_on_connect=True,
667 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100668 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000669 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000670 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000671
Antoine Pitrou152efa22010-05-16 18:19:27 +0000672 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100673 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000674 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000675 if server_side and not certfile:
676 raise ValueError("certfile must be specified for server-side "
677 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000678 if keyfile and not certfile:
679 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000680 if certfile and not keyfile:
681 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100682 self._context = SSLContext(ssl_version)
683 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000684 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100685 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000686 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100687 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100688 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100689 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000690 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100691 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000692 self.keyfile = keyfile
693 self.certfile = certfile
694 self.cert_reqs = cert_reqs
695 self.ssl_version = ssl_version
696 self.ca_certs = ca_certs
697 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100698 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
699 # mixed in.
700 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
701 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000702 if server_side and server_hostname:
703 raise ValueError("server_hostname can only be specified "
704 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100705 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600706 raise ValueError("check_hostname requires server_hostname")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000707 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000708 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000709 self.do_handshake_on_connect = do_handshake_on_connect
710 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000711 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000712 socket.__init__(self,
713 family=sock.family,
714 type=sock.type,
715 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000716 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000717 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000718 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000719 elif fileno is not None:
720 socket.__init__(self, fileno=fileno)
721 else:
722 socket.__init__(self, family=family, type=type, proto=proto)
723
Antoine Pitrou242db722013-05-01 20:52:07 +0200724 # See if we are connected
725 try:
726 self.getpeername()
727 except OSError as e:
728 if e.errno != errno.ENOTCONN:
729 raise
730 connected = False
731 else:
732 connected = True
733
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000734 self._closed = False
735 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000736 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000737 if connected:
738 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000739 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200740 sslobj = self._context._wrap_socket(self, server_side,
741 server_hostname)
742 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000743 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000744 timeout = self.gettimeout()
745 if timeout == 0.0:
746 # non-blocking
747 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000748 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000749
Christian Heimes1aa9a752013-12-02 02:41:19 +0100750 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000751 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100752 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200753
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100754 @property
755 def context(self):
756 return self._context
757
758 @context.setter
759 def context(self, ctx):
760 self._context = ctx
761 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000762
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000763 def dup(self):
764 raise NotImplemented("Can't dup() %s instances" %
765 self.__class__.__name__)
766
Bill Janssen6e027db2007-11-15 22:23:56 +0000767 def _checkClosed(self, msg=None):
768 # raise an exception here if you wish to check for spurious closes
769 pass
770
Antoine Pitrou242db722013-05-01 20:52:07 +0200771 def _check_connected(self):
772 if not self._connected:
773 # getpeername() will raise ENOTCONN if the socket is really
774 # not connected; note that we can be connected even without
775 # _connected being set, e.g. if connect() first returned
776 # EAGAIN.
777 self.getpeername()
778
Martin Panterf6b1d662016-03-28 00:22:09 +0000779 def read(self, len=1024, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000780 """Read up to LEN bytes and return them.
781 Return zero-length string on EOF."""
782
Bill Janssen6e027db2007-11-15 22:23:56 +0000783 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200784 if not self._sslobj:
785 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000786 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200787 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000788 except SSLError as x:
789 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000790 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000791 return 0
792 else:
793 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000794 else:
795 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000796
797 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000798 """Write DATA to the underlying SSL channel. Returns
799 number of bytes of DATA actually transmitted."""
800
Bill Janssen6e027db2007-11-15 22:23:56 +0000801 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200802 if not self._sslobj:
803 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000804 return self._sslobj.write(data)
805
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000807 """Returns a formatted version of the data in the
808 certificate provided by the other end of the SSL channel.
809 Return None if no certificate was provided, {} if a
810 certificate was provided, but not validated."""
811
Bill Janssen6e027db2007-11-15 22:23:56 +0000812 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200813 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200814 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100816 def selected_npn_protocol(self):
817 self._checkClosed()
818 if not self._sslobj or not _ssl.HAS_NPN:
819 return None
820 else:
821 return self._sslobj.selected_npn_protocol()
822
Benjamin Petersoncca27322015-01-23 16:35:37 -0500823 def selected_alpn_protocol(self):
824 self._checkClosed()
825 if not self._sslobj or not _ssl.HAS_ALPN:
826 return None
827 else:
828 return self._sslobj.selected_alpn_protocol()
829
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000830 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000831 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832 if not self._sslobj:
833 return None
834 else:
835 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000836
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600837 def shared_ciphers(self):
838 self._checkClosed()
839 if not self._sslobj:
840 return None
841 return self._sslobj.shared_ciphers()
842
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100843 def compression(self):
844 self._checkClosed()
845 if not self._sslobj:
846 return None
847 else:
848 return self._sslobj.compression()
849
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000850 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000851 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000852 if self._sslobj:
853 if flags != 0:
854 raise ValueError(
855 "non-zero flags not allowed in calls to send() on %s" %
856 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200857 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000858 else:
859 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000860
Antoine Pitroua468adc2010-09-14 14:43:44 +0000861 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000862 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000863 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000864 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000865 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000866 elif addr is None:
867 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000868 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000869 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000870
Nick Coghlan513886a2011-08-28 00:00:27 +1000871 def sendmsg(self, *args, **kwargs):
872 # Ensure programs don't send data unencrypted if they try to
873 # use this method.
874 raise NotImplementedError("sendmsg not allowed on instances of %s" %
875 self.__class__)
876
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000877 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000878 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000879 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000880 if flags != 0:
881 raise ValueError(
882 "non-zero flags not allowed in calls to sendall() on %s" %
883 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000884 amount = len(data)
885 count = 0
886 while (count < amount):
887 v = self.send(data[count:])
888 count += v
889 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000890 else:
891 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000892
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200893 def sendfile(self, file, offset=0, count=None):
894 """Send a file, possibly by using os.sendfile() if this is a
895 clear-text socket. Return the total number of bytes sent.
896 """
897 if self._sslobj is None:
898 # os.sendfile() works with plain sockets only
899 return super().sendfile(file, offset, count)
900 else:
901 return self._sendfile_use_send(file, offset, count)
902
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000903 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000904 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000905 if self._sslobj:
906 if flags != 0:
907 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000908 "non-zero flags not allowed in calls to recv() on %s" %
909 self.__class__)
910 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000911 else:
912 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000913
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000914 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000915 self._checkClosed()
916 if buffer and (nbytes is None):
917 nbytes = len(buffer)
918 elif nbytes is None:
919 nbytes = 1024
920 if self._sslobj:
921 if flags != 0:
922 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000923 "non-zero flags not allowed in calls to recv_into() on %s" %
924 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000925 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000926 else:
927 return socket.recv_into(self, buffer, nbytes, flags)
928
Antoine Pitroua468adc2010-09-14 14:43:44 +0000929 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000930 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000931 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000932 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000933 self.__class__)
934 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000935 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000936
Bill Janssen58afe4c2008-09-08 16:45:19 +0000937 def recvfrom_into(self, buffer, nbytes=None, flags=0):
938 self._checkClosed()
939 if self._sslobj:
940 raise ValueError("recvfrom_into not allowed on instances of %s" %
941 self.__class__)
942 else:
943 return socket.recvfrom_into(self, buffer, nbytes, flags)
944
Nick Coghlan513886a2011-08-28 00:00:27 +1000945 def recvmsg(self, *args, **kwargs):
946 raise NotImplementedError("recvmsg not allowed on instances of %s" %
947 self.__class__)
948
949 def recvmsg_into(self, *args, **kwargs):
950 raise NotImplementedError("recvmsg_into not allowed on instances of "
951 "%s" % self.__class__)
952
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000953 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000954 self._checkClosed()
955 if self._sslobj:
956 return self._sslobj.pending()
957 else:
958 return 0
959
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000960 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000961 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000962 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000963 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000964
Ezio Melottidc55e672010-01-18 09:15:14 +0000965 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000966 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200967 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +0000968 self._sslobj = None
969 return s
970 else:
971 raise ValueError("No SSL wrapper around " + str(self))
972
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000973 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000975 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000976
Bill Janssen48dc27c2007-12-05 03:38:10 +0000977 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000978 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200979 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000980 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000981 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000982 if timeout == 0.0 and block:
983 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000984 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000985 finally:
986 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000987
Antoine Pitroub4410db2011-05-18 18:51:06 +0200988 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000989 if self.server_side:
990 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000991 # Here we assume that the socket is client-side, and not
992 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000993 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000994 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200995 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
996 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000997 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200998 if connect_ex:
999 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001000 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001001 rc = None
1002 socket.connect(self, addr)
1003 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001004 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001005 if self.do_handshake_on_connect:
1006 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001007 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001008 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001009 self._sslobj = None
1010 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001011
1012 def connect(self, addr):
1013 """Connects to remote ADDR, and then wraps the connection in
1014 an SSL channel."""
1015 self._real_connect(addr, False)
1016
1017 def connect_ex(self, addr):
1018 """Connects to remote ADDR, and then wraps the connection in
1019 an SSL channel."""
1020 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001021
1022 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001023 """Accepts a new connection from a remote client, and returns
1024 a tuple containing that new connection wrapped with a server-side
1025 SSL channel, and the address of the remote client."""
1026
1027 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001028 newsock = self.context.wrap_socket(newsock,
1029 do_handshake_on_connect=self.do_handshake_on_connect,
1030 suppress_ragged_eofs=self.suppress_ragged_eofs,
1031 server_side=True)
1032 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001033
Antoine Pitroud6494802011-07-21 01:11:30 +02001034 def get_channel_binding(self, cb_type="tls-unique"):
1035 """Get channel binding data for current connection. Raise ValueError
1036 if the requested `cb_type` is not supported. Return bytes of the data
1037 or None if the data is not available (e.g. before the handshake).
1038 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001039 if self._sslobj is None:
1040 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001041 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001042
Antoine Pitrou47e40422014-09-04 21:00:10 +02001043 def version(self):
1044 """
1045 Return a string identifying the protocol version used by the
1046 current SSL channel, or None if there is no established channel.
1047 """
1048 if self._sslobj is None:
1049 return None
1050 return self._sslobj.version()
1051
Bill Janssen54cc54c2007-12-14 22:08:56 +00001052
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053def wrap_socket(sock, keyfile=None, certfile=None,
1054 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +00001055 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001056 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001057 suppress_ragged_eofs=True,
1058 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059
Bill Janssen6e027db2007-11-15 22:23:56 +00001060 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001062 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001063 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001064 suppress_ragged_eofs=suppress_ragged_eofs,
1065 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066
Thomas Woutersed03b412007-08-28 21:37:11 +00001067# some utility functions
1068
1069def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001070 """Return the time in seconds since the Epoch, given the timestring
1071 representing the "notBefore" or "notAfter" date from a certificate
1072 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001073
Antoine Pitrouc695c952014-04-28 20:57:36 +02001074 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1075
1076 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1077 UTC should be specified as GMT (see ASN1_TIME_print())
1078 """
1079 from time import strptime
1080 from calendar import timegm
1081
1082 months = (
1083 "Jan","Feb","Mar","Apr","May","Jun",
1084 "Jul","Aug","Sep","Oct","Nov","Dec"
1085 )
1086 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1087 try:
1088 month_number = months.index(cert_time[:3].title()) + 1
1089 except ValueError:
1090 raise ValueError('time data %r does not match '
1091 'format "%%b%s"' % (cert_time, time_format))
1092 else:
1093 # found valid month
1094 tt = strptime(cert_time[3:], time_format)
1095 # return an integer, the previous mktime()-based implementation
1096 # returned a float (fractional seconds are always zero here).
1097 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001098
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1100PEM_FOOTER = "-----END CERTIFICATE-----"
1101
1102def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103 """Takes a certificate in binary DER format and returns the
1104 PEM version of it as a string."""
1105
Bill Janssen6e027db2007-11-15 22:23:56 +00001106 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1107 return (PEM_HEADER + '\n' +
1108 textwrap.fill(f, 64) + '\n' +
1109 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
1111def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112 """Takes a certificate in ASCII PEM format and returns the
1113 DER-encoded version of it as a byte sequence"""
1114
1115 if not pem_cert_string.startswith(PEM_HEADER):
1116 raise ValueError("Invalid PEM encoding; must start with %s"
1117 % PEM_HEADER)
1118 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1119 raise ValueError("Invalid PEM encoding; must end with %s"
1120 % PEM_FOOTER)
1121 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001122 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Antoine Pitrou94a5b662014-04-16 18:56:28 +02001124def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125 """Retrieve the certificate from the server at the specified address,
1126 and return it as a PEM-encoded string.
1127 If 'ca_certs' is specified, validate the server cert against it.
1128 If 'ssl_version' is specified, use it in the connection attempt."""
1129
1130 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001131 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132 cert_reqs = CERT_REQUIRED
1133 else:
1134 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001135 context = _create_stdlib_context(ssl_version,
1136 cert_reqs=cert_reqs,
1137 cafile=ca_certs)
1138 with create_connection(addr) as sock:
1139 with context.wrap_socket(sock) as sslsock:
1140 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141 return DER_cert_to_PEM_cert(dercert)
1142
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001143def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001144 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')