blob: ab7a49b5763f85b1e28f47da56016fbe4d01eebd [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)
413 self.load_verify_locations(cadata=certs)
414 return certs
415
416 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
417 if not isinstance(purpose, _ASN1Object):
418 raise TypeError(purpose)
419 if sys.platform == "win32":
420 for storename in self._windows_cert_stores:
421 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400422 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100423
Antoine Pitrou152efa22010-05-16 18:19:27 +0000424
Christian Heimes4c05b472013-11-23 15:58:30 +0100425def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
426 capath=None, cadata=None):
427 """Create a SSLContext object with default settings.
428
429 NOTE: The protocol and settings may change anytime without prior
430 deprecation. The values represent a fair balance between maximum
431 compatibility and security.
432 """
433 if not isinstance(purpose, _ASN1Object):
434 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400435
436 context = SSLContext(PROTOCOL_SSLv23)
437
Christian Heimes4c05b472013-11-23 15:58:30 +0100438 # SSLv2 considered harmful.
439 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400440
441 # SSLv3 has problematic security and is only required for really old
442 # clients such as IE6 on Windows XP
443 context.options |= OP_NO_SSLv3
444
Christian Heimesdec813f2013-11-28 08:06:54 +0100445 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
446 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400447
Christian Heimes4c05b472013-11-23 15:58:30 +0100448 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400449 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100450 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100451 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400452 elif purpose == Purpose.CLIENT_AUTH:
453 # Prefer the server's ciphers by default so that we get stronger
454 # encryption
455 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
456
457 # Use single use keys in order to improve forward secrecy
458 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
459 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
460
461 # disallow ciphers with known vulnerabilities
462 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
463
Christian Heimes4c05b472013-11-23 15:58:30 +0100464 if cafile or capath or cadata:
465 context.load_verify_locations(cafile, capath, cadata)
466 elif context.verify_mode != CERT_NONE:
467 # no explicit cafile, capath or cadata but the verify mode is
468 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
469 # root CA certificates for the given purpose. This may fail silently.
470 context.load_default_certs(purpose)
471 return context
472
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500473def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100474 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100475 certfile=None, keyfile=None,
476 cafile=None, capath=None, cadata=None):
477 """Create a SSLContext object for Python stdlib modules
478
479 All Python stdlib modules shall use this function to create SSLContext
480 objects in order to keep common settings in one place. The configuration
481 is less restrict than create_default_context()'s to increase backward
482 compatibility.
483 """
484 if not isinstance(purpose, _ASN1Object):
485 raise TypeError(purpose)
486
487 context = SSLContext(protocol)
488 # SSLv2 considered harmful.
489 context.options |= OP_NO_SSLv2
Antoine Pitroue4eda4d2014-10-17 19:28:30 +0200490 # SSLv3 has problematic security and is only required for really old
491 # clients such as IE6 on Windows XP
492 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100493
494 if cert_reqs is not None:
495 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100496 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100497
498 if keyfile and not certfile:
499 raise ValueError("certfile must be specified")
500 if certfile or keyfile:
501 context.load_cert_chain(certfile, keyfile)
502
503 # load CA root certs
504 if cafile or capath or cadata:
505 context.load_verify_locations(cafile, capath, cadata)
506 elif context.verify_mode != CERT_NONE:
507 # no explicit cafile, capath or cadata but the verify mode is
508 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
509 # root CA certificates for the given purpose. This may fail silently.
510 context.load_default_certs(purpose)
511
512 return context
513
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500514# Used by http.client if no context is explicitly passed.
515_create_default_https_context = create_default_context
516
517
518# Backwards compatibility alias, even though it's not a public name.
519_create_stdlib_context = _create_unverified_context
520
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200521
522class SSLObject:
523 """This class implements an interface on top of a low-level SSL object as
524 implemented by OpenSSL. This object captures the state of an SSL connection
525 but does not provide any network IO itself. IO needs to be performed
526 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
527
528 This class does not have a public constructor. Instances are returned by
529 ``SSLContext.wrap_bio``. This class is typically used by framework authors
530 that want to implement asynchronous IO for SSL through memory buffers.
531
532 When compared to ``SSLSocket``, this object lacks the following features:
533
534 * Any form of network IO incluging methods such as ``recv`` and ``send``.
535 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
536 """
537
538 def __init__(self, sslobj, owner=None):
539 self._sslobj = sslobj
540 # Note: _sslobj takes a weak reference to owner
541 self._sslobj.owner = owner or self
542
543 @property
544 def context(self):
545 """The SSLContext that is currently in use."""
546 return self._sslobj.context
547
548 @context.setter
549 def context(self, ctx):
550 self._sslobj.context = ctx
551
552 @property
553 def server_side(self):
554 """Whether this is a server-side socket."""
555 return self._sslobj.server_side
556
557 @property
558 def server_hostname(self):
559 """The currently set server hostname (for SNI), or ``None`` if no
560 server hostame is set."""
561 return self._sslobj.server_hostname
562
563 def read(self, len=0, buffer=None):
564 """Read up to 'len' bytes from the SSL object and return them.
565
566 If 'buffer' is provided, read into this buffer and return the number of
567 bytes read.
568 """
569 if buffer is not None:
570 v = self._sslobj.read(len, buffer)
571 else:
572 v = self._sslobj.read(len or 1024)
573 return v
574
575 def write(self, data):
576 """Write 'data' to the SSL object and return the number of bytes
577 written.
578
579 The 'data' argument must support the buffer interface.
580 """
581 return self._sslobj.write(data)
582
583 def getpeercert(self, binary_form=False):
584 """Returns a formatted version of the data in the certificate provided
585 by the other end of the SSL channel.
586
587 Return None if no certificate was provided, {} if a certificate was
588 provided, but not validated.
589 """
590 return self._sslobj.peer_certificate(binary_form)
591
592 def selected_npn_protocol(self):
593 """Return the currently selected NPN protocol as a string, or ``None``
594 if a next protocol was not negotiated or if NPN is not supported by one
595 of the peers."""
596 if _ssl.HAS_NPN:
597 return self._sslobj.selected_npn_protocol()
598
Benjamin Petersoncca27322015-01-23 16:35:37 -0500599 def selected_alpn_protocol(self):
600 """Return the currently selected ALPN protocol as a string, or ``None``
601 if a next protocol was not negotiated or if ALPN is not supported by one
602 of the peers."""
603 if _ssl.HAS_ALPN:
604 return self._sslobj.selected_alpn_protocol()
605
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200606 def cipher(self):
607 """Return the currently selected cipher as a 3-tuple ``(name,
608 ssl_version, secret_bits)``."""
609 return self._sslobj.cipher()
610
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600611 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500612 """Return a list of ciphers shared by the client during the handshake or
613 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600614 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600615 return self._sslobj.shared_ciphers()
616
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200617 def compression(self):
618 """Return the current compression algorithm in use, or ``None`` if
619 compression was not negotiated or not supported by one of the peers."""
620 return self._sslobj.compression()
621
622 def pending(self):
623 """Return the number of bytes that can be read immediately."""
624 return self._sslobj.pending()
625
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200626 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200627 """Start the SSL/TLS handshake."""
628 self._sslobj.do_handshake()
629 if self.context.check_hostname:
630 if not self.server_hostname:
631 raise ValueError("check_hostname needs server_hostname "
632 "argument")
633 match_hostname(self.getpeercert(), self.server_hostname)
634
635 def unwrap(self):
636 """Start the SSL shutdown handshake."""
637 return self._sslobj.shutdown()
638
639 def get_channel_binding(self, cb_type="tls-unique"):
640 """Get channel binding data for current connection. Raise ValueError
641 if the requested `cb_type` is not supported. Return bytes of the data
642 or None if the data is not available (e.g. before the handshake)."""
643 if cb_type not in CHANNEL_BINDING_TYPES:
644 raise ValueError("Unsupported channel binding type")
645 if cb_type != "tls-unique":
646 raise NotImplementedError(
647 "{0} channel binding type not implemented"
648 .format(cb_type))
649 return self._sslobj.tls_unique_cb()
650
651 def version(self):
652 """Return a string identifying the protocol version used by the
653 current SSL channel. """
654 return self._sslobj.version()
655
656
Antoine Pitrou152efa22010-05-16 18:19:27 +0000657class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000658 """This class implements a subtype of socket.socket that wraps
659 the underlying OS socket in an SSL context when necessary, and
660 provides read and write methods over that channel."""
661
Bill Janssen6e027db2007-11-15 22:23:56 +0000662 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000663 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000664 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
665 do_handshake_on_connect=True,
666 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100667 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000668 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000669 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000670
Antoine Pitrou152efa22010-05-16 18:19:27 +0000671 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100672 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000673 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000674 if server_side and not certfile:
675 raise ValueError("certfile must be specified for server-side "
676 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000677 if keyfile and not certfile:
678 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000679 if certfile and not keyfile:
680 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100681 self._context = SSLContext(ssl_version)
682 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000683 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100684 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000685 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100686 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100687 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100688 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000689 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100690 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000691 self.keyfile = keyfile
692 self.certfile = certfile
693 self.cert_reqs = cert_reqs
694 self.ssl_version = ssl_version
695 self.ca_certs = ca_certs
696 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100697 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
698 # mixed in.
699 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
700 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000701 if server_side and server_hostname:
702 raise ValueError("server_hostname can only be specified "
703 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100704 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600705 raise ValueError("check_hostname requires server_hostname")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000706 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000707 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000708 self.do_handshake_on_connect = do_handshake_on_connect
709 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000710 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000711 socket.__init__(self,
712 family=sock.family,
713 type=sock.type,
714 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000715 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000716 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000717 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000718 elif fileno is not None:
719 socket.__init__(self, fileno=fileno)
720 else:
721 socket.__init__(self, family=family, type=type, proto=proto)
722
Antoine Pitrou242db722013-05-01 20:52:07 +0200723 # See if we are connected
724 try:
725 self.getpeername()
726 except OSError as e:
727 if e.errno != errno.ENOTCONN:
728 raise
729 connected = False
730 else:
731 connected = True
732
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000733 self._closed = False
734 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000735 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000736 if connected:
737 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000738 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200739 sslobj = self._context._wrap_socket(self, server_side,
740 server_hostname)
741 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000742 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000743 timeout = self.gettimeout()
744 if timeout == 0.0:
745 # non-blocking
746 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000747 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000748
Christian Heimes1aa9a752013-12-02 02:41:19 +0100749 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000750 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100751 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200752
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100753 @property
754 def context(self):
755 return self._context
756
757 @context.setter
758 def context(self, ctx):
759 self._context = ctx
760 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000761
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000762 def dup(self):
763 raise NotImplemented("Can't dup() %s instances" %
764 self.__class__.__name__)
765
Bill Janssen6e027db2007-11-15 22:23:56 +0000766 def _checkClosed(self, msg=None):
767 # raise an exception here if you wish to check for spurious closes
768 pass
769
Antoine Pitrou242db722013-05-01 20:52:07 +0200770 def _check_connected(self):
771 if not self._connected:
772 # getpeername() will raise ENOTCONN if the socket is really
773 # not connected; note that we can be connected even without
774 # _connected being set, e.g. if connect() first returned
775 # EAGAIN.
776 self.getpeername()
777
Bill Janssen54cc54c2007-12-14 22:08:56 +0000778 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000779 """Read up to LEN bytes and return them.
780 Return zero-length string on EOF."""
781
Bill Janssen6e027db2007-11-15 22:23:56 +0000782 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200783 if not self._sslobj:
784 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000785 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200786 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000787 except SSLError as x:
788 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000789 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000790 return 0
791 else:
792 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000793 else:
794 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000795
796 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000797 """Write DATA to the underlying SSL channel. Returns
798 number of bytes of DATA actually transmitted."""
799
Bill Janssen6e027db2007-11-15 22:23:56 +0000800 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200801 if not self._sslobj:
802 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000803 return self._sslobj.write(data)
804
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000806 """Returns a formatted version of the data in the
807 certificate provided by the other end of the SSL channel.
808 Return None if no certificate was provided, {} if a
809 certificate was provided, but not validated."""
810
Bill Janssen6e027db2007-11-15 22:23:56 +0000811 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200812 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200813 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100815 def selected_npn_protocol(self):
816 self._checkClosed()
817 if not self._sslobj or not _ssl.HAS_NPN:
818 return None
819 else:
820 return self._sslobj.selected_npn_protocol()
821
Benjamin Petersoncca27322015-01-23 16:35:37 -0500822 def selected_alpn_protocol(self):
823 self._checkClosed()
824 if not self._sslobj or not _ssl.HAS_ALPN:
825 return None
826 else:
827 return self._sslobj.selected_alpn_protocol()
828
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000829 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000830 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831 if not self._sslobj:
832 return None
833 else:
834 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000835
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600836 def shared_ciphers(self):
837 self._checkClosed()
838 if not self._sslobj:
839 return None
840 return self._sslobj.shared_ciphers()
841
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100842 def compression(self):
843 self._checkClosed()
844 if not self._sslobj:
845 return None
846 else:
847 return self._sslobj.compression()
848
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000849 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000850 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000851 if self._sslobj:
852 if flags != 0:
853 raise ValueError(
854 "non-zero flags not allowed in calls to send() on %s" %
855 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200856 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000857 else:
858 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000859
Antoine Pitroua468adc2010-09-14 14:43:44 +0000860 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000861 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000862 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000863 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000864 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000865 elif addr is None:
866 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000867 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000868 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000869
Nick Coghlan513886a2011-08-28 00:00:27 +1000870 def sendmsg(self, *args, **kwargs):
871 # Ensure programs don't send data unencrypted if they try to
872 # use this method.
873 raise NotImplementedError("sendmsg not allowed on instances of %s" %
874 self.__class__)
875
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000876 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000877 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000878 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000879 if flags != 0:
880 raise ValueError(
881 "non-zero flags not allowed in calls to sendall() on %s" %
882 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000883 amount = len(data)
884 count = 0
885 while (count < amount):
886 v = self.send(data[count:])
887 count += v
888 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000889 else:
890 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000891
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200892 def sendfile(self, file, offset=0, count=None):
893 """Send a file, possibly by using os.sendfile() if this is a
894 clear-text socket. Return the total number of bytes sent.
895 """
896 if self._sslobj is None:
897 # os.sendfile() works with plain sockets only
898 return super().sendfile(file, offset, count)
899 else:
900 return self._sendfile_use_send(file, offset, count)
901
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000902 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000903 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000904 if self._sslobj:
905 if flags != 0:
906 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000907 "non-zero flags not allowed in calls to recv() on %s" %
908 self.__class__)
909 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000910 else:
911 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000912
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000913 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000914 self._checkClosed()
915 if buffer and (nbytes is None):
916 nbytes = len(buffer)
917 elif nbytes is None:
918 nbytes = 1024
919 if self._sslobj:
920 if flags != 0:
921 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000922 "non-zero flags not allowed in calls to recv_into() on %s" %
923 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000924 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000925 else:
926 return socket.recv_into(self, buffer, nbytes, flags)
927
Antoine Pitroua468adc2010-09-14 14:43:44 +0000928 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000929 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000930 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000931 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000932 self.__class__)
933 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000934 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000935
Bill Janssen58afe4c2008-09-08 16:45:19 +0000936 def recvfrom_into(self, buffer, nbytes=None, flags=0):
937 self._checkClosed()
938 if self._sslobj:
939 raise ValueError("recvfrom_into not allowed on instances of %s" %
940 self.__class__)
941 else:
942 return socket.recvfrom_into(self, buffer, nbytes, flags)
943
Nick Coghlan513886a2011-08-28 00:00:27 +1000944 def recvmsg(self, *args, **kwargs):
945 raise NotImplementedError("recvmsg not allowed on instances of %s" %
946 self.__class__)
947
948 def recvmsg_into(self, *args, **kwargs):
949 raise NotImplementedError("recvmsg_into not allowed on instances of "
950 "%s" % self.__class__)
951
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000952 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000953 self._checkClosed()
954 if self._sslobj:
955 return self._sslobj.pending()
956 else:
957 return 0
958
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000959 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000960 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000962 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000963
Ezio Melottidc55e672010-01-18 09:15:14 +0000964 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000965 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200966 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +0000967 self._sslobj = None
968 return s
969 else:
970 raise ValueError("No SSL wrapper around " + str(self))
971
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000972 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000974 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000975
Bill Janssen48dc27c2007-12-05 03:38:10 +0000976 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000977 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200978 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000979 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000980 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000981 if timeout == 0.0 and block:
982 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000983 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000984 finally:
985 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000986
Antoine Pitroub4410db2011-05-18 18:51:06 +0200987 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000988 if self.server_side:
989 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000990 # Here we assume that the socket is client-side, and not
991 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000992 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000993 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200994 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
995 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000996 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200997 if connect_ex:
998 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000999 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001000 rc = None
1001 socket.connect(self, addr)
1002 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001003 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001004 if self.do_handshake_on_connect:
1005 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001006 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001007 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001008 self._sslobj = None
1009 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001010
1011 def connect(self, addr):
1012 """Connects to remote ADDR, and then wraps the connection in
1013 an SSL channel."""
1014 self._real_connect(addr, False)
1015
1016 def connect_ex(self, addr):
1017 """Connects to remote ADDR, and then wraps the connection in
1018 an SSL channel."""
1019 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001020
1021 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001022 """Accepts a new connection from a remote client, and returns
1023 a tuple containing that new connection wrapped with a server-side
1024 SSL channel, and the address of the remote client."""
1025
1026 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001027 newsock = self.context.wrap_socket(newsock,
1028 do_handshake_on_connect=self.do_handshake_on_connect,
1029 suppress_ragged_eofs=self.suppress_ragged_eofs,
1030 server_side=True)
1031 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032
Antoine Pitroud6494802011-07-21 01:11:30 +02001033 def get_channel_binding(self, cb_type="tls-unique"):
1034 """Get channel binding data for current connection. Raise ValueError
1035 if the requested `cb_type` is not supported. Return bytes of the data
1036 or None if the data is not available (e.g. before the handshake).
1037 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001038 if self._sslobj is None:
1039 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001040 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001041
Antoine Pitrou47e40422014-09-04 21:00:10 +02001042 def version(self):
1043 """
1044 Return a string identifying the protocol version used by the
1045 current SSL channel, or None if there is no established channel.
1046 """
1047 if self._sslobj is None:
1048 return None
1049 return self._sslobj.version()
1050
Bill Janssen54cc54c2007-12-14 22:08:56 +00001051
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052def wrap_socket(sock, keyfile=None, certfile=None,
1053 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +00001054 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001055 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001056 suppress_ragged_eofs=True,
1057 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Bill Janssen6e027db2007-11-15 22:23:56 +00001059 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001061 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001062 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001063 suppress_ragged_eofs=suppress_ragged_eofs,
1064 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065
Thomas Woutersed03b412007-08-28 21:37:11 +00001066# some utility functions
1067
1068def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001069 """Return the time in seconds since the Epoch, given the timestring
1070 representing the "notBefore" or "notAfter" date from a certificate
1071 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001072
Antoine Pitrouc695c952014-04-28 20:57:36 +02001073 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1074
1075 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1076 UTC should be specified as GMT (see ASN1_TIME_print())
1077 """
1078 from time import strptime
1079 from calendar import timegm
1080
1081 months = (
1082 "Jan","Feb","Mar","Apr","May","Jun",
1083 "Jul","Aug","Sep","Oct","Nov","Dec"
1084 )
1085 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1086 try:
1087 month_number = months.index(cert_time[:3].title()) + 1
1088 except ValueError:
1089 raise ValueError('time data %r does not match '
1090 'format "%%b%s"' % (cert_time, time_format))
1091 else:
1092 # found valid month
1093 tt = strptime(cert_time[3:], time_format)
1094 # return an integer, the previous mktime()-based implementation
1095 # returned a float (fractional seconds are always zero here).
1096 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001097
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1099PEM_FOOTER = "-----END CERTIFICATE-----"
1100
1101def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102 """Takes a certificate in binary DER format and returns the
1103 PEM version of it as a string."""
1104
Bill Janssen6e027db2007-11-15 22:23:56 +00001105 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1106 return (PEM_HEADER + '\n' +
1107 textwrap.fill(f, 64) + '\n' +
1108 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
1110def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111 """Takes a certificate in ASCII PEM format and returns the
1112 DER-encoded version of it as a byte sequence"""
1113
1114 if not pem_cert_string.startswith(PEM_HEADER):
1115 raise ValueError("Invalid PEM encoding; must start with %s"
1116 % PEM_HEADER)
1117 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1118 raise ValueError("Invalid PEM encoding; must end with %s"
1119 % PEM_FOOTER)
1120 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001121 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
Antoine Pitrou94a5b662014-04-16 18:56:28 +02001123def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124 """Retrieve the certificate from the server at the specified address,
1125 and return it as a PEM-encoded string.
1126 If 'ca_certs' is specified, validate the server cert against it.
1127 If 'ssl_version' is specified, use it in the connection attempt."""
1128
1129 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001130 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131 cert_reqs = CERT_REQUIRED
1132 else:
1133 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001134 context = _create_stdlib_context(ssl_version,
1135 cert_reqs=cert_reqs,
1136 cafile=ca_certs)
1137 with create_connection(addr) as sock:
1138 with context.wrap_socket(sock) as sslsock:
1139 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140 return DER_cert_to_PEM_cert(dercert)
1141
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001142def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001143 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')