blob: 8c75f009c836acd109531bb1748dc019ca524e47 [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
Christian Heimes72d28502013-11-23 13:56:58 +010095from enum import Enum as _Enum
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 Pitrou41032a62011-10-27 23:56:55 +0200100from _ssl import _SSLContext
101from _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 Stinnerfcfed192015-01-06 13:54:58 +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_')
Victor Stinner00411422014-12-12 12:23:09 +0100124_import_symbols('PROTOCOL_')
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100125
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100126from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100127
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200128from _ssl import _OPENSSL_API_VERSION
129
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100130
Victor Stinner00411422014-12-12 12:23:09 +0100131_PROTOCOL_NAMES = {value: name for name, value in globals().items() if name.startswith('PROTOCOL_')}
Victor Stinner3de49192011-05-09 00:42:58 +0200132try:
133 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100134 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400135except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100136 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200137else:
138 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000139
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140try:
141 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400142except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100143 pass
144else:
145 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
146 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
147
Christian Heimes46bebee2013-06-09 19:03:31 +0200148if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100149 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200150
Antoine Pitrou15399c32011-04-28 19:23:55 +0200151from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100152from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000154import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000155
Andrew Svetlov0832af62012-12-18 23:10:48 +0200156
157socket_error = OSError # keep that public name in module namespace
158
Antoine Pitroud6494802011-07-21 01:11:30 +0200159if _ssl.HAS_TLS_UNIQUE:
160 CHANNEL_BINDING_TYPES = ['tls-unique']
161else:
162 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000163
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100164# Disable weak or insecure ciphers by default
165# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400166# Enable a better set of ciphers by default
167# This list has been explicitly chosen to:
168# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
169# * Prefer ECDHE over DHE for better performance
170# * Prefer any AES-GCM over any AES-CBC for better performance and security
171# * Then Use HIGH cipher suites as a fallback
172# * Then Use 3DES as fallback which is secure but slow
173# * Finally use RC4 as a fallback which is problematic but needed for
174# compatibility some times.
175# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
176# reasons
177_DEFAULT_CIPHERS = (
178 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
179 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
180 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
181)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100182
Donald Stufft6a2ba942014-03-23 19:05:28 -0400183# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400184# This list has been explicitly chosen to:
185# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
186# * Prefer ECDHE over DHE for better performance
187# * Prefer any AES-GCM over any AES-CBC for better performance and security
188# * Then Use HIGH cipher suites as a fallback
189# * Then Use 3DES as fallback which is secure but slow
190# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
191# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400192_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400193 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
194 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
195 '!eNULL:!MD5:!DSS:!RC4'
196)
Christian Heimes4c05b472013-11-23 15:58:30 +0100197
Thomas Woutersed03b412007-08-28 21:37:11 +0000198
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000199class CertificateError(ValueError):
200 pass
201
202
Georg Brandl72c98d32013-10-27 07:16:53 +0100203def _dnsname_match(dn, hostname, max_wildcards=1):
204 """Matching according to RFC 6125, section 6.4.3
205
206 http://tools.ietf.org/html/rfc6125#section-6.4.3
207 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000208 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100209 if not dn:
210 return False
211
212 leftmost, *remainder = dn.split(r'.')
213
214 wildcards = leftmost.count('*')
215 if wildcards > max_wildcards:
216 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300217 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100218 # policy among SSL implementations showed it to be a
219 # reasonable choice.
220 raise CertificateError(
221 "too many wildcards in certificate DNS name: " + repr(dn))
222
223 # speed up common case w/o wildcards
224 if not wildcards:
225 return dn.lower() == hostname.lower()
226
227 # RFC 6125, section 6.4.3, subitem 1.
228 # The client SHOULD NOT attempt to match a presented identifier in which
229 # the wildcard character comprises a label other than the left-most label.
230 if leftmost == '*':
231 # When '*' is a fragment by itself, it matches a non-empty dotless
232 # fragment.
233 pats.append('[^.]+')
234 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
235 # RFC 6125, section 6.4.3, subitem 3.
236 # The client SHOULD NOT attempt to match a presented identifier
237 # where the wildcard character is embedded within an A-label or
238 # U-label of an internationalized domain name.
239 pats.append(re.escape(leftmost))
240 else:
241 # Otherwise, '*' matches any dotless string, e.g. www*
242 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
243
244 # add the remaining fragments, ignore any wildcards
245 for frag in remainder:
246 pats.append(re.escape(frag))
247
248 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
249 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000250
251
252def match_hostname(cert, hostname):
253 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100254 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
255 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000256
257 CertificateError is raised on failure. On success, the function
258 returns nothing.
259 """
260 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100261 raise ValueError("empty or no certificate, match_hostname needs a "
262 "SSL socket or SSL context with either "
263 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000264 dnsnames = []
265 san = cert.get('subjectAltName', ())
266 for key, value in san:
267 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100268 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000269 return
270 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200271 if not dnsnames:
272 # The subject is only checked when there is no dNSName entry
273 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000274 for sub in cert.get('subject', ()):
275 for key, value in sub:
276 # XXX according to RFC 2818, the most specific Common Name
277 # must be used.
278 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100279 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000280 return
281 dnsnames.append(value)
282 if len(dnsnames) > 1:
283 raise CertificateError("hostname %r "
284 "doesn't match either of %s"
285 % (hostname, ', '.join(map(repr, dnsnames))))
286 elif len(dnsnames) == 1:
287 raise CertificateError("hostname %r "
288 "doesn't match %r"
289 % (hostname, dnsnames[0]))
290 else:
291 raise CertificateError("no appropriate commonName or "
292 "subjectAltName fields were found")
293
294
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100295DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200296 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
297 "openssl_capath")
298
299def get_default_verify_paths():
300 """Return paths to default cafile and capath.
301 """
302 parts = _ssl.get_default_verify_paths()
303
304 # environment vars shadow paths
305 cafile = os.environ.get(parts[0], parts[1])
306 capath = os.environ.get(parts[2], parts[3])
307
308 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
309 capath if os.path.isdir(capath) else None,
310 *parts)
311
312
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100313class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
314 """ASN.1 object identifier lookup
315 """
316 __slots__ = ()
317
318 def __new__(cls, oid):
319 return super().__new__(cls, *_txt2obj(oid, name=False))
320
321 @classmethod
322 def fromnid(cls, nid):
323 """Create _ASN1Object from OpenSSL numeric ID
324 """
325 return super().__new__(cls, *_nid2obj(nid))
326
327 @classmethod
328 def fromname(cls, name):
329 """Create _ASN1Object from short name, long name or OID
330 """
331 return super().__new__(cls, *_txt2obj(name, name=True))
332
333
Christian Heimes72d28502013-11-23 13:56:58 +0100334class Purpose(_ASN1Object, _Enum):
335 """SSLContext purpose flags with X509v3 Extended Key Usage objects
336 """
337 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
338 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
339
340
Antoine Pitrou152efa22010-05-16 18:19:27 +0000341class SSLContext(_SSLContext):
342 """An SSLContext holds various SSL-related configuration options and
343 data, such as certificates and possibly a private key."""
344
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100345 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100346 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347
348 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100349 self = _SSLContext.__new__(cls, protocol)
350 if protocol != _SSLv2_IF_EXISTS:
351 self.set_ciphers(_DEFAULT_CIPHERS)
352 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000353
354 def __init__(self, protocol):
355 self.protocol = protocol
356
357 def wrap_socket(self, sock, server_side=False,
358 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000359 suppress_ragged_eofs=True,
360 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000361 return SSLSocket(sock=sock, server_side=server_side,
362 do_handshake_on_connect=do_handshake_on_connect,
363 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000364 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000365 _context=self)
366
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100367 def set_npn_protocols(self, npn_protocols):
368 protos = bytearray()
369 for protocol in npn_protocols:
370 b = bytes(protocol, 'ascii')
371 if len(b) == 0 or len(b) > 255:
372 raise SSLError('NPN protocols must be 1 to 255 in length')
373 protos.append(len(b))
374 protos.extend(b)
375
376 self._set_npn_protocols(protos)
377
Christian Heimes72d28502013-11-23 13:56:58 +0100378 def _load_windows_store_certs(self, storename, purpose):
379 certs = bytearray()
380 for cert, encoding, trust in enum_certificates(storename):
381 # CA certs are never PKCS#7 encoded
382 if encoding == "x509_asn":
383 if trust is True or purpose.oid in trust:
384 certs.extend(cert)
385 self.load_verify_locations(cadata=certs)
386 return certs
387
388 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
389 if not isinstance(purpose, _ASN1Object):
390 raise TypeError(purpose)
391 if sys.platform == "win32":
392 for storename in self._windows_cert_stores:
393 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400394 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100395
Antoine Pitrou152efa22010-05-16 18:19:27 +0000396
Christian Heimes4c05b472013-11-23 15:58:30 +0100397def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
398 capath=None, cadata=None):
399 """Create a SSLContext object with default settings.
400
401 NOTE: The protocol and settings may change anytime without prior
402 deprecation. The values represent a fair balance between maximum
403 compatibility and security.
404 """
405 if not isinstance(purpose, _ASN1Object):
406 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400407
408 context = SSLContext(PROTOCOL_SSLv23)
409
Christian Heimes4c05b472013-11-23 15:58:30 +0100410 # SSLv2 considered harmful.
411 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400412
413 # SSLv3 has problematic security and is only required for really old
414 # clients such as IE6 on Windows XP
415 context.options |= OP_NO_SSLv3
416
Christian Heimesdec813f2013-11-28 08:06:54 +0100417 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
418 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400419
Christian Heimes4c05b472013-11-23 15:58:30 +0100420 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400421 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100422 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100423 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400424 elif purpose == Purpose.CLIENT_AUTH:
425 # Prefer the server's ciphers by default so that we get stronger
426 # encryption
427 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
428
429 # Use single use keys in order to improve forward secrecy
430 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
431 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
432
433 # disallow ciphers with known vulnerabilities
434 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
435
Christian Heimes4c05b472013-11-23 15:58:30 +0100436 if cafile or capath or cadata:
437 context.load_verify_locations(cafile, capath, cadata)
438 elif context.verify_mode != CERT_NONE:
439 # no explicit cafile, capath or cadata but the verify mode is
440 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
441 # root CA certificates for the given purpose. This may fail silently.
442 context.load_default_certs(purpose)
443 return context
444
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500445def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100446 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100447 certfile=None, keyfile=None,
448 cafile=None, capath=None, cadata=None):
449 """Create a SSLContext object for Python stdlib modules
450
451 All Python stdlib modules shall use this function to create SSLContext
452 objects in order to keep common settings in one place. The configuration
453 is less restrict than create_default_context()'s to increase backward
454 compatibility.
455 """
456 if not isinstance(purpose, _ASN1Object):
457 raise TypeError(purpose)
458
459 context = SSLContext(protocol)
460 # SSLv2 considered harmful.
461 context.options |= OP_NO_SSLv2
Antoine Pitroua21de3d2014-10-17 19:28:30 +0200462 # SSLv3 has problematic security and is only required for really old
463 # clients such as IE6 on Windows XP
464 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100465
466 if cert_reqs is not None:
467 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100468 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100469
470 if keyfile and not certfile:
471 raise ValueError("certfile must be specified")
472 if certfile or keyfile:
473 context.load_cert_chain(certfile, keyfile)
474
475 # load CA root certs
476 if cafile or capath or cadata:
477 context.load_verify_locations(cafile, capath, cadata)
478 elif context.verify_mode != CERT_NONE:
479 # no explicit cafile, capath or cadata but the verify mode is
480 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
481 # root CA certificates for the given purpose. This may fail silently.
482 context.load_default_certs(purpose)
483
484 return context
485
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500486# Used by http.client if no context is explicitly passed.
487_create_default_https_context = create_default_context
488
489
490# Backwards compatibility alias, even though it's not a public name.
491_create_stdlib_context = _create_unverified_context
492
493
Antoine Pitrou152efa22010-05-16 18:19:27 +0000494class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000495 """This class implements a subtype of socket.socket that wraps
496 the underlying OS socket in an SSL context when necessary, and
497 provides read and write methods over that channel."""
498
Bill Janssen6e027db2007-11-15 22:23:56 +0000499 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000500 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000501 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
502 do_handshake_on_connect=True,
503 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100504 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000505 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000506 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000507
Antoine Pitrou152efa22010-05-16 18:19:27 +0000508 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100509 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000510 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000511 if server_side and not certfile:
512 raise ValueError("certfile must be specified for server-side "
513 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000514 if keyfile and not certfile:
515 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000516 if certfile and not keyfile:
517 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100518 self._context = SSLContext(ssl_version)
519 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000520 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100521 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000522 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100523 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100524 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100525 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000526 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100527 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000528 self.keyfile = keyfile
529 self.certfile = certfile
530 self.cert_reqs = cert_reqs
531 self.ssl_version = ssl_version
532 self.ca_certs = ca_certs
533 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100534 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
535 # mixed in.
536 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
537 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000538 if server_side and server_hostname:
539 raise ValueError("server_hostname can only be specified "
540 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100541 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600542 raise ValueError("check_hostname requires server_hostname")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000543 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000544 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000545 self.do_handshake_on_connect = do_handshake_on_connect
546 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000547 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000548 socket.__init__(self,
549 family=sock.family,
550 type=sock.type,
551 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000552 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000553 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000554 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000555 elif fileno is not None:
556 socket.__init__(self, fileno=fileno)
557 else:
558 socket.__init__(self, family=family, type=type, proto=proto)
559
Antoine Pitrou242db722013-05-01 20:52:07 +0200560 # See if we are connected
561 try:
562 self.getpeername()
563 except OSError as e:
564 if e.errno != errno.ENOTCONN:
565 raise
566 connected = False
567 else:
568 connected = True
569
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000570 self._closed = False
571 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000572 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000573 if connected:
574 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000575 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100576 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000577 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000578 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000579 timeout = self.gettimeout()
580 if timeout == 0.0:
581 # non-blocking
582 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000583 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000584
Christian Heimes1aa9a752013-12-02 02:41:19 +0100585 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000586 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100587 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200588
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100589 @property
590 def context(self):
591 return self._context
592
593 @context.setter
594 def context(self, ctx):
595 self._context = ctx
596 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000597
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000598 def dup(self):
599 raise NotImplemented("Can't dup() %s instances" %
600 self.__class__.__name__)
601
Bill Janssen6e027db2007-11-15 22:23:56 +0000602 def _checkClosed(self, msg=None):
603 # raise an exception here if you wish to check for spurious closes
604 pass
605
Antoine Pitrou242db722013-05-01 20:52:07 +0200606 def _check_connected(self):
607 if not self._connected:
608 # getpeername() will raise ENOTCONN if the socket is really
609 # not connected; note that we can be connected even without
610 # _connected being set, e.g. if connect() first returned
611 # EAGAIN.
612 self.getpeername()
613
Bill Janssen54cc54c2007-12-14 22:08:56 +0000614 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000615 """Read up to LEN bytes and return them.
616 Return zero-length string on EOF."""
617
Bill Janssen6e027db2007-11-15 22:23:56 +0000618 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200619 if not self._sslobj:
620 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000621 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000622 if buffer is not None:
623 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000624 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000625 v = self._sslobj.read(len or 1024)
626 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000627 except SSLError as x:
628 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000629 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000630 return 0
631 else:
632 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000633 else:
634 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000635
636 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000637 """Write DATA to the underlying SSL channel. Returns
638 number of bytes of DATA actually transmitted."""
639
Bill Janssen6e027db2007-11-15 22:23:56 +0000640 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200641 if not self._sslobj:
642 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000643 return self._sslobj.write(data)
644
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000646 """Returns a formatted version of the data in the
647 certificate provided by the other end of the SSL channel.
648 Return None if no certificate was provided, {} if a
649 certificate was provided, but not validated."""
650
Bill Janssen6e027db2007-11-15 22:23:56 +0000651 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200652 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653 return self._sslobj.peer_certificate(binary_form)
654
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100655 def selected_npn_protocol(self):
656 self._checkClosed()
657 if not self._sslobj or not _ssl.HAS_NPN:
658 return None
659 else:
660 return self._sslobj.selected_npn_protocol()
661
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000662 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000663 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664 if not self._sslobj:
665 return None
666 else:
667 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000668
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100669 def compression(self):
670 self._checkClosed()
671 if not self._sslobj:
672 return None
673 else:
674 return self._sslobj.compression()
675
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000676 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000677 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000678 if self._sslobj:
679 if flags != 0:
680 raise ValueError(
681 "non-zero flags not allowed in calls to send() on %s" %
682 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200683 try:
684 v = self._sslobj.write(data)
685 except SSLError as x:
686 if x.args[0] == SSL_ERROR_WANT_READ:
687 return 0
688 elif x.args[0] == SSL_ERROR_WANT_WRITE:
689 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000690 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200691 raise
692 else:
693 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000694 else:
695 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000696
Antoine Pitroua468adc2010-09-14 14:43:44 +0000697 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000698 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000699 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000700 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000701 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000702 elif addr is None:
703 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000704 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000705 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000706
Nick Coghlan513886a2011-08-28 00:00:27 +1000707 def sendmsg(self, *args, **kwargs):
708 # Ensure programs don't send data unencrypted if they try to
709 # use this method.
710 raise NotImplementedError("sendmsg not allowed on instances of %s" %
711 self.__class__)
712
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000713 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000714 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000715 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000716 if flags != 0:
717 raise ValueError(
718 "non-zero flags not allowed in calls to sendall() on %s" %
719 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000720 amount = len(data)
721 count = 0
722 while (count < amount):
723 v = self.send(data[count:])
724 count += v
725 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000726 else:
727 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000728
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000729 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000730 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000731 if self._sslobj:
732 if flags != 0:
733 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000734 "non-zero flags not allowed in calls to recv() on %s" %
735 self.__class__)
736 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000737 else:
738 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000740 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000741 self._checkClosed()
742 if buffer and (nbytes is None):
743 nbytes = len(buffer)
744 elif nbytes is None:
745 nbytes = 1024
746 if self._sslobj:
747 if flags != 0:
748 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000749 "non-zero flags not allowed in calls to recv_into() on %s" %
750 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000751 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000752 else:
753 return socket.recv_into(self, buffer, nbytes, flags)
754
Antoine Pitroua468adc2010-09-14 14:43:44 +0000755 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000756 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000757 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000758 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000759 self.__class__)
760 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000761 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000762
Bill Janssen58afe4c2008-09-08 16:45:19 +0000763 def recvfrom_into(self, buffer, nbytes=None, flags=0):
764 self._checkClosed()
765 if self._sslobj:
766 raise ValueError("recvfrom_into not allowed on instances of %s" %
767 self.__class__)
768 else:
769 return socket.recvfrom_into(self, buffer, nbytes, flags)
770
Nick Coghlan513886a2011-08-28 00:00:27 +1000771 def recvmsg(self, *args, **kwargs):
772 raise NotImplementedError("recvmsg not allowed on instances of %s" %
773 self.__class__)
774
775 def recvmsg_into(self, *args, **kwargs):
776 raise NotImplementedError("recvmsg_into not allowed on instances of "
777 "%s" % self.__class__)
778
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000779 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000780 self._checkClosed()
781 if self._sslobj:
782 return self._sslobj.pending()
783 else:
784 return 0
785
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000786 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000787 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000789 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000790
Ezio Melottidc55e672010-01-18 09:15:14 +0000791 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000792 if self._sslobj:
793 s = self._sslobj.shutdown()
794 self._sslobj = None
795 return s
796 else:
797 raise ValueError("No SSL wrapper around " + str(self))
798
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000799 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000801 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000802
Bill Janssen48dc27c2007-12-05 03:38:10 +0000803 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000804 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200805 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000806 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000807 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000808 if timeout == 0.0 and block:
809 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000810 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000811 finally:
812 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000813
Christian Heimes1aa9a752013-12-02 02:41:19 +0100814 if self.context.check_hostname:
Christian Heimes1da3ba82013-12-04 20:46:20 +0100815 if not self.server_hostname:
816 raise ValueError("check_hostname needs server_hostname "
817 "argument")
818 match_hostname(self.getpeercert(), self.server_hostname)
Christian Heimes1aa9a752013-12-02 02:41:19 +0100819
Antoine Pitroub4410db2011-05-18 18:51:06 +0200820 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000821 if self.server_side:
822 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000823 # Here we assume that the socket is client-side, and not
824 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000825 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000827 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000828 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200829 if connect_ex:
830 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000831 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200832 rc = None
833 socket.connect(self, addr)
834 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200835 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200836 if self.do_handshake_on_connect:
837 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200838 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +0100839 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +0200840 self._sslobj = None
841 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000842
843 def connect(self, addr):
844 """Connects to remote ADDR, and then wraps the connection in
845 an SSL channel."""
846 self._real_connect(addr, False)
847
848 def connect_ex(self, addr):
849 """Connects to remote ADDR, and then wraps the connection in
850 an SSL channel."""
851 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000852
853 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000854 """Accepts a new connection from a remote client, and returns
855 a tuple containing that new connection wrapped with a server-side
856 SSL channel, and the address of the remote client."""
857
858 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100859 newsock = self.context.wrap_socket(newsock,
860 do_handshake_on_connect=self.do_handshake_on_connect,
861 suppress_ragged_eofs=self.suppress_ragged_eofs,
862 server_side=True)
863 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroud6494802011-07-21 01:11:30 +0200865 def get_channel_binding(self, cb_type="tls-unique"):
866 """Get channel binding data for current connection. Raise ValueError
867 if the requested `cb_type` is not supported. Return bytes of the data
868 or None if the data is not available (e.g. before the handshake).
869 """
870 if cb_type not in CHANNEL_BINDING_TYPES:
871 raise ValueError("Unsupported channel binding type")
872 if cb_type != "tls-unique":
873 raise NotImplementedError(
874 "{0} channel binding type not implemented"
875 .format(cb_type))
876 if self._sslobj is None:
877 return None
878 return self._sslobj.tls_unique_cb()
879
Bill Janssen54cc54c2007-12-14 22:08:56 +0000880
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881def wrap_socket(sock, keyfile=None, certfile=None,
882 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000883 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000884 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100885 suppress_ragged_eofs=True,
886 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Bill Janssen6e027db2007-11-15 22:23:56 +0000888 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000890 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000891 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000892 suppress_ragged_eofs=suppress_ragged_eofs,
893 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Thomas Woutersed03b412007-08-28 21:37:11 +0000895# some utility functions
896
897def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000898 """Takes a date-time string in standard ASN1_print form
899 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
900 a Python time value in seconds past the epoch."""
901
Thomas Woutersed03b412007-08-28 21:37:11 +0000902 import time
903 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
904
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905PEM_HEADER = "-----BEGIN CERTIFICATE-----"
906PEM_FOOTER = "-----END CERTIFICATE-----"
907
908def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909 """Takes a certificate in binary DER format and returns the
910 PEM version of it as a string."""
911
Bill Janssen6e027db2007-11-15 22:23:56 +0000912 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
913 return (PEM_HEADER + '\n' +
914 textwrap.fill(f, 64) + '\n' +
915 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000916
917def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918 """Takes a certificate in ASCII PEM format and returns the
919 DER-encoded version of it as a byte sequence"""
920
921 if not pem_cert_string.startswith(PEM_HEADER):
922 raise ValueError("Invalid PEM encoding; must start with %s"
923 % PEM_HEADER)
924 if not pem_cert_string.strip().endswith(PEM_FOOTER):
925 raise ValueError("Invalid PEM encoding; must end with %s"
926 % PEM_FOOTER)
927 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000928 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Victor Stinner9d017172015-01-06 12:21:26 +0100930def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931 """Retrieve the certificate from the server at the specified address,
932 and return it as a PEM-encoded string.
933 If 'ca_certs' is specified, validate the server cert against it.
934 If 'ssl_version' is specified, use it in the connection attempt."""
935
936 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +0100937 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938 cert_reqs = CERT_REQUIRED
939 else:
940 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +0100941 context = _create_stdlib_context(ssl_version,
942 cert_reqs=cert_reqs,
943 cafile=ca_certs)
944 with create_connection(addr) as sock:
945 with context.wrap_socket(sock) as sslsock:
946 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947 return DER_cert_to_PEM_cert(dercert)
948
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000949def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200950 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')