blob: 56bc38e5e1818dadd3b60dbe0228f8b379868c06 [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 Heimes22587792013-11-21 23:56:13 +0100107from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
108 VERIFY_X509_STRICT)
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100109from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100110from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
111try:
112 from _ssl import RAND_egd
113except ImportError:
114 # LibreSSL does not provide RAND_egd
115 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100116
117def _import_symbols(prefix):
118 for n in dir(_ssl):
119 if n.startswith(prefix):
120 globals()[n] = getattr(_ssl, n)
121
122_import_symbols('OP_')
123_import_symbols('ALERT_DESCRIPTION_')
124_import_symbols('SSL_ERROR_')
125
Benjamin Petersoncca27322015-01-23 16:35:37 -0500126from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100127
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200128from _ssl import _OPENSSL_API_VERSION
129
Antoine Pitrou172f0252014-04-18 20:33:08 +0200130_SSLMethod = _IntEnum('_SSLMethod',
131 {name: value for name, value in vars(_ssl).items()
132 if name.startswith('PROTOCOL_')})
133globals().update(_SSLMethod.__members__)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100134
Antoine Pitrou172f0252014-04-18 20:33:08 +0200135_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
136
Victor Stinner3de49192011-05-09 00:42:58 +0200137try:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100138 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Antoine Pitrou172f0252014-04-18 20:33:08 +0200139except NameError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100140 _SSLv2_IF_EXISTS = None
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100141
Christian Heimes46bebee2013-06-09 19:03:31 +0200142if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100143 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200144
Antoine Pitrou15399c32011-04-28 19:23:55 +0200145from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100146from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000147import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000148import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000149
Andrew Svetlov0832af62012-12-18 23:10:48 +0200150
151socket_error = OSError # keep that public name in module namespace
152
Antoine Pitroud6494802011-07-21 01:11:30 +0200153if _ssl.HAS_TLS_UNIQUE:
154 CHANNEL_BINDING_TYPES = ['tls-unique']
155else:
156 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000157
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100158# Disable weak or insecure ciphers by default
159# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400160# Enable a better set of ciphers by default
161# This list has been explicitly chosen to:
162# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
163# * Prefer ECDHE over DHE for better performance
164# * Prefer any AES-GCM over any AES-CBC for better performance and security
165# * Then Use HIGH cipher suites as a fallback
166# * Then Use 3DES as fallback which is secure but slow
167# * Finally use RC4 as a fallback which is problematic but needed for
168# compatibility some times.
169# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
170# reasons
171_DEFAULT_CIPHERS = (
172 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
173 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
174 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
175)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100176
Donald Stufft6a2ba942014-03-23 19:05:28 -0400177# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400178# This list has been explicitly chosen to:
179# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
180# * Prefer ECDHE over DHE for better performance
181# * Prefer any AES-GCM over any AES-CBC for better performance and security
182# * Then Use HIGH cipher suites as a fallback
183# * Then Use 3DES as fallback which is secure but slow
184# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
185# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400186_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400187 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
188 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
189 '!eNULL:!MD5:!DSS:!RC4'
190)
Christian Heimes4c05b472013-11-23 15:58:30 +0100191
Thomas Woutersed03b412007-08-28 21:37:11 +0000192
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000193class CertificateError(ValueError):
194 pass
195
196
Georg Brandl72c98d32013-10-27 07:16:53 +0100197def _dnsname_match(dn, hostname, max_wildcards=1):
198 """Matching according to RFC 6125, section 6.4.3
199
200 http://tools.ietf.org/html/rfc6125#section-6.4.3
201 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000202 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100203 if not dn:
204 return False
205
206 leftmost, *remainder = dn.split(r'.')
207
208 wildcards = leftmost.count('*')
209 if wildcards > max_wildcards:
210 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300211 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100212 # policy among SSL implementations showed it to be a
213 # reasonable choice.
214 raise CertificateError(
215 "too many wildcards in certificate DNS name: " + repr(dn))
216
217 # speed up common case w/o wildcards
218 if not wildcards:
219 return dn.lower() == hostname.lower()
220
221 # RFC 6125, section 6.4.3, subitem 1.
222 # The client SHOULD NOT attempt to match a presented identifier in which
223 # the wildcard character comprises a label other than the left-most label.
224 if leftmost == '*':
225 # When '*' is a fragment by itself, it matches a non-empty dotless
226 # fragment.
227 pats.append('[^.]+')
228 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
229 # RFC 6125, section 6.4.3, subitem 3.
230 # The client SHOULD NOT attempt to match a presented identifier
231 # where the wildcard character is embedded within an A-label or
232 # U-label of an internationalized domain name.
233 pats.append(re.escape(leftmost))
234 else:
235 # Otherwise, '*' matches any dotless string, e.g. www*
236 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
237
238 # add the remaining fragments, ignore any wildcards
239 for frag in remainder:
240 pats.append(re.escape(frag))
241
242 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
243 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000244
245
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100246def _ipaddress_match(ipname, host_ip):
247 """Exact matching of IP addresses.
248
249 RFC 6125 explicitly doesn't define an algorithm for this
250 (section 1.7.2 - "Out of Scope").
251 """
252 # OpenSSL may add a trailing newline to a subjectAltName's IP address
253 ip = ipaddress.ip_address(ipname.rstrip())
254 return ip == host_ip
255
256
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000257def match_hostname(cert, hostname):
258 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100259 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
260 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000261
262 CertificateError is raised on failure. On success, the function
263 returns nothing.
264 """
265 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100266 raise ValueError("empty or no certificate, match_hostname needs a "
267 "SSL socket or SSL context with either "
268 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100269 try:
270 host_ip = ipaddress.ip_address(hostname)
271 except ValueError:
272 # Not an IP address (common case)
273 host_ip = None
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000274 dnsnames = []
275 san = cert.get('subjectAltName', ())
276 for key, value in san:
277 if key == 'DNS':
Antoine Pitrouc481bfb2015-02-15 18:12:20 +0100278 if host_ip is None and _dnsname_match(value, hostname):
279 return
280 dnsnames.append(value)
281 elif key == 'IP Address':
282 if host_ip is not None and _ipaddress_match(value, host_ip):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000283 return
284 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200285 if not dnsnames:
286 # The subject is only checked when there is no dNSName entry
287 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000288 for sub in cert.get('subject', ()):
289 for key, value in sub:
290 # XXX according to RFC 2818, the most specific Common Name
291 # must be used.
292 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100293 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000294 return
295 dnsnames.append(value)
296 if len(dnsnames) > 1:
297 raise CertificateError("hostname %r "
298 "doesn't match either of %s"
299 % (hostname, ', '.join(map(repr, dnsnames))))
300 elif len(dnsnames) == 1:
301 raise CertificateError("hostname %r "
302 "doesn't match %r"
303 % (hostname, dnsnames[0]))
304 else:
305 raise CertificateError("no appropriate commonName or "
306 "subjectAltName fields were found")
307
308
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100309DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200310 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
311 "openssl_capath")
312
313def get_default_verify_paths():
314 """Return paths to default cafile and capath.
315 """
316 parts = _ssl.get_default_verify_paths()
317
318 # environment vars shadow paths
319 cafile = os.environ.get(parts[0], parts[1])
320 capath = os.environ.get(parts[2], parts[3])
321
322 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
323 capath if os.path.isdir(capath) else None,
324 *parts)
325
326
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100327class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
328 """ASN.1 object identifier lookup
329 """
330 __slots__ = ()
331
332 def __new__(cls, oid):
333 return super().__new__(cls, *_txt2obj(oid, name=False))
334
335 @classmethod
336 def fromnid(cls, nid):
337 """Create _ASN1Object from OpenSSL numeric ID
338 """
339 return super().__new__(cls, *_nid2obj(nid))
340
341 @classmethod
342 def fromname(cls, name):
343 """Create _ASN1Object from short name, long name or OID
344 """
345 return super().__new__(cls, *_txt2obj(name, name=True))
346
347
Christian Heimes72d28502013-11-23 13:56:58 +0100348class Purpose(_ASN1Object, _Enum):
349 """SSLContext purpose flags with X509v3 Extended Key Usage objects
350 """
351 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
352 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
353
354
Antoine Pitrou152efa22010-05-16 18:19:27 +0000355class SSLContext(_SSLContext):
356 """An SSLContext holds various SSL-related configuration options and
357 data, such as certificates and possibly a private key."""
358
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100359 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100360 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000361
362 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100363 self = _SSLContext.__new__(cls, protocol)
364 if protocol != _SSLv2_IF_EXISTS:
365 self.set_ciphers(_DEFAULT_CIPHERS)
366 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000367
368 def __init__(self, protocol):
369 self.protocol = protocol
370
371 def wrap_socket(self, sock, server_side=False,
372 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000373 suppress_ragged_eofs=True,
374 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375 return SSLSocket(sock=sock, server_side=server_side,
376 do_handshake_on_connect=do_handshake_on_connect,
377 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000378 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000379 _context=self)
380
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200381 def wrap_bio(self, incoming, outgoing, server_side=False,
382 server_hostname=None):
383 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
384 server_hostname=server_hostname)
385 return SSLObject(sslobj)
386
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100387 def set_npn_protocols(self, npn_protocols):
388 protos = bytearray()
389 for protocol in npn_protocols:
390 b = bytes(protocol, 'ascii')
391 if len(b) == 0 or len(b) > 255:
392 raise SSLError('NPN protocols must be 1 to 255 in length')
393 protos.append(len(b))
394 protos.extend(b)
395
396 self._set_npn_protocols(protos)
397
Benjamin Petersoncca27322015-01-23 16:35:37 -0500398 def set_alpn_protocols(self, alpn_protocols):
399 protos = bytearray()
400 for protocol in alpn_protocols:
401 b = bytes(protocol, 'ascii')
402 if len(b) == 0 or len(b) > 255:
403 raise SSLError('ALPN protocols must be 1 to 255 in length')
404 protos.append(len(b))
405 protos.extend(b)
406
407 self._set_alpn_protocols(protos)
408
Christian Heimes72d28502013-11-23 13:56:58 +0100409 def _load_windows_store_certs(self, storename, purpose):
410 certs = bytearray()
411 for cert, encoding, trust in enum_certificates(storename):
412 # CA certs are never PKCS#7 encoded
413 if encoding == "x509_asn":
414 if trust is True or purpose.oid in trust:
415 certs.extend(cert)
416 self.load_verify_locations(cadata=certs)
417 return certs
418
419 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
420 if not isinstance(purpose, _ASN1Object):
421 raise TypeError(purpose)
422 if sys.platform == "win32":
423 for storename in self._windows_cert_stores:
424 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400425 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100426
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427
Christian Heimes4c05b472013-11-23 15:58:30 +0100428def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
429 capath=None, cadata=None):
430 """Create a SSLContext object with default settings.
431
432 NOTE: The protocol and settings may change anytime without prior
433 deprecation. The values represent a fair balance between maximum
434 compatibility and security.
435 """
436 if not isinstance(purpose, _ASN1Object):
437 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400438
439 context = SSLContext(PROTOCOL_SSLv23)
440
Christian Heimes4c05b472013-11-23 15:58:30 +0100441 # SSLv2 considered harmful.
442 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400443
444 # SSLv3 has problematic security and is only required for really old
445 # clients such as IE6 on Windows XP
446 context.options |= OP_NO_SSLv3
447
Christian Heimesdec813f2013-11-28 08:06:54 +0100448 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
449 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400450
Christian Heimes4c05b472013-11-23 15:58:30 +0100451 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400452 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100453 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100454 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400455 elif purpose == Purpose.CLIENT_AUTH:
456 # Prefer the server's ciphers by default so that we get stronger
457 # encryption
458 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
459
460 # Use single use keys in order to improve forward secrecy
461 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
462 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
463
464 # disallow ciphers with known vulnerabilities
465 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
466
Christian Heimes4c05b472013-11-23 15:58:30 +0100467 if cafile or capath or cadata:
468 context.load_verify_locations(cafile, capath, cadata)
469 elif context.verify_mode != CERT_NONE:
470 # no explicit cafile, capath or cadata but the verify mode is
471 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
472 # root CA certificates for the given purpose. This may fail silently.
473 context.load_default_certs(purpose)
474 return context
475
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500476def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100477 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100478 certfile=None, keyfile=None,
479 cafile=None, capath=None, cadata=None):
480 """Create a SSLContext object for Python stdlib modules
481
482 All Python stdlib modules shall use this function to create SSLContext
483 objects in order to keep common settings in one place. The configuration
484 is less restrict than create_default_context()'s to increase backward
485 compatibility.
486 """
487 if not isinstance(purpose, _ASN1Object):
488 raise TypeError(purpose)
489
490 context = SSLContext(protocol)
491 # SSLv2 considered harmful.
492 context.options |= OP_NO_SSLv2
Antoine Pitroue4eda4d2014-10-17 19:28:30 +0200493 # SSLv3 has problematic security and is only required for really old
494 # clients such as IE6 on Windows XP
495 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100496
497 if cert_reqs is not None:
498 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100499 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100500
501 if keyfile and not certfile:
502 raise ValueError("certfile must be specified")
503 if certfile or keyfile:
504 context.load_cert_chain(certfile, keyfile)
505
506 # load CA root certs
507 if cafile or capath or cadata:
508 context.load_verify_locations(cafile, capath, cadata)
509 elif context.verify_mode != CERT_NONE:
510 # no explicit cafile, capath or cadata but the verify mode is
511 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
512 # root CA certificates for the given purpose. This may fail silently.
513 context.load_default_certs(purpose)
514
515 return context
516
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500517# Used by http.client if no context is explicitly passed.
518_create_default_https_context = create_default_context
519
520
521# Backwards compatibility alias, even though it's not a public name.
522_create_stdlib_context = _create_unverified_context
523
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200524
525class SSLObject:
526 """This class implements an interface on top of a low-level SSL object as
527 implemented by OpenSSL. This object captures the state of an SSL connection
528 but does not provide any network IO itself. IO needs to be performed
529 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
530
531 This class does not have a public constructor. Instances are returned by
532 ``SSLContext.wrap_bio``. This class is typically used by framework authors
533 that want to implement asynchronous IO for SSL through memory buffers.
534
535 When compared to ``SSLSocket``, this object lacks the following features:
536
537 * Any form of network IO incluging methods such as ``recv`` and ``send``.
538 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
539 """
540
541 def __init__(self, sslobj, owner=None):
542 self._sslobj = sslobj
543 # Note: _sslobj takes a weak reference to owner
544 self._sslobj.owner = owner or self
545
546 @property
547 def context(self):
548 """The SSLContext that is currently in use."""
549 return self._sslobj.context
550
551 @context.setter
552 def context(self, ctx):
553 self._sslobj.context = ctx
554
555 @property
556 def server_side(self):
557 """Whether this is a server-side socket."""
558 return self._sslobj.server_side
559
560 @property
561 def server_hostname(self):
562 """The currently set server hostname (for SNI), or ``None`` if no
563 server hostame is set."""
564 return self._sslobj.server_hostname
565
566 def read(self, len=0, buffer=None):
567 """Read up to 'len' bytes from the SSL object and return them.
568
569 If 'buffer' is provided, read into this buffer and return the number of
570 bytes read.
571 """
572 if buffer is not None:
573 v = self._sslobj.read(len, buffer)
574 else:
575 v = self._sslobj.read(len or 1024)
576 return v
577
578 def write(self, data):
579 """Write 'data' to the SSL object and return the number of bytes
580 written.
581
582 The 'data' argument must support the buffer interface.
583 """
584 return self._sslobj.write(data)
585
586 def getpeercert(self, binary_form=False):
587 """Returns a formatted version of the data in the certificate provided
588 by the other end of the SSL channel.
589
590 Return None if no certificate was provided, {} if a certificate was
591 provided, but not validated.
592 """
593 return self._sslobj.peer_certificate(binary_form)
594
595 def selected_npn_protocol(self):
596 """Return the currently selected NPN protocol as a string, or ``None``
597 if a next protocol was not negotiated or if NPN is not supported by one
598 of the peers."""
599 if _ssl.HAS_NPN:
600 return self._sslobj.selected_npn_protocol()
601
Benjamin Petersoncca27322015-01-23 16:35:37 -0500602 def selected_alpn_protocol(self):
603 """Return the currently selected ALPN protocol as a string, or ``None``
604 if a next protocol was not negotiated or if ALPN is not supported by one
605 of the peers."""
606 if _ssl.HAS_ALPN:
607 return self._sslobj.selected_alpn_protocol()
608
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200609 def cipher(self):
610 """Return the currently selected cipher as a 3-tuple ``(name,
611 ssl_version, secret_bits)``."""
612 return self._sslobj.cipher()
613
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600614 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500615 """Return a list of ciphers shared by the client during the handshake or
616 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600617 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600618 return self._sslobj.shared_ciphers()
619
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200620 def compression(self):
621 """Return the current compression algorithm in use, or ``None`` if
622 compression was not negotiated or not supported by one of the peers."""
623 return self._sslobj.compression()
624
625 def pending(self):
626 """Return the number of bytes that can be read immediately."""
627 return self._sslobj.pending()
628
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200629 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200630 """Start the SSL/TLS handshake."""
631 self._sslobj.do_handshake()
632 if self.context.check_hostname:
633 if not self.server_hostname:
634 raise ValueError("check_hostname needs server_hostname "
635 "argument")
636 match_hostname(self.getpeercert(), self.server_hostname)
637
638 def unwrap(self):
639 """Start the SSL shutdown handshake."""
640 return self._sslobj.shutdown()
641
642 def get_channel_binding(self, cb_type="tls-unique"):
643 """Get channel binding data for current connection. Raise ValueError
644 if the requested `cb_type` is not supported. Return bytes of the data
645 or None if the data is not available (e.g. before the handshake)."""
646 if cb_type not in CHANNEL_BINDING_TYPES:
647 raise ValueError("Unsupported channel binding type")
648 if cb_type != "tls-unique":
649 raise NotImplementedError(
650 "{0} channel binding type not implemented"
651 .format(cb_type))
652 return self._sslobj.tls_unique_cb()
653
654 def version(self):
655 """Return a string identifying the protocol version used by the
656 current SSL channel. """
657 return self._sslobj.version()
658
659
Antoine Pitrou152efa22010-05-16 18:19:27 +0000660class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000661 """This class implements a subtype of socket.socket that wraps
662 the underlying OS socket in an SSL context when necessary, and
663 provides read and write methods over that channel."""
664
Bill Janssen6e027db2007-11-15 22:23:56 +0000665 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000666 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000667 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
668 do_handshake_on_connect=True,
669 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100670 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000671 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000672 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000673
Antoine Pitrou152efa22010-05-16 18:19:27 +0000674 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100675 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000676 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000677 if server_side and not certfile:
678 raise ValueError("certfile must be specified for server-side "
679 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000680 if keyfile and not certfile:
681 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000682 if certfile and not keyfile:
683 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100684 self._context = SSLContext(ssl_version)
685 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000686 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100687 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000688 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100689 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100690 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100691 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000692 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100693 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000694 self.keyfile = keyfile
695 self.certfile = certfile
696 self.cert_reqs = cert_reqs
697 self.ssl_version = ssl_version
698 self.ca_certs = ca_certs
699 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100700 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
701 # mixed in.
702 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
703 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000704 if server_side and server_hostname:
705 raise ValueError("server_hostname can only be specified "
706 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100707 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600708 raise ValueError("check_hostname requires server_hostname")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000709 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000710 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000711 self.do_handshake_on_connect = do_handshake_on_connect
712 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000713 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000714 socket.__init__(self,
715 family=sock.family,
716 type=sock.type,
717 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000718 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000719 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000720 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000721 elif fileno is not None:
722 socket.__init__(self, fileno=fileno)
723 else:
724 socket.__init__(self, family=family, type=type, proto=proto)
725
Antoine Pitrou242db722013-05-01 20:52:07 +0200726 # See if we are connected
727 try:
728 self.getpeername()
729 except OSError as e:
730 if e.errno != errno.ENOTCONN:
731 raise
732 connected = False
733 else:
734 connected = True
735
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000736 self._closed = False
737 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000738 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000739 if connected:
740 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000741 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200742 sslobj = self._context._wrap_socket(self, server_side,
743 server_hostname)
744 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000745 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000746 timeout = self.gettimeout()
747 if timeout == 0.0:
748 # non-blocking
749 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000750 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000751
Christian Heimes1aa9a752013-12-02 02:41:19 +0100752 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000753 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100754 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200755
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756 @property
757 def context(self):
758 return self._context
759
760 @context.setter
761 def context(self, ctx):
762 self._context = ctx
763 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000764
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000765 def dup(self):
766 raise NotImplemented("Can't dup() %s instances" %
767 self.__class__.__name__)
768
Bill Janssen6e027db2007-11-15 22:23:56 +0000769 def _checkClosed(self, msg=None):
770 # raise an exception here if you wish to check for spurious closes
771 pass
772
Antoine Pitrou242db722013-05-01 20:52:07 +0200773 def _check_connected(self):
774 if not self._connected:
775 # getpeername() will raise ENOTCONN if the socket is really
776 # not connected; note that we can be connected even without
777 # _connected being set, e.g. if connect() first returned
778 # EAGAIN.
779 self.getpeername()
780
Bill Janssen54cc54c2007-12-14 22:08:56 +0000781 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000782 """Read up to LEN bytes and return them.
783 Return zero-length string on EOF."""
784
Bill Janssen6e027db2007-11-15 22:23:56 +0000785 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200786 if not self._sslobj:
787 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000788 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200789 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000790 except SSLError as x:
791 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000792 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000793 return 0
794 else:
795 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000796 else:
797 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000798
799 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000800 """Write DATA to the underlying SSL channel. Returns
801 number of bytes of DATA actually transmitted."""
802
Bill Janssen6e027db2007-11-15 22:23:56 +0000803 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200804 if not self._sslobj:
805 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000806 return self._sslobj.write(data)
807
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000809 """Returns a formatted version of the data in the
810 certificate provided by the other end of the SSL channel.
811 Return None if no certificate was provided, {} if a
812 certificate was provided, but not validated."""
813
Bill Janssen6e027db2007-11-15 22:23:56 +0000814 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200815 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200816 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100818 def selected_npn_protocol(self):
819 self._checkClosed()
820 if not self._sslobj or not _ssl.HAS_NPN:
821 return None
822 else:
823 return self._sslobj.selected_npn_protocol()
824
Benjamin Petersoncca27322015-01-23 16:35:37 -0500825 def selected_alpn_protocol(self):
826 self._checkClosed()
827 if not self._sslobj or not _ssl.HAS_ALPN:
828 return None
829 else:
830 return self._sslobj.selected_alpn_protocol()
831
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000832 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000833 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834 if not self._sslobj:
835 return None
836 else:
837 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000838
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600839 def shared_ciphers(self):
840 self._checkClosed()
841 if not self._sslobj:
842 return None
843 return self._sslobj.shared_ciphers()
844
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100845 def compression(self):
846 self._checkClosed()
847 if not self._sslobj:
848 return None
849 else:
850 return self._sslobj.compression()
851
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000852 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000853 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000854 if self._sslobj:
855 if flags != 0:
856 raise ValueError(
857 "non-zero flags not allowed in calls to send() on %s" %
858 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200859 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000860 else:
861 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000862
Antoine Pitroua468adc2010-09-14 14:43:44 +0000863 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000864 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000865 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000866 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000867 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000868 elif addr is None:
869 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000870 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000871 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000872
Nick Coghlan513886a2011-08-28 00:00:27 +1000873 def sendmsg(self, *args, **kwargs):
874 # Ensure programs don't send data unencrypted if they try to
875 # use this method.
876 raise NotImplementedError("sendmsg not allowed on instances of %s" %
877 self.__class__)
878
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000879 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000880 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000881 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000882 if flags != 0:
883 raise ValueError(
884 "non-zero flags not allowed in calls to sendall() on %s" %
885 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000886 amount = len(data)
887 count = 0
888 while (count < amount):
889 v = self.send(data[count:])
890 count += v
891 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000892 else:
893 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000894
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200895 def sendfile(self, file, offset=0, count=None):
896 """Send a file, possibly by using os.sendfile() if this is a
897 clear-text socket. Return the total number of bytes sent.
898 """
899 if self._sslobj is None:
900 # os.sendfile() works with plain sockets only
901 return super().sendfile(file, offset, count)
902 else:
903 return self._sendfile_use_send(file, offset, count)
904
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000905 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000906 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000907 if self._sslobj:
908 if flags != 0:
909 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000910 "non-zero flags not allowed in calls to recv() on %s" %
911 self.__class__)
912 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000913 else:
914 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000915
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000916 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000917 self._checkClosed()
918 if buffer and (nbytes is None):
919 nbytes = len(buffer)
920 elif nbytes is None:
921 nbytes = 1024
922 if self._sslobj:
923 if flags != 0:
924 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000925 "non-zero flags not allowed in calls to recv_into() on %s" %
926 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000927 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000928 else:
929 return socket.recv_into(self, buffer, nbytes, flags)
930
Antoine Pitroua468adc2010-09-14 14:43:44 +0000931 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000932 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000933 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000934 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000935 self.__class__)
936 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000937 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000938
Bill Janssen58afe4c2008-09-08 16:45:19 +0000939 def recvfrom_into(self, buffer, nbytes=None, flags=0):
940 self._checkClosed()
941 if self._sslobj:
942 raise ValueError("recvfrom_into not allowed on instances of %s" %
943 self.__class__)
944 else:
945 return socket.recvfrom_into(self, buffer, nbytes, flags)
946
Nick Coghlan513886a2011-08-28 00:00:27 +1000947 def recvmsg(self, *args, **kwargs):
948 raise NotImplementedError("recvmsg not allowed on instances of %s" %
949 self.__class__)
950
951 def recvmsg_into(self, *args, **kwargs):
952 raise NotImplementedError("recvmsg_into not allowed on instances of "
953 "%s" % self.__class__)
954
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000955 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000956 self._checkClosed()
957 if self._sslobj:
958 return self._sslobj.pending()
959 else:
960 return 0
961
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000962 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000963 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000965 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000966
Ezio Melottidc55e672010-01-18 09:15:14 +0000967 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000968 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200969 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +0000970 self._sslobj = None
971 return s
972 else:
973 raise ValueError("No SSL wrapper around " + str(self))
974
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000975 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000977 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000978
Bill Janssen48dc27c2007-12-05 03:38:10 +0000979 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000980 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200981 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000982 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000983 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000984 if timeout == 0.0 and block:
985 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000986 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000987 finally:
988 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000989
Antoine Pitroub4410db2011-05-18 18:51:06 +0200990 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000991 if self.server_side:
992 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000993 # Here we assume that the socket is client-side, and not
994 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000995 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000996 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200997 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
998 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000999 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001000 if connect_ex:
1001 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001002 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +02001003 rc = None
1004 socket.connect(self, addr)
1005 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +02001006 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +02001007 if self.do_handshake_on_connect:
1008 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +02001009 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +01001010 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +02001011 self._sslobj = None
1012 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +00001013
1014 def connect(self, addr):
1015 """Connects to remote ADDR, and then wraps the connection in
1016 an SSL channel."""
1017 self._real_connect(addr, False)
1018
1019 def connect_ex(self, addr):
1020 """Connects to remote ADDR, and then wraps the connection in
1021 an SSL channel."""
1022 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001023
1024 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001025 """Accepts a new connection from a remote client, and returns
1026 a tuple containing that new connection wrapped with a server-side
1027 SSL channel, and the address of the remote client."""
1028
1029 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001030 newsock = self.context.wrap_socket(newsock,
1031 do_handshake_on_connect=self.do_handshake_on_connect,
1032 suppress_ragged_eofs=self.suppress_ragged_eofs,
1033 server_side=True)
1034 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035
Antoine Pitroud6494802011-07-21 01:11:30 +02001036 def get_channel_binding(self, cb_type="tls-unique"):
1037 """Get channel binding data for current connection. Raise ValueError
1038 if the requested `cb_type` is not supported. Return bytes of the data
1039 or None if the data is not available (e.g. before the handshake).
1040 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001041 if self._sslobj is None:
1042 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001043 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001044
Antoine Pitrou47e40422014-09-04 21:00:10 +02001045 def version(self):
1046 """
1047 Return a string identifying the protocol version used by the
1048 current SSL channel, or None if there is no established channel.
1049 """
1050 if self._sslobj is None:
1051 return None
1052 return self._sslobj.version()
1053
Bill Janssen54cc54c2007-12-14 22:08:56 +00001054
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055def wrap_socket(sock, keyfile=None, certfile=None,
1056 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +00001057 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001058 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001059 suppress_ragged_eofs=True,
1060 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Bill Janssen6e027db2007-11-15 22:23:56 +00001062 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001064 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001065 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001066 suppress_ragged_eofs=suppress_ragged_eofs,
1067 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001068
Thomas Woutersed03b412007-08-28 21:37:11 +00001069# some utility functions
1070
1071def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001072 """Return the time in seconds since the Epoch, given the timestring
1073 representing the "notBefore" or "notAfter" date from a certificate
1074 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001075
Antoine Pitrouc695c952014-04-28 20:57:36 +02001076 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1077
1078 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1079 UTC should be specified as GMT (see ASN1_TIME_print())
1080 """
1081 from time import strptime
1082 from calendar import timegm
1083
1084 months = (
1085 "Jan","Feb","Mar","Apr","May","Jun",
1086 "Jul","Aug","Sep","Oct","Nov","Dec"
1087 )
1088 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1089 try:
1090 month_number = months.index(cert_time[:3].title()) + 1
1091 except ValueError:
1092 raise ValueError('time data %r does not match '
1093 'format "%%b%s"' % (cert_time, time_format))
1094 else:
1095 # found valid month
1096 tt = strptime(cert_time[3:], time_format)
1097 # return an integer, the previous mktime()-based implementation
1098 # returned a float (fractional seconds are always zero here).
1099 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001100
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001101PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1102PEM_FOOTER = "-----END CERTIFICATE-----"
1103
1104def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105 """Takes a certificate in binary DER format and returns the
1106 PEM version of it as a string."""
1107
Bill Janssen6e027db2007-11-15 22:23:56 +00001108 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1109 return (PEM_HEADER + '\n' +
1110 textwrap.fill(f, 64) + '\n' +
1111 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
1113def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114 """Takes a certificate in ASCII PEM format and returns the
1115 DER-encoded version of it as a byte sequence"""
1116
1117 if not pem_cert_string.startswith(PEM_HEADER):
1118 raise ValueError("Invalid PEM encoding; must start with %s"
1119 % PEM_HEADER)
1120 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1121 raise ValueError("Invalid PEM encoding; must end with %s"
1122 % PEM_FOOTER)
1123 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001124 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125
Antoine Pitrou94a5b662014-04-16 18:56:28 +02001126def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127 """Retrieve the certificate from the server at the specified address,
1128 and return it as a PEM-encoded string.
1129 If 'ca_certs' is specified, validate the server cert against it.
1130 If 'ssl_version' is specified, use it in the connection attempt."""
1131
1132 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001133 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134 cert_reqs = CERT_REQUIRED
1135 else:
1136 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001137 context = _create_stdlib_context(ssl_version,
1138 cert_reqs=cert_reqs,
1139 cafile=ca_certs)
1140 with create_connection(addr) as sock:
1141 with context.wrap_socket(sock) as sslsock:
1142 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143 return DER_cert_to_PEM_cert(dercert)
1144
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001145def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001146 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')