blob: 3d4997caf05b4b491f4b8ff6672a1e686f7edd72 [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 Stinner99c8b162011-05-24 12:05:19 +0200109from _ssl import RAND_status, RAND_egd, RAND_add, RAND_bytes, RAND_pseudo_bytes
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100110
111def _import_symbols(prefix):
112 for n in dir(_ssl):
113 if n.startswith(prefix):
114 globals()[n] = getattr(_ssl, n)
115
116_import_symbols('OP_')
117_import_symbols('ALERT_DESCRIPTION_')
118_import_symbols('SSL_ERROR_')
119
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100120from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100121
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100122from _ssl import PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200123from _ssl import _OPENSSL_API_VERSION
124
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100125
Victor Stinner3de49192011-05-09 00:42:58 +0200126_PROTOCOL_NAMES = {
127 PROTOCOL_TLSv1: "TLSv1",
128 PROTOCOL_SSLv23: "SSLv23",
129 PROTOCOL_SSLv3: "SSLv3",
130}
131try:
132 from _ssl import PROTOCOL_SSLv2
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100133 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Brett Cannoncd171c82013-07-04 17:43:24 -0400134except ImportError:
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100135 _SSLv2_IF_EXISTS = None
Victor Stinner3de49192011-05-09 00:42:58 +0200136else:
137 _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
Thomas Woutersed03b412007-08-28 21:37:11 +0000138
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100139try:
140 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
Brett Cannoncd171c82013-07-04 17:43:24 -0400141except ImportError:
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142 pass
143else:
144 _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
145 _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
146
Christian Heimes46bebee2013-06-09 19:03:31 +0200147if sys.platform == "win32":
Christian Heimes44109d72013-11-22 01:51:30 +0100148 from _ssl import enum_certificates, enum_crls
Christian Heimes46bebee2013-06-09 19:03:31 +0200149
Antoine Pitrou15399c32011-04-28 19:23:55 +0200150from socket import socket, AF_INET, SOCK_STREAM, create_connection
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100151from socket import SOL_SOCKET, SO_TYPE
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000152import base64 # for DER-to-PEM translation
Antoine Pitroude8cf322010-04-26 17:29:05 +0000153import errno
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000154
Andrew Svetlov0832af62012-12-18 23:10:48 +0200155
156socket_error = OSError # keep that public name in module namespace
157
Antoine Pitroud6494802011-07-21 01:11:30 +0200158if _ssl.HAS_TLS_UNIQUE:
159 CHANNEL_BINDING_TYPES = ['tls-unique']
160else:
161 CHANNEL_BINDING_TYPES = []
Thomas Woutersed03b412007-08-28 21:37:11 +0000162
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100163# Disable weak or insecure ciphers by default
164# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Donald Stufft79ccaa22014-03-21 21:33:34 -0400165# Enable a better set of ciphers by default
166# This list has been explicitly chosen to:
167# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
168# * Prefer ECDHE over DHE for better performance
169# * Prefer any AES-GCM over any AES-CBC for better performance and security
170# * Then Use HIGH cipher suites as a fallback
171# * Then Use 3DES as fallback which is secure but slow
172# * Finally use RC4 as a fallback which is problematic but needed for
173# compatibility some times.
174# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
175# reasons
176_DEFAULT_CIPHERS = (
177 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
178 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
179 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
180)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100181
Donald Stufft6a2ba942014-03-23 19:05:28 -0400182# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400183# This list has been explicitly chosen to:
184# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
185# * Prefer ECDHE over DHE for better performance
186# * Prefer any AES-GCM over any AES-CBC for better performance and security
187# * Then Use HIGH cipher suites as a fallback
188# * Then Use 3DES as fallback which is secure but slow
189# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
190# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400191_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400192 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
193 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
194 '!eNULL:!MD5:!DSS:!RC4'
195)
Christian Heimes4c05b472013-11-23 15:58:30 +0100196
Thomas Woutersed03b412007-08-28 21:37:11 +0000197
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000198class CertificateError(ValueError):
199 pass
200
201
Georg Brandl72c98d32013-10-27 07:16:53 +0100202def _dnsname_match(dn, hostname, max_wildcards=1):
203 """Matching according to RFC 6125, section 6.4.3
204
205 http://tools.ietf.org/html/rfc6125#section-6.4.3
206 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000207 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100208 if not dn:
209 return False
210
211 leftmost, *remainder = dn.split(r'.')
212
213 wildcards = leftmost.count('*')
214 if wildcards > max_wildcards:
215 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300216 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100217 # policy among SSL implementations showed it to be a
218 # reasonable choice.
219 raise CertificateError(
220 "too many wildcards in certificate DNS name: " + repr(dn))
221
222 # speed up common case w/o wildcards
223 if not wildcards:
224 return dn.lower() == hostname.lower()
225
226 # RFC 6125, section 6.4.3, subitem 1.
227 # The client SHOULD NOT attempt to match a presented identifier in which
228 # the wildcard character comprises a label other than the left-most label.
229 if leftmost == '*':
230 # When '*' is a fragment by itself, it matches a non-empty dotless
231 # fragment.
232 pats.append('[^.]+')
233 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
234 # RFC 6125, section 6.4.3, subitem 3.
235 # The client SHOULD NOT attempt to match a presented identifier
236 # where the wildcard character is embedded within an A-label or
237 # U-label of an internationalized domain name.
238 pats.append(re.escape(leftmost))
239 else:
240 # Otherwise, '*' matches any dotless string, e.g. www*
241 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
242
243 # add the remaining fragments, ignore any wildcards
244 for frag in remainder:
245 pats.append(re.escape(frag))
246
247 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
248 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000249
250
251def match_hostname(cert, hostname):
252 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100253 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
254 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000255
256 CertificateError is raised on failure. On success, the function
257 returns nothing.
258 """
259 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100260 raise ValueError("empty or no certificate, match_hostname needs a "
261 "SSL socket or SSL context with either "
262 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000263 dnsnames = []
264 san = cert.get('subjectAltName', ())
265 for key, value in san:
266 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100267 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000268 return
269 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200270 if not dnsnames:
271 # The subject is only checked when there is no dNSName entry
272 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000273 for sub in cert.get('subject', ()):
274 for key, value in sub:
275 # XXX according to RFC 2818, the most specific Common Name
276 # must be used.
277 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100278 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000279 return
280 dnsnames.append(value)
281 if len(dnsnames) > 1:
282 raise CertificateError("hostname %r "
283 "doesn't match either of %s"
284 % (hostname, ', '.join(map(repr, dnsnames))))
285 elif len(dnsnames) == 1:
286 raise CertificateError("hostname %r "
287 "doesn't match %r"
288 % (hostname, dnsnames[0]))
289 else:
290 raise CertificateError("no appropriate commonName or "
291 "subjectAltName fields were found")
292
293
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100294DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200295 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
296 "openssl_capath")
297
298def get_default_verify_paths():
299 """Return paths to default cafile and capath.
300 """
301 parts = _ssl.get_default_verify_paths()
302
303 # environment vars shadow paths
304 cafile = os.environ.get(parts[0], parts[1])
305 capath = os.environ.get(parts[2], parts[3])
306
307 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
308 capath if os.path.isdir(capath) else None,
309 *parts)
310
311
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100312class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
313 """ASN.1 object identifier lookup
314 """
315 __slots__ = ()
316
317 def __new__(cls, oid):
318 return super().__new__(cls, *_txt2obj(oid, name=False))
319
320 @classmethod
321 def fromnid(cls, nid):
322 """Create _ASN1Object from OpenSSL numeric ID
323 """
324 return super().__new__(cls, *_nid2obj(nid))
325
326 @classmethod
327 def fromname(cls, name):
328 """Create _ASN1Object from short name, long name or OID
329 """
330 return super().__new__(cls, *_txt2obj(name, name=True))
331
332
Christian Heimes72d28502013-11-23 13:56:58 +0100333class Purpose(_ASN1Object, _Enum):
334 """SSLContext purpose flags with X509v3 Extended Key Usage objects
335 """
336 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
337 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
338
339
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340class SSLContext(_SSLContext):
341 """An SSLContext holds various SSL-related configuration options and
342 data, such as certificates and possibly a private key."""
343
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100344 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100345 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000346
347 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100348 self = _SSLContext.__new__(cls, protocol)
349 if protocol != _SSLv2_IF_EXISTS:
350 self.set_ciphers(_DEFAULT_CIPHERS)
351 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000352
353 def __init__(self, protocol):
354 self.protocol = protocol
355
356 def wrap_socket(self, sock, server_side=False,
357 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000358 suppress_ragged_eofs=True,
359 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000360 return SSLSocket(sock=sock, server_side=server_side,
361 do_handshake_on_connect=do_handshake_on_connect,
362 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000363 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364 _context=self)
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
Christian Heimes72d28502013-11-23 13:56:58 +0100377 def _load_windows_store_certs(self, storename, purpose):
378 certs = bytearray()
379 for cert, encoding, trust in enum_certificates(storename):
380 # CA certs are never PKCS#7 encoded
381 if encoding == "x509_asn":
382 if trust is True or purpose.oid in trust:
383 certs.extend(cert)
384 self.load_verify_locations(cadata=certs)
385 return certs
386
387 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
388 if not isinstance(purpose, _ASN1Object):
389 raise TypeError(purpose)
390 if sys.platform == "win32":
391 for storename in self._windows_cert_stores:
392 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400393 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100394
Antoine Pitrou152efa22010-05-16 18:19:27 +0000395
Christian Heimes4c05b472013-11-23 15:58:30 +0100396def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
397 capath=None, cadata=None):
398 """Create a SSLContext object with default settings.
399
400 NOTE: The protocol and settings may change anytime without prior
401 deprecation. The values represent a fair balance between maximum
402 compatibility and security.
403 """
404 if not isinstance(purpose, _ASN1Object):
405 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400406
407 context = SSLContext(PROTOCOL_SSLv23)
408
Christian Heimes4c05b472013-11-23 15:58:30 +0100409 # SSLv2 considered harmful.
410 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400411
412 # SSLv3 has problematic security and is only required for really old
413 # clients such as IE6 on Windows XP
414 context.options |= OP_NO_SSLv3
415
Christian Heimesdec813f2013-11-28 08:06:54 +0100416 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
417 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400418
Christian Heimes4c05b472013-11-23 15:58:30 +0100419 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400420 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100421 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100422 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400423 elif purpose == Purpose.CLIENT_AUTH:
424 # Prefer the server's ciphers by default so that we get stronger
425 # encryption
426 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
427
428 # Use single use keys in order to improve forward secrecy
429 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
430 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
431
432 # disallow ciphers with known vulnerabilities
433 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
434
Christian Heimes4c05b472013-11-23 15:58:30 +0100435 if cafile or capath or cadata:
436 context.load_verify_locations(cafile, capath, cadata)
437 elif context.verify_mode != CERT_NONE:
438 # no explicit cafile, capath or cadata but the verify mode is
439 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
440 # root CA certificates for the given purpose. This may fail silently.
441 context.load_default_certs(purpose)
442 return context
443
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500444def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100445 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100446 certfile=None, keyfile=None,
447 cafile=None, capath=None, cadata=None):
448 """Create a SSLContext object for Python stdlib modules
449
450 All Python stdlib modules shall use this function to create SSLContext
451 objects in order to keep common settings in one place. The configuration
452 is less restrict than create_default_context()'s to increase backward
453 compatibility.
454 """
455 if not isinstance(purpose, _ASN1Object):
456 raise TypeError(purpose)
457
458 context = SSLContext(protocol)
459 # SSLv2 considered harmful.
460 context.options |= OP_NO_SSLv2
Antoine Pitroua21de3d2014-10-17 19:28:30 +0200461 # SSLv3 has problematic security and is only required for really old
462 # clients such as IE6 on Windows XP
463 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100464
465 if cert_reqs is not None:
466 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100467 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100468
469 if keyfile and not certfile:
470 raise ValueError("certfile must be specified")
471 if certfile or keyfile:
472 context.load_cert_chain(certfile, keyfile)
473
474 # load CA root certs
475 if cafile or capath or cadata:
476 context.load_verify_locations(cafile, capath, cadata)
477 elif context.verify_mode != CERT_NONE:
478 # no explicit cafile, capath or cadata but the verify mode is
479 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
480 # root CA certificates for the given purpose. This may fail silently.
481 context.load_default_certs(purpose)
482
483 return context
484
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500485# Used by http.client if no context is explicitly passed.
486_create_default_https_context = create_default_context
487
488
489# Backwards compatibility alias, even though it's not a public name.
490_create_stdlib_context = _create_unverified_context
491
492
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000494 """This class implements a subtype of socket.socket that wraps
495 the underlying OS socket in an SSL context when necessary, and
496 provides read and write methods over that channel."""
497
Bill Janssen6e027db2007-11-15 22:23:56 +0000498 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000499 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000500 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
501 do_handshake_on_connect=True,
502 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100503 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000504 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000506
Antoine Pitrou152efa22010-05-16 18:19:27 +0000507 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100508 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000509 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000510 if server_side and not certfile:
511 raise ValueError("certfile must be specified for server-side "
512 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000513 if keyfile and not certfile:
514 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000515 if certfile and not keyfile:
516 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100517 self._context = SSLContext(ssl_version)
518 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000519 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100520 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100522 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100523 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100524 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000525 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100526 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000527 self.keyfile = keyfile
528 self.certfile = certfile
529 self.cert_reqs = cert_reqs
530 self.ssl_version = ssl_version
531 self.ca_certs = ca_certs
532 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100533 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
534 # mixed in.
535 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
536 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000537 if server_side and server_hostname:
538 raise ValueError("server_hostname can only be specified "
539 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100540 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600541 raise ValueError("check_hostname requires server_hostname")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000542 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000543 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000544 self.do_handshake_on_connect = do_handshake_on_connect
545 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000546 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000547 socket.__init__(self,
548 family=sock.family,
549 type=sock.type,
550 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000551 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000552 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000553 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000554 elif fileno is not None:
555 socket.__init__(self, fileno=fileno)
556 else:
557 socket.__init__(self, family=family, type=type, proto=proto)
558
Antoine Pitrou242db722013-05-01 20:52:07 +0200559 # See if we are connected
560 try:
561 self.getpeername()
562 except OSError as e:
563 if e.errno != errno.ENOTCONN:
564 raise
565 connected = False
566 else:
567 connected = True
568
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000569 self._closed = False
570 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000571 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000572 if connected:
573 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000574 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100575 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000576 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000577 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000578 timeout = self.gettimeout()
579 if timeout == 0.0:
580 # non-blocking
581 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000582 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000583
Christian Heimes1aa9a752013-12-02 02:41:19 +0100584 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000585 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100586 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200587
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100588 @property
589 def context(self):
590 return self._context
591
592 @context.setter
593 def context(self, ctx):
594 self._context = ctx
595 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000596
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000597 def dup(self):
598 raise NotImplemented("Can't dup() %s instances" %
599 self.__class__.__name__)
600
Bill Janssen6e027db2007-11-15 22:23:56 +0000601 def _checkClosed(self, msg=None):
602 # raise an exception here if you wish to check for spurious closes
603 pass
604
Antoine Pitrou242db722013-05-01 20:52:07 +0200605 def _check_connected(self):
606 if not self._connected:
607 # getpeername() will raise ENOTCONN if the socket is really
608 # not connected; note that we can be connected even without
609 # _connected being set, e.g. if connect() first returned
610 # EAGAIN.
611 self.getpeername()
612
Bill Janssen54cc54c2007-12-14 22:08:56 +0000613 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000614 """Read up to LEN bytes and return them.
615 Return zero-length string on EOF."""
616
Bill Janssen6e027db2007-11-15 22:23:56 +0000617 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200618 if not self._sslobj:
619 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000620 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000621 if buffer is not None:
622 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000623 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000624 v = self._sslobj.read(len or 1024)
625 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000626 except SSLError as x:
627 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000628 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000629 return 0
630 else:
631 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000632 else:
633 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000634
635 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000636 """Write DATA to the underlying SSL channel. Returns
637 number of bytes of DATA actually transmitted."""
638
Bill Janssen6e027db2007-11-15 22:23:56 +0000639 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200640 if not self._sslobj:
641 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000642 return self._sslobj.write(data)
643
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000645 """Returns a formatted version of the data in the
646 certificate provided by the other end of the SSL channel.
647 Return None if no certificate was provided, {} if a
648 certificate was provided, but not validated."""
649
Bill Janssen6e027db2007-11-15 22:23:56 +0000650 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200651 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652 return self._sslobj.peer_certificate(binary_form)
653
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100654 def selected_npn_protocol(self):
655 self._checkClosed()
656 if not self._sslobj or not _ssl.HAS_NPN:
657 return None
658 else:
659 return self._sslobj.selected_npn_protocol()
660
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000661 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000662 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663 if not self._sslobj:
664 return None
665 else:
666 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000667
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100668 def compression(self):
669 self._checkClosed()
670 if not self._sslobj:
671 return None
672 else:
673 return self._sslobj.compression()
674
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000675 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000676 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000677 if self._sslobj:
678 if flags != 0:
679 raise ValueError(
680 "non-zero flags not allowed in calls to send() on %s" %
681 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200682 try:
683 v = self._sslobj.write(data)
684 except SSLError as x:
685 if x.args[0] == SSL_ERROR_WANT_READ:
686 return 0
687 elif x.args[0] == SSL_ERROR_WANT_WRITE:
688 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000689 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200690 raise
691 else:
692 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000693 else:
694 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000695
Antoine Pitroua468adc2010-09-14 14:43:44 +0000696 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000697 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000698 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000699 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000700 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000701 elif addr is None:
702 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000703 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000704 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000705
Nick Coghlan513886a2011-08-28 00:00:27 +1000706 def sendmsg(self, *args, **kwargs):
707 # Ensure programs don't send data unencrypted if they try to
708 # use this method.
709 raise NotImplementedError("sendmsg not allowed on instances of %s" %
710 self.__class__)
711
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000712 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000713 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000714 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000715 if flags != 0:
716 raise ValueError(
717 "non-zero flags not allowed in calls to sendall() on %s" %
718 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000719 amount = len(data)
720 count = 0
721 while (count < amount):
722 v = self.send(data[count:])
723 count += v
724 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000725 else:
726 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000727
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000728 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000729 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000730 if self._sslobj:
731 if flags != 0:
732 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000733 "non-zero flags not allowed in calls to recv() on %s" %
734 self.__class__)
735 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000736 else:
737 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000738
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000739 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000740 self._checkClosed()
741 if buffer and (nbytes is None):
742 nbytes = len(buffer)
743 elif nbytes is None:
744 nbytes = 1024
745 if self._sslobj:
746 if flags != 0:
747 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000748 "non-zero flags not allowed in calls to recv_into() on %s" %
749 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000750 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000751 else:
752 return socket.recv_into(self, buffer, nbytes, flags)
753
Antoine Pitroua468adc2010-09-14 14:43:44 +0000754 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000755 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000756 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000757 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000758 self.__class__)
759 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000760 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000761
Bill Janssen58afe4c2008-09-08 16:45:19 +0000762 def recvfrom_into(self, buffer, nbytes=None, flags=0):
763 self._checkClosed()
764 if self._sslobj:
765 raise ValueError("recvfrom_into not allowed on instances of %s" %
766 self.__class__)
767 else:
768 return socket.recvfrom_into(self, buffer, nbytes, flags)
769
Nick Coghlan513886a2011-08-28 00:00:27 +1000770 def recvmsg(self, *args, **kwargs):
771 raise NotImplementedError("recvmsg not allowed on instances of %s" %
772 self.__class__)
773
774 def recvmsg_into(self, *args, **kwargs):
775 raise NotImplementedError("recvmsg_into not allowed on instances of "
776 "%s" % self.__class__)
777
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000778 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000779 self._checkClosed()
780 if self._sslobj:
781 return self._sslobj.pending()
782 else:
783 return 0
784
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000785 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000786 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000788 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000789
Ezio Melottidc55e672010-01-18 09:15:14 +0000790 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000791 if self._sslobj:
792 s = self._sslobj.shutdown()
793 self._sslobj = None
794 return s
795 else:
796 raise ValueError("No SSL wrapper around " + str(self))
797
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000798 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000800 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000801
Bill Janssen48dc27c2007-12-05 03:38:10 +0000802 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000803 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200804 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000805 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000806 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000807 if timeout == 0.0 and block:
808 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000809 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000810 finally:
811 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000812
Christian Heimes1aa9a752013-12-02 02:41:19 +0100813 if self.context.check_hostname:
Christian Heimes1da3ba82013-12-04 20:46:20 +0100814 if not self.server_hostname:
815 raise ValueError("check_hostname needs server_hostname "
816 "argument")
817 match_hostname(self.getpeercert(), self.server_hostname)
Christian Heimes1aa9a752013-12-02 02:41:19 +0100818
Antoine Pitroub4410db2011-05-18 18:51:06 +0200819 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000820 if self.server_side:
821 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000822 # Here we assume that the socket is client-side, and not
823 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000824 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000826 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000827 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200828 if connect_ex:
829 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000830 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200831 rc = None
832 socket.connect(self, addr)
833 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200834 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200835 if self.do_handshake_on_connect:
836 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200837 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +0100838 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +0200839 self._sslobj = None
840 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000841
842 def connect(self, addr):
843 """Connects to remote ADDR, and then wraps the connection in
844 an SSL channel."""
845 self._real_connect(addr, False)
846
847 def connect_ex(self, addr):
848 """Connects to remote ADDR, and then wraps the connection in
849 an SSL channel."""
850 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000851
852 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000853 """Accepts a new connection from a remote client, and returns
854 a tuple containing that new connection wrapped with a server-side
855 SSL channel, and the address of the remote client."""
856
857 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100858 newsock = self.context.wrap_socket(newsock,
859 do_handshake_on_connect=self.do_handshake_on_connect,
860 suppress_ragged_eofs=self.suppress_ragged_eofs,
861 server_side=True)
862 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863
Antoine Pitroud6494802011-07-21 01:11:30 +0200864 def get_channel_binding(self, cb_type="tls-unique"):
865 """Get channel binding data for current connection. Raise ValueError
866 if the requested `cb_type` is not supported. Return bytes of the data
867 or None if the data is not available (e.g. before the handshake).
868 """
869 if cb_type not in CHANNEL_BINDING_TYPES:
870 raise ValueError("Unsupported channel binding type")
871 if cb_type != "tls-unique":
872 raise NotImplementedError(
873 "{0} channel binding type not implemented"
874 .format(cb_type))
875 if self._sslobj is None:
876 return None
877 return self._sslobj.tls_unique_cb()
878
Bill Janssen54cc54c2007-12-14 22:08:56 +0000879
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880def wrap_socket(sock, keyfile=None, certfile=None,
881 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000882 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000883 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100884 suppress_ragged_eofs=True,
885 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Bill Janssen6e027db2007-11-15 22:23:56 +0000887 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000889 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000890 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000891 suppress_ragged_eofs=suppress_ragged_eofs,
892 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
Thomas Woutersed03b412007-08-28 21:37:11 +0000894# some utility functions
895
896def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000897 """Takes a date-time string in standard ASN1_print form
898 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
899 a Python time value in seconds past the epoch."""
900
Thomas Woutersed03b412007-08-28 21:37:11 +0000901 import time
902 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
903
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904PEM_HEADER = "-----BEGIN CERTIFICATE-----"
905PEM_FOOTER = "-----END CERTIFICATE-----"
906
907def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908 """Takes a certificate in binary DER format and returns the
909 PEM version of it as a string."""
910
Bill Janssen6e027db2007-11-15 22:23:56 +0000911 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
912 return (PEM_HEADER + '\n' +
913 textwrap.fill(f, 64) + '\n' +
914 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915
916def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917 """Takes a certificate in ASCII PEM format and returns the
918 DER-encoded version of it as a byte sequence"""
919
920 if not pem_cert_string.startswith(PEM_HEADER):
921 raise ValueError("Invalid PEM encoding; must start with %s"
922 % PEM_HEADER)
923 if not pem_cert_string.strip().endswith(PEM_FOOTER):
924 raise ValueError("Invalid PEM encoding; must end with %s"
925 % PEM_FOOTER)
926 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000927 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000929def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930 """Retrieve the certificate from the server at the specified address,
931 and return it as a PEM-encoded string.
932 If 'ca_certs' is specified, validate the server cert against it.
933 If 'ssl_version' is specified, use it in the connection attempt."""
934
935 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +0100936 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937 cert_reqs = CERT_REQUIRED
938 else:
939 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +0100940 context = _create_stdlib_context(ssl_version,
941 cert_reqs=cert_reqs,
942 cafile=ca_certs)
943 with create_connection(addr) as sock:
944 with context.wrap_socket(sock) as sslsock:
945 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946 return DER_cert_to_PEM_cert(dercert)
947
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000948def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200949 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')