blob: 807e9f2896d19f346f78f5ede21cca1105255b3e [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
Christian Heimes05e8be12008-02-23 18:30:17 +000090import textwrap
Antoine Pitrou59fdd672010-10-08 10:37:08 +000091import re
Christian Heimes46bebee2013-06-09 19:03:31 +020092import sys
Christian Heimes6d7ad132013-06-09 18:02:55 +020093import os
Christian Heimesa6bc95a2013-11-17 19:59:14 +010094from collections import namedtuple
Antoine Pitrou172f0252014-04-18 20:33:08 +020095from enum import Enum as _Enum, IntEnum as _IntEnum
Thomas Woutersed03b412007-08-28 21:37:11 +000096
97import _ssl # if we can't import it, let the error propagate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098
Antoine Pitrou04f6a322010-04-05 21:40:07 +000099from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200100from _ssl import _SSLContext, MemoryBIO
Antoine Pitrou41032a62011-10-27 23:56:55 +0200101from _ssl import (
102 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
103 SSLSyscallError, SSLEOFError,
104 )
Thomas Woutersed03b412007-08-28 21:37:11 +0000105from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Christian Heimes22587792013-11-21 23:56:13 +0100106from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
107 VERIFY_X509_STRICT)
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerbeeb5122014-11-28 13:28:25 +0100109from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
110try:
111 from _ssl import RAND_egd
112except ImportError:
113 # LibreSSL does not provide RAND_egd
114 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100115
116def _import_symbols(prefix):
117 for n in dir(_ssl):
118 if n.startswith(prefix):
119 globals()[n] = getattr(_ssl, n)
120
121_import_symbols('OP_')
122_import_symbols('ALERT_DESCRIPTION_')
123_import_symbols('SSL_ERROR_')
124
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
Antoine Pitrou172f0252014-04-18 20:33:08 +0200129_SSLMethod = _IntEnum('_SSLMethod',
130 {name: value for name, value in vars(_ssl).items()
131 if name.startswith('PROTOCOL_')})
132globals().update(_SSLMethod.__members__)
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
166# * Finally use RC4 as a fallback which is problematic but needed for
167# compatibility some times.
168# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
169# reasons
170_DEFAULT_CIPHERS = (
171 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
172 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
173 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
174)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100175
Donald Stufft6a2ba942014-03-23 19:05:28 -0400176# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400177# This list has been explicitly chosen to:
178# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
179# * Prefer ECDHE over DHE for better performance
180# * Prefer any AES-GCM over any AES-CBC for better performance and security
181# * Then Use HIGH cipher suites as a fallback
182# * Then Use 3DES as fallback which is secure but slow
183# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
184# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400185_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400186 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
187 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
188 '!eNULL:!MD5:!DSS:!RC4'
189)
Christian Heimes4c05b472013-11-23 15:58:30 +0100190
Thomas Woutersed03b412007-08-28 21:37:11 +0000191
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000192class CertificateError(ValueError):
193 pass
194
195
Georg Brandl72c98d32013-10-27 07:16:53 +0100196def _dnsname_match(dn, hostname, max_wildcards=1):
197 """Matching according to RFC 6125, section 6.4.3
198
199 http://tools.ietf.org/html/rfc6125#section-6.4.3
200 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000201 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100202 if not dn:
203 return False
204
205 leftmost, *remainder = dn.split(r'.')
206
207 wildcards = leftmost.count('*')
208 if wildcards > max_wildcards:
209 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300210 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100211 # policy among SSL implementations showed it to be a
212 # reasonable choice.
213 raise CertificateError(
214 "too many wildcards in certificate DNS name: " + repr(dn))
215
216 # speed up common case w/o wildcards
217 if not wildcards:
218 return dn.lower() == hostname.lower()
219
220 # RFC 6125, section 6.4.3, subitem 1.
221 # The client SHOULD NOT attempt to match a presented identifier in which
222 # the wildcard character comprises a label other than the left-most label.
223 if leftmost == '*':
224 # When '*' is a fragment by itself, it matches a non-empty dotless
225 # fragment.
226 pats.append('[^.]+')
227 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
228 # RFC 6125, section 6.4.3, subitem 3.
229 # The client SHOULD NOT attempt to match a presented identifier
230 # where the wildcard character is embedded within an A-label or
231 # U-label of an internationalized domain name.
232 pats.append(re.escape(leftmost))
233 else:
234 # Otherwise, '*' matches any dotless string, e.g. www*
235 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
236
237 # add the remaining fragments, ignore any wildcards
238 for frag in remainder:
239 pats.append(re.escape(frag))
240
241 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
242 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000243
244
245def match_hostname(cert, hostname):
246 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100247 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
248 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000249
250 CertificateError is raised on failure. On success, the function
251 returns nothing.
252 """
253 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100254 raise ValueError("empty or no certificate, match_hostname needs a "
255 "SSL socket or SSL context with either "
256 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000257 dnsnames = []
258 san = cert.get('subjectAltName', ())
259 for key, value in san:
260 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100261 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000262 return
263 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200264 if not dnsnames:
265 # The subject is only checked when there is no dNSName entry
266 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000267 for sub in cert.get('subject', ()):
268 for key, value in sub:
269 # XXX according to RFC 2818, the most specific Common Name
270 # must be used.
271 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100272 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000273 return
274 dnsnames.append(value)
275 if len(dnsnames) > 1:
276 raise CertificateError("hostname %r "
277 "doesn't match either of %s"
278 % (hostname, ', '.join(map(repr, dnsnames))))
279 elif len(dnsnames) == 1:
280 raise CertificateError("hostname %r "
281 "doesn't match %r"
282 % (hostname, dnsnames[0]))
283 else:
284 raise CertificateError("no appropriate commonName or "
285 "subjectAltName fields were found")
286
287
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100288DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200289 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
290 "openssl_capath")
291
292def get_default_verify_paths():
293 """Return paths to default cafile and capath.
294 """
295 parts = _ssl.get_default_verify_paths()
296
297 # environment vars shadow paths
298 cafile = os.environ.get(parts[0], parts[1])
299 capath = os.environ.get(parts[2], parts[3])
300
301 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
302 capath if os.path.isdir(capath) else None,
303 *parts)
304
305
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100306class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
307 """ASN.1 object identifier lookup
308 """
309 __slots__ = ()
310
311 def __new__(cls, oid):
312 return super().__new__(cls, *_txt2obj(oid, name=False))
313
314 @classmethod
315 def fromnid(cls, nid):
316 """Create _ASN1Object from OpenSSL numeric ID
317 """
318 return super().__new__(cls, *_nid2obj(nid))
319
320 @classmethod
321 def fromname(cls, name):
322 """Create _ASN1Object from short name, long name or OID
323 """
324 return super().__new__(cls, *_txt2obj(name, name=True))
325
326
Christian Heimes72d28502013-11-23 13:56:58 +0100327class Purpose(_ASN1Object, _Enum):
328 """SSLContext purpose flags with X509v3 Extended Key Usage objects
329 """
330 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
331 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
332
333
Antoine Pitrou152efa22010-05-16 18:19:27 +0000334class SSLContext(_SSLContext):
335 """An SSLContext holds various SSL-related configuration options and
336 data, such as certificates and possibly a private key."""
337
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100338 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100339 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340
341 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100342 self = _SSLContext.__new__(cls, protocol)
343 if protocol != _SSLv2_IF_EXISTS:
344 self.set_ciphers(_DEFAULT_CIPHERS)
345 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346
347 def __init__(self, protocol):
348 self.protocol = protocol
349
350 def wrap_socket(self, sock, server_side=False,
351 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000352 suppress_ragged_eofs=True,
353 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000354 return SSLSocket(sock=sock, server_side=server_side,
355 do_handshake_on_connect=do_handshake_on_connect,
356 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000357 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000358 _context=self)
359
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200360 def wrap_bio(self, incoming, outgoing, server_side=False,
361 server_hostname=None):
362 sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
363 server_hostname=server_hostname)
364 return SSLObject(sslobj)
365
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100366 def set_npn_protocols(self, npn_protocols):
367 protos = bytearray()
368 for protocol in npn_protocols:
369 b = bytes(protocol, 'ascii')
370 if len(b) == 0 or len(b) > 255:
371 raise SSLError('NPN protocols must be 1 to 255 in length')
372 protos.append(len(b))
373 protos.extend(b)
374
375 self._set_npn_protocols(protos)
376
Benjamin Petersoncca27322015-01-23 16:35:37 -0500377 def set_alpn_protocols(self, alpn_protocols):
378 protos = bytearray()
379 for protocol in alpn_protocols:
380 b = bytes(protocol, 'ascii')
381 if len(b) == 0 or len(b) > 255:
382 raise SSLError('ALPN protocols must be 1 to 255 in length')
383 protos.append(len(b))
384 protos.extend(b)
385
386 self._set_alpn_protocols(protos)
387
Christian Heimes72d28502013-11-23 13:56:58 +0100388 def _load_windows_store_certs(self, storename, purpose):
389 certs = bytearray()
390 for cert, encoding, trust in enum_certificates(storename):
391 # CA certs are never PKCS#7 encoded
392 if encoding == "x509_asn":
393 if trust is True or purpose.oid in trust:
394 certs.extend(cert)
395 self.load_verify_locations(cadata=certs)
396 return certs
397
398 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
399 if not isinstance(purpose, _ASN1Object):
400 raise TypeError(purpose)
401 if sys.platform == "win32":
402 for storename in self._windows_cert_stores:
403 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400404 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100405
Antoine Pitrou152efa22010-05-16 18:19:27 +0000406
Christian Heimes4c05b472013-11-23 15:58:30 +0100407def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
408 capath=None, cadata=None):
409 """Create a SSLContext object with default settings.
410
411 NOTE: The protocol and settings may change anytime without prior
412 deprecation. The values represent a fair balance between maximum
413 compatibility and security.
414 """
415 if not isinstance(purpose, _ASN1Object):
416 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400417
418 context = SSLContext(PROTOCOL_SSLv23)
419
Christian Heimes4c05b472013-11-23 15:58:30 +0100420 # SSLv2 considered harmful.
421 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400422
423 # SSLv3 has problematic security and is only required for really old
424 # clients such as IE6 on Windows XP
425 context.options |= OP_NO_SSLv3
426
Christian Heimesdec813f2013-11-28 08:06:54 +0100427 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
428 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400429
Christian Heimes4c05b472013-11-23 15:58:30 +0100430 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400431 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100432 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100433 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400434 elif purpose == Purpose.CLIENT_AUTH:
435 # Prefer the server's ciphers by default so that we get stronger
436 # encryption
437 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
438
439 # Use single use keys in order to improve forward secrecy
440 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
441 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
442
443 # disallow ciphers with known vulnerabilities
444 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
445
Christian Heimes4c05b472013-11-23 15:58:30 +0100446 if cafile or capath or cadata:
447 context.load_verify_locations(cafile, capath, cadata)
448 elif context.verify_mode != CERT_NONE:
449 # no explicit cafile, capath or cadata but the verify mode is
450 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
451 # root CA certificates for the given purpose. This may fail silently.
452 context.load_default_certs(purpose)
453 return context
454
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500455def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100456 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100457 certfile=None, keyfile=None,
458 cafile=None, capath=None, cadata=None):
459 """Create a SSLContext object for Python stdlib modules
460
461 All Python stdlib modules shall use this function to create SSLContext
462 objects in order to keep common settings in one place. The configuration
463 is less restrict than create_default_context()'s to increase backward
464 compatibility.
465 """
466 if not isinstance(purpose, _ASN1Object):
467 raise TypeError(purpose)
468
469 context = SSLContext(protocol)
470 # SSLv2 considered harmful.
471 context.options |= OP_NO_SSLv2
Antoine Pitroue4eda4d2014-10-17 19:28:30 +0200472 # SSLv3 has problematic security and is only required for really old
473 # clients such as IE6 on Windows XP
474 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100475
476 if cert_reqs is not None:
477 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100478 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100479
480 if keyfile and not certfile:
481 raise ValueError("certfile must be specified")
482 if certfile or keyfile:
483 context.load_cert_chain(certfile, keyfile)
484
485 # load CA root certs
486 if cafile or capath or cadata:
487 context.load_verify_locations(cafile, capath, cadata)
488 elif context.verify_mode != CERT_NONE:
489 # no explicit cafile, capath or cadata but the verify mode is
490 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
491 # root CA certificates for the given purpose. This may fail silently.
492 context.load_default_certs(purpose)
493
494 return context
495
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500496# Used by http.client if no context is explicitly passed.
497_create_default_https_context = create_default_context
498
499
500# Backwards compatibility alias, even though it's not a public name.
501_create_stdlib_context = _create_unverified_context
502
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200503
504class SSLObject:
505 """This class implements an interface on top of a low-level SSL object as
506 implemented by OpenSSL. This object captures the state of an SSL connection
507 but does not provide any network IO itself. IO needs to be performed
508 through separate "BIO" objects which are OpenSSL's IO abstraction layer.
509
510 This class does not have a public constructor. Instances are returned by
511 ``SSLContext.wrap_bio``. This class is typically used by framework authors
512 that want to implement asynchronous IO for SSL through memory buffers.
513
514 When compared to ``SSLSocket``, this object lacks the following features:
515
516 * Any form of network IO incluging methods such as ``recv`` and ``send``.
517 * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
518 """
519
520 def __init__(self, sslobj, owner=None):
521 self._sslobj = sslobj
522 # Note: _sslobj takes a weak reference to owner
523 self._sslobj.owner = owner or self
524
525 @property
526 def context(self):
527 """The SSLContext that is currently in use."""
528 return self._sslobj.context
529
530 @context.setter
531 def context(self, ctx):
532 self._sslobj.context = ctx
533
534 @property
535 def server_side(self):
536 """Whether this is a server-side socket."""
537 return self._sslobj.server_side
538
539 @property
540 def server_hostname(self):
541 """The currently set server hostname (for SNI), or ``None`` if no
542 server hostame is set."""
543 return self._sslobj.server_hostname
544
545 def read(self, len=0, buffer=None):
546 """Read up to 'len' bytes from the SSL object and return them.
547
548 If 'buffer' is provided, read into this buffer and return the number of
549 bytes read.
550 """
551 if buffer is not None:
552 v = self._sslobj.read(len, buffer)
553 else:
554 v = self._sslobj.read(len or 1024)
555 return v
556
557 def write(self, data):
558 """Write 'data' to the SSL object and return the number of bytes
559 written.
560
561 The 'data' argument must support the buffer interface.
562 """
563 return self._sslobj.write(data)
564
565 def getpeercert(self, binary_form=False):
566 """Returns a formatted version of the data in the certificate provided
567 by the other end of the SSL channel.
568
569 Return None if no certificate was provided, {} if a certificate was
570 provided, but not validated.
571 """
572 return self._sslobj.peer_certificate(binary_form)
573
574 def selected_npn_protocol(self):
575 """Return the currently selected NPN protocol as a string, or ``None``
576 if a next protocol was not negotiated or if NPN is not supported by one
577 of the peers."""
578 if _ssl.HAS_NPN:
579 return self._sslobj.selected_npn_protocol()
580
Benjamin Petersoncca27322015-01-23 16:35:37 -0500581 def selected_alpn_protocol(self):
582 """Return the currently selected ALPN protocol as a string, or ``None``
583 if a next protocol was not negotiated or if ALPN is not supported by one
584 of the peers."""
585 if _ssl.HAS_ALPN:
586 return self._sslobj.selected_alpn_protocol()
587
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200588 def cipher(self):
589 """Return the currently selected cipher as a 3-tuple ``(name,
590 ssl_version, secret_bits)``."""
591 return self._sslobj.cipher()
592
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600593 def shared_ciphers(self):
Benjamin Petersonc114e7d2015-01-11 15:22:07 -0500594 """Return a list of ciphers shared by the client during the handshake or
595 None if this is not a valid server connection.
Benjamin Peterson5318c7a2015-01-07 11:26:50 -0600596 """
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600597 return self._sslobj.shared_ciphers()
598
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200599 def compression(self):
600 """Return the current compression algorithm in use, or ``None`` if
601 compression was not negotiated or not supported by one of the peers."""
602 return self._sslobj.compression()
603
604 def pending(self):
605 """Return the number of bytes that can be read immediately."""
606 return self._sslobj.pending()
607
Antoine Pitrou3cb93792014-10-06 00:21:09 +0200608 def do_handshake(self):
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200609 """Start the SSL/TLS handshake."""
610 self._sslobj.do_handshake()
611 if self.context.check_hostname:
612 if not self.server_hostname:
613 raise ValueError("check_hostname needs server_hostname "
614 "argument")
615 match_hostname(self.getpeercert(), self.server_hostname)
616
617 def unwrap(self):
618 """Start the SSL shutdown handshake."""
619 return self._sslobj.shutdown()
620
621 def get_channel_binding(self, cb_type="tls-unique"):
622 """Get channel binding data for current connection. Raise ValueError
623 if the requested `cb_type` is not supported. Return bytes of the data
624 or None if the data is not available (e.g. before the handshake)."""
625 if cb_type not in CHANNEL_BINDING_TYPES:
626 raise ValueError("Unsupported channel binding type")
627 if cb_type != "tls-unique":
628 raise NotImplementedError(
629 "{0} channel binding type not implemented"
630 .format(cb_type))
631 return self._sslobj.tls_unique_cb()
632
633 def version(self):
634 """Return a string identifying the protocol version used by the
635 current SSL channel. """
636 return self._sslobj.version()
637
638
Antoine Pitrou152efa22010-05-16 18:19:27 +0000639class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000640 """This class implements a subtype of socket.socket that wraps
641 the underlying OS socket in an SSL context when necessary, and
642 provides read and write methods over that channel."""
643
Bill Janssen6e027db2007-11-15 22:23:56 +0000644 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000645 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000646 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
647 do_handshake_on_connect=True,
648 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100649 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000650 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000651 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000652
Antoine Pitrou152efa22010-05-16 18:19:27 +0000653 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100654 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000655 else:
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000656 if server_side and not certfile:
657 raise ValueError("certfile must be specified for server-side "
658 "operations")
Giampaolo Rodolà8b7da622010-08-30 18:28:05 +0000659 if keyfile and not certfile:
660 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000661 if certfile and not keyfile:
662 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100663 self._context = SSLContext(ssl_version)
664 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000665 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100666 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000667 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100668 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100669 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100670 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000671 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100672 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000673 self.keyfile = keyfile
674 self.certfile = certfile
675 self.cert_reqs = cert_reqs
676 self.ssl_version = ssl_version
677 self.ca_certs = ca_certs
678 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100679 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
680 # mixed in.
681 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
682 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000683 if server_side and server_hostname:
684 raise ValueError("server_hostname can only be specified "
685 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100686 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600687 raise ValueError("check_hostname requires server_hostname")
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000688 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000689 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000690 self.do_handshake_on_connect = do_handshake_on_connect
691 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000692 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000693 socket.__init__(self,
694 family=sock.family,
695 type=sock.type,
696 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000697 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000698 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000699 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000700 elif fileno is not None:
701 socket.__init__(self, fileno=fileno)
702 else:
703 socket.__init__(self, family=family, type=type, proto=proto)
704
Antoine Pitrou242db722013-05-01 20:52:07 +0200705 # See if we are connected
706 try:
707 self.getpeername()
708 except OSError as e:
709 if e.errno != errno.ENOTCONN:
710 raise
711 connected = False
712 else:
713 connected = True
714
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000715 self._closed = False
716 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000717 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000718 if connected:
719 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000720 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200721 sslobj = self._context._wrap_socket(self, server_side,
722 server_hostname)
723 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000724 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000725 timeout = self.gettimeout()
726 if timeout == 0.0:
727 # non-blocking
728 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000729 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000730
Christian Heimes1aa9a752013-12-02 02:41:19 +0100731 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000732 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100733 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200734
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100735 @property
736 def context(self):
737 return self._context
738
739 @context.setter
740 def context(self, ctx):
741 self._context = ctx
742 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000743
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000744 def dup(self):
745 raise NotImplemented("Can't dup() %s instances" %
746 self.__class__.__name__)
747
Bill Janssen6e027db2007-11-15 22:23:56 +0000748 def _checkClosed(self, msg=None):
749 # raise an exception here if you wish to check for spurious closes
750 pass
751
Antoine Pitrou242db722013-05-01 20:52:07 +0200752 def _check_connected(self):
753 if not self._connected:
754 # getpeername() will raise ENOTCONN if the socket is really
755 # not connected; note that we can be connected even without
756 # _connected being set, e.g. if connect() first returned
757 # EAGAIN.
758 self.getpeername()
759
Bill Janssen54cc54c2007-12-14 22:08:56 +0000760 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000761 """Read up to LEN bytes and return them.
762 Return zero-length string on EOF."""
763
Bill Janssen6e027db2007-11-15 22:23:56 +0000764 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200765 if not self._sslobj:
766 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000767 try:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200768 return self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000769 except SSLError as x:
770 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000771 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000772 return 0
773 else:
774 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000775 else:
776 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000777
778 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000779 """Write DATA to the underlying SSL channel. Returns
780 number of bytes of DATA actually transmitted."""
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("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000785 return self._sslobj.write(data)
786
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000788 """Returns a formatted version of the data in the
789 certificate provided by the other end of the SSL channel.
790 Return None if no certificate was provided, {} if a
791 certificate was provided, but not validated."""
792
Bill Janssen6e027db2007-11-15 22:23:56 +0000793 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200794 self._check_connected()
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200795 return self._sslobj.getpeercert(binary_form)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100797 def selected_npn_protocol(self):
798 self._checkClosed()
799 if not self._sslobj or not _ssl.HAS_NPN:
800 return None
801 else:
802 return self._sslobj.selected_npn_protocol()
803
Benjamin Petersoncca27322015-01-23 16:35:37 -0500804 def selected_alpn_protocol(self):
805 self._checkClosed()
806 if not self._sslobj or not _ssl.HAS_ALPN:
807 return None
808 else:
809 return self._sslobj.selected_alpn_protocol()
810
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000811 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000812 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813 if not self._sslobj:
814 return None
815 else:
816 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000817
Benjamin Peterson4cb17812015-01-07 11:14:26 -0600818 def shared_ciphers(self):
819 self._checkClosed()
820 if not self._sslobj:
821 return None
822 return self._sslobj.shared_ciphers()
823
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100824 def compression(self):
825 self._checkClosed()
826 if not self._sslobj:
827 return None
828 else:
829 return self._sslobj.compression()
830
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000831 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000832 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000833 if self._sslobj:
834 if flags != 0:
835 raise ValueError(
836 "non-zero flags not allowed in calls to send() on %s" %
837 self.__class__)
Antoine Pitroub4bebda2014-04-29 10:03:28 +0200838 return self._sslobj.write(data)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000839 else:
840 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000841
Antoine Pitroua468adc2010-09-14 14:43:44 +0000842 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000843 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000844 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000845 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000846 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000847 elif addr is None:
848 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000849 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000850 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000851
Nick Coghlan513886a2011-08-28 00:00:27 +1000852 def sendmsg(self, *args, **kwargs):
853 # Ensure programs don't send data unencrypted if they try to
854 # use this method.
855 raise NotImplementedError("sendmsg not allowed on instances of %s" %
856 self.__class__)
857
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000858 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000859 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000860 if self._sslobj:
Giampaolo Rodolà374f8352010-08-29 12:08:09 +0000861 if flags != 0:
862 raise ValueError(
863 "non-zero flags not allowed in calls to sendall() on %s" %
864 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000865 amount = len(data)
866 count = 0
867 while (count < amount):
868 v = self.send(data[count:])
869 count += v
870 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000871 else:
872 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000873
Giampaolo Rodola'915d1412014-06-11 03:54:30 +0200874 def sendfile(self, file, offset=0, count=None):
875 """Send a file, possibly by using os.sendfile() if this is a
876 clear-text socket. Return the total number of bytes sent.
877 """
878 if self._sslobj is None:
879 # os.sendfile() works with plain sockets only
880 return super().sendfile(file, offset, count)
881 else:
882 return self._sendfile_use_send(file, offset, count)
883
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000884 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000885 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000886 if self._sslobj:
887 if flags != 0:
888 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000889 "non-zero flags not allowed in calls to recv() on %s" %
890 self.__class__)
891 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000892 else:
893 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000894
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000895 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000896 self._checkClosed()
897 if buffer and (nbytes is None):
898 nbytes = len(buffer)
899 elif nbytes is None:
900 nbytes = 1024
901 if self._sslobj:
902 if flags != 0:
903 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000904 "non-zero flags not allowed in calls to recv_into() on %s" %
905 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000906 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000907 else:
908 return socket.recv_into(self, buffer, nbytes, flags)
909
Antoine Pitroua468adc2010-09-14 14:43:44 +0000910 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000911 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000912 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000913 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000914 self.__class__)
915 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000916 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000917
Bill Janssen58afe4c2008-09-08 16:45:19 +0000918 def recvfrom_into(self, buffer, nbytes=None, flags=0):
919 self._checkClosed()
920 if self._sslobj:
921 raise ValueError("recvfrom_into not allowed on instances of %s" %
922 self.__class__)
923 else:
924 return socket.recvfrom_into(self, buffer, nbytes, flags)
925
Nick Coghlan513886a2011-08-28 00:00:27 +1000926 def recvmsg(self, *args, **kwargs):
927 raise NotImplementedError("recvmsg not allowed on instances of %s" %
928 self.__class__)
929
930 def recvmsg_into(self, *args, **kwargs):
931 raise NotImplementedError("recvmsg_into not allowed on instances of "
932 "%s" % self.__class__)
933
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000934 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000935 self._checkClosed()
936 if self._sslobj:
937 return self._sslobj.pending()
938 else:
939 return 0
940
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000941 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000942 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000944 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000945
Ezio Melottidc55e672010-01-18 09:15:14 +0000946 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000947 if self._sslobj:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200948 s = self._sslobj.unwrap()
Bill Janssen40a0f662008-08-12 16:56:25 +0000949 self._sslobj = None
950 return s
951 else:
952 raise ValueError("No SSL wrapper around " + str(self))
953
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000954 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000956 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000957
Bill Janssen48dc27c2007-12-05 03:38:10 +0000958 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000959 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200960 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000961 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000962 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000963 if timeout == 0.0 and block:
964 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000965 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000966 finally:
967 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000968
Antoine Pitroub4410db2011-05-18 18:51:06 +0200969 def _real_connect(self, addr, connect_ex):
Giampaolo Rodolà745ab382010-08-29 19:25:49 +0000970 if self.server_side:
971 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000972 # Here we assume that the socket is client-side, and not
973 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000974 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200976 sslobj = self.context._wrap_socket(self, False, self.server_hostname)
977 self._sslobj = SSLObject(sslobj, owner=self)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000978 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200979 if connect_ex:
980 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000981 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200982 rc = None
983 socket.connect(self, addr)
984 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200985 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200986 if self.do_handshake_on_connect:
987 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200988 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +0100989 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +0200990 self._sslobj = None
991 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000992
993 def connect(self, addr):
994 """Connects to remote ADDR, and then wraps the connection in
995 an SSL channel."""
996 self._real_connect(addr, False)
997
998 def connect_ex(self, addr):
999 """Connects to remote ADDR, and then wraps the connection in
1000 an SSL channel."""
1001 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +00001002
1003 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001004 """Accepts a new connection from a remote client, and returns
1005 a tuple containing that new connection wrapped with a server-side
1006 SSL channel, and the address of the remote client."""
1007
1008 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +01001009 newsock = self.context.wrap_socket(newsock,
1010 do_handshake_on_connect=self.do_handshake_on_connect,
1011 suppress_ragged_eofs=self.suppress_ragged_eofs,
1012 server_side=True)
1013 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001014
Antoine Pitroud6494802011-07-21 01:11:30 +02001015 def get_channel_binding(self, cb_type="tls-unique"):
1016 """Get channel binding data for current connection. Raise ValueError
1017 if the requested `cb_type` is not supported. Return bytes of the data
1018 or None if the data is not available (e.g. before the handshake).
1019 """
Antoine Pitroud6494802011-07-21 01:11:30 +02001020 if self._sslobj is None:
1021 return None
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001022 return self._sslobj.get_channel_binding(cb_type)
Antoine Pitroud6494802011-07-21 01:11:30 +02001023
Antoine Pitrou47e40422014-09-04 21:00:10 +02001024 def version(self):
1025 """
1026 Return a string identifying the protocol version used by the
1027 current SSL channel, or None if there is no established channel.
1028 """
1029 if self._sslobj is None:
1030 return None
1031 return self._sslobj.version()
1032
Bill Janssen54cc54c2007-12-14 22:08:56 +00001033
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034def wrap_socket(sock, keyfile=None, certfile=None,
1035 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +00001036 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001037 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001038 suppress_ragged_eofs=True,
1039 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001040
Bill Janssen6e027db2007-11-15 22:23:56 +00001041 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001042 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +00001043 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +00001044 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +00001045 suppress_ragged_eofs=suppress_ragged_eofs,
1046 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047
Thomas Woutersed03b412007-08-28 21:37:11 +00001048# some utility functions
1049
1050def cert_time_to_seconds(cert_time):
Antoine Pitrouc695c952014-04-28 20:57:36 +02001051 """Return the time in seconds since the Epoch, given the timestring
1052 representing the "notBefore" or "notAfter" date from a certificate
1053 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001054
Antoine Pitrouc695c952014-04-28 20:57:36 +02001055 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
1056
1057 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1058 UTC should be specified as GMT (see ASN1_TIME_print())
1059 """
1060 from time import strptime
1061 from calendar import timegm
1062
1063 months = (
1064 "Jan","Feb","Mar","Apr","May","Jun",
1065 "Jul","Aug","Sep","Oct","Nov","Dec"
1066 )
1067 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
1068 try:
1069 month_number = months.index(cert_time[:3].title()) + 1
1070 except ValueError:
1071 raise ValueError('time data %r does not match '
1072 'format "%%b%s"' % (cert_time, time_format))
1073 else:
1074 # found valid month
1075 tt = strptime(cert_time[3:], time_format)
1076 # return an integer, the previous mktime()-based implementation
1077 # returned a float (fractional seconds are always zero here).
1078 return timegm((tt[0], month_number) + tt[2:6])
Thomas Woutersed03b412007-08-28 21:37:11 +00001079
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080PEM_HEADER = "-----BEGIN CERTIFICATE-----"
1081PEM_FOOTER = "-----END CERTIFICATE-----"
1082
1083def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084 """Takes a certificate in binary DER format and returns the
1085 PEM version of it as a string."""
1086
Bill Janssen6e027db2007-11-15 22:23:56 +00001087 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
1088 return (PEM_HEADER + '\n' +
1089 textwrap.fill(f, 64) + '\n' +
1090 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
1092def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093 """Takes a certificate in ASCII PEM format and returns the
1094 DER-encoded version of it as a byte sequence"""
1095
1096 if not pem_cert_string.startswith(PEM_HEADER):
1097 raise ValueError("Invalid PEM encoding; must start with %s"
1098 % PEM_HEADER)
1099 if not pem_cert_string.strip().endswith(PEM_FOOTER):
1100 raise ValueError("Invalid PEM encoding; must end with %s"
1101 % PEM_FOOTER)
1102 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +00001103 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104
Antoine Pitrou94a5b662014-04-16 18:56:28 +02001105def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106 """Retrieve the certificate from the server at the specified address,
1107 and return it as a PEM-encoded string.
1108 If 'ca_certs' is specified, validate the server cert against it.
1109 If 'ssl_version' is specified, use it in the connection attempt."""
1110
1111 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +01001112 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001113 cert_reqs = CERT_REQUIRED
1114 else:
1115 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +01001116 context = _create_stdlib_context(ssl_version,
1117 cert_reqs=cert_reqs,
1118 cafile=ca_certs)
1119 with create_connection(addr) as sock:
1120 with context.wrap_socket(sock) as sslsock:
1121 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122 return DER_cert_to_PEM_cert(dercert)
1123
Guido van Rossum5b8b1552007-11-16 00:06:11 +00001124def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +02001125 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')