blob: ec42e38d08638c106b5325f8cfecabb12184e5a7 [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 Heimesa6bc95a2013-11-17 19:59:14 +0100106from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Victor Stinnerfcfed192015-01-06 13:54:58 +0100107from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
108try:
109 from _ssl import RAND_egd
110except ImportError:
111 # LibreSSL does not provide RAND_egd
112 pass
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100113
114def _import_symbols(prefix):
115 for n in dir(_ssl):
116 if n.startswith(prefix):
117 globals()[n] = getattr(_ssl, n)
118
119_import_symbols('OP_')
120_import_symbols('ALERT_DESCRIPTION_')
121_import_symbols('SSL_ERROR_')
Victor Stinner00411422014-12-12 12:23:09 +0100122_import_symbols('PROTOCOL_')
Benjamin Peterson7bcf9a52015-03-04 23:18:57 -0500123_import_symbols('VERIFY_')
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100124
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100125from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100126
Antoine Pitroub9ac25d2011-07-08 18:47:06 +0200127from _ssl import _OPENSSL_API_VERSION
128
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100129
Victor Stinner00411422014-12-12 12:23:09 +0100130_PROTOCOL_NAMES = {value: name for name, value in globals().items() if name.startswith('PROTOCOL_')}
Victor Stinner3de49192011-05-09 00:42:58 +0200131try:
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
Donald Stufft79ccaa22014-03-21 21:33:34 -0400172# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
173# reasons
174_DEFAULT_CIPHERS = (
175 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
Benjamin Peterson500af332015-02-19 17:57:08 -0500176 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
177 '!eNULL:!MD5'
Donald Stufft79ccaa22014-03-21 21:33:34 -0400178)
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100179
Donald Stufft6a2ba942014-03-23 19:05:28 -0400180# Restricted and more secure ciphers for the server side
Donald Stufft79ccaa22014-03-21 21:33:34 -0400181# This list has been explicitly chosen to:
182# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
183# * Prefer ECDHE over DHE for better performance
184# * Prefer any AES-GCM over any AES-CBC for better performance and security
185# * Then Use HIGH cipher suites as a fallback
186# * Then Use 3DES as fallback which is secure but slow
187# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
188# security reasons
Donald Stufft6a2ba942014-03-23 19:05:28 -0400189_RESTRICTED_SERVER_CIPHERS = (
Donald Stufft79ccaa22014-03-21 21:33:34 -0400190 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
191 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
192 '!eNULL:!MD5:!DSS:!RC4'
193)
Christian Heimes4c05b472013-11-23 15:58:30 +0100194
Thomas Woutersed03b412007-08-28 21:37:11 +0000195
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000196class CertificateError(ValueError):
197 pass
198
199
Georg Brandl72c98d32013-10-27 07:16:53 +0100200def _dnsname_match(dn, hostname, max_wildcards=1):
201 """Matching according to RFC 6125, section 6.4.3
202
203 http://tools.ietf.org/html/rfc6125#section-6.4.3
204 """
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000205 pats = []
Georg Brandl72c98d32013-10-27 07:16:53 +0100206 if not dn:
207 return False
208
209 leftmost, *remainder = dn.split(r'.')
210
211 wildcards = leftmost.count('*')
212 if wildcards > max_wildcards:
213 # Issue #17980: avoid denials of service by refusing more
Berker Peksagf23530f2014-10-19 18:04:38 +0300214 # than one wildcard per fragment. A survey of established
Georg Brandl72c98d32013-10-27 07:16:53 +0100215 # policy among SSL implementations showed it to be a
216 # reasonable choice.
217 raise CertificateError(
218 "too many wildcards in certificate DNS name: " + repr(dn))
219
220 # speed up common case w/o wildcards
221 if not wildcards:
222 return dn.lower() == hostname.lower()
223
224 # RFC 6125, section 6.4.3, subitem 1.
225 # The client SHOULD NOT attempt to match a presented identifier in which
226 # the wildcard character comprises a label other than the left-most label.
227 if leftmost == '*':
228 # When '*' is a fragment by itself, it matches a non-empty dotless
229 # fragment.
230 pats.append('[^.]+')
231 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
232 # RFC 6125, section 6.4.3, subitem 3.
233 # The client SHOULD NOT attempt to match a presented identifier
234 # where the wildcard character is embedded within an A-label or
235 # U-label of an internationalized domain name.
236 pats.append(re.escape(leftmost))
237 else:
238 # Otherwise, '*' matches any dotless string, e.g. www*
239 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
240
241 # add the remaining fragments, ignore any wildcards
242 for frag in remainder:
243 pats.append(re.escape(frag))
244
245 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
246 return pat.match(hostname)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000247
248
249def match_hostname(cert, hostname):
250 """Verify that *cert* (in decoded format as returned by
Georg Brandl72c98d32013-10-27 07:16:53 +0100251 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
252 rules are followed, but IP addresses are not accepted for *hostname*.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000253
254 CertificateError is raised on failure. On success, the function
255 returns nothing.
256 """
257 if not cert:
Christian Heimes1aa9a752013-12-02 02:41:19 +0100258 raise ValueError("empty or no certificate, match_hostname needs a "
259 "SSL socket or SSL context with either "
260 "CERT_OPTIONAL or CERT_REQUIRED")
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000261 dnsnames = []
262 san = cert.get('subjectAltName', ())
263 for key, value in san:
264 if key == 'DNS':
Georg Brandl72c98d32013-10-27 07:16:53 +0100265 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000266 return
267 dnsnames.append(value)
Antoine Pitrou1c86b442011-05-06 15:19:49 +0200268 if not dnsnames:
269 # The subject is only checked when there is no dNSName entry
270 # in subjectAltName
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000271 for sub in cert.get('subject', ()):
272 for key, value in sub:
273 # XXX according to RFC 2818, the most specific Common Name
274 # must be used.
275 if key == 'commonName':
Georg Brandl72c98d32013-10-27 07:16:53 +0100276 if _dnsname_match(value, hostname):
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000277 return
278 dnsnames.append(value)
279 if len(dnsnames) > 1:
280 raise CertificateError("hostname %r "
281 "doesn't match either of %s"
282 % (hostname, ', '.join(map(repr, dnsnames))))
283 elif len(dnsnames) == 1:
284 raise CertificateError("hostname %r "
285 "doesn't match %r"
286 % (hostname, dnsnames[0]))
287 else:
288 raise CertificateError("no appropriate commonName or "
289 "subjectAltName fields were found")
290
291
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100292DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
Christian Heimes6d7ad132013-06-09 18:02:55 +0200293 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
294 "openssl_capath")
295
296def get_default_verify_paths():
297 """Return paths to default cafile and capath.
298 """
299 parts = _ssl.get_default_verify_paths()
300
301 # environment vars shadow paths
302 cafile = os.environ.get(parts[0], parts[1])
303 capath = os.environ.get(parts[2], parts[3])
304
305 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
306 capath if os.path.isdir(capath) else None,
307 *parts)
308
309
Christian Heimesa6bc95a2013-11-17 19:59:14 +0100310class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
311 """ASN.1 object identifier lookup
312 """
313 __slots__ = ()
314
315 def __new__(cls, oid):
316 return super().__new__(cls, *_txt2obj(oid, name=False))
317
318 @classmethod
319 def fromnid(cls, nid):
320 """Create _ASN1Object from OpenSSL numeric ID
321 """
322 return super().__new__(cls, *_nid2obj(nid))
323
324 @classmethod
325 def fromname(cls, name):
326 """Create _ASN1Object from short name, long name or OID
327 """
328 return super().__new__(cls, *_txt2obj(name, name=True))
329
330
Christian Heimes72d28502013-11-23 13:56:58 +0100331class Purpose(_ASN1Object, _Enum):
332 """SSLContext purpose flags with X509v3 Extended Key Usage objects
333 """
334 SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
335 CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
336
337
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338class SSLContext(_SSLContext):
339 """An SSLContext holds various SSL-related configuration options and
340 data, such as certificates and possibly a private key."""
341
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100342 __slots__ = ('protocol', '__weakref__')
Christian Heimes72d28502013-11-23 13:56:58 +0100343 _windows_cert_stores = ("CA", "ROOT")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000344
345 def __new__(cls, protocol, *args, **kwargs):
Antoine Pitrou8f85f902012-01-03 22:46:48 +0100346 self = _SSLContext.__new__(cls, protocol)
347 if protocol != _SSLv2_IF_EXISTS:
348 self.set_ciphers(_DEFAULT_CIPHERS)
349 return self
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350
351 def __init__(self, protocol):
352 self.protocol = protocol
353
354 def wrap_socket(self, sock, server_side=False,
355 do_handshake_on_connect=True,
Antoine Pitroud5323212010-10-22 18:19:07 +0000356 suppress_ragged_eofs=True,
357 server_hostname=None):
Antoine Pitrou152efa22010-05-16 18:19:27 +0000358 return SSLSocket(sock=sock, server_side=server_side,
359 do_handshake_on_connect=do_handshake_on_connect,
360 suppress_ragged_eofs=suppress_ragged_eofs,
Antoine Pitroud5323212010-10-22 18:19:07 +0000361 server_hostname=server_hostname,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000362 _context=self)
363
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100364 def set_npn_protocols(self, npn_protocols):
365 protos = bytearray()
366 for protocol in npn_protocols:
367 b = bytes(protocol, 'ascii')
368 if len(b) == 0 or len(b) > 255:
369 raise SSLError('NPN protocols must be 1 to 255 in length')
370 protos.append(len(b))
371 protos.extend(b)
372
373 self._set_npn_protocols(protos)
374
Christian Heimes72d28502013-11-23 13:56:58 +0100375 def _load_windows_store_certs(self, storename, purpose):
376 certs = bytearray()
377 for cert, encoding, trust in enum_certificates(storename):
378 # CA certs are never PKCS#7 encoded
379 if encoding == "x509_asn":
380 if trust is True or purpose.oid in trust:
381 certs.extend(cert)
382 self.load_verify_locations(cadata=certs)
383 return certs
384
385 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
386 if not isinstance(purpose, _ASN1Object):
387 raise TypeError(purpose)
388 if sys.platform == "win32":
389 for storename in self._windows_cert_stores:
390 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson5915b0f2014-10-03 17:27:05 -0400391 self.set_default_verify_paths()
Christian Heimes72d28502013-11-23 13:56:58 +0100392
Antoine Pitrou152efa22010-05-16 18:19:27 +0000393
Christian Heimes4c05b472013-11-23 15:58:30 +0100394def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
395 capath=None, cadata=None):
396 """Create a SSLContext object with default settings.
397
398 NOTE: The protocol and settings may change anytime without prior
399 deprecation. The values represent a fair balance between maximum
400 compatibility and security.
401 """
402 if not isinstance(purpose, _ASN1Object):
403 raise TypeError(purpose)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400404
405 context = SSLContext(PROTOCOL_SSLv23)
406
Christian Heimes4c05b472013-11-23 15:58:30 +0100407 # SSLv2 considered harmful.
408 context.options |= OP_NO_SSLv2
Donald Stufft6a2ba942014-03-23 19:05:28 -0400409
410 # SSLv3 has problematic security and is only required for really old
411 # clients such as IE6 on Windows XP
412 context.options |= OP_NO_SSLv3
413
Christian Heimesdec813f2013-11-28 08:06:54 +0100414 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
415 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
Donald Stufft6a2ba942014-03-23 19:05:28 -0400416
Christian Heimes4c05b472013-11-23 15:58:30 +0100417 if purpose == Purpose.SERVER_AUTH:
Donald Stufft6a2ba942014-03-23 19:05:28 -0400418 # verify certs and host name in client mode
Christian Heimes4c05b472013-11-23 15:58:30 +0100419 context.verify_mode = CERT_REQUIRED
Christian Heimes1aa9a752013-12-02 02:41:19 +0100420 context.check_hostname = True
Donald Stufft6a2ba942014-03-23 19:05:28 -0400421 elif purpose == Purpose.CLIENT_AUTH:
422 # Prefer the server's ciphers by default so that we get stronger
423 # encryption
424 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
425
426 # Use single use keys in order to improve forward secrecy
427 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
428 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
429
430 # disallow ciphers with known vulnerabilities
431 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
432
Christian Heimes4c05b472013-11-23 15:58:30 +0100433 if cafile or capath or cadata:
434 context.load_verify_locations(cafile, capath, cadata)
435 elif context.verify_mode != CERT_NONE:
436 # no explicit cafile, capath or cadata but the verify mode is
437 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
438 # root CA certificates for the given purpose. This may fail silently.
439 context.load_default_certs(purpose)
440 return context
441
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500442def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
Christian Heimesa02c69a2013-12-02 20:59:28 +0100443 check_hostname=False, purpose=Purpose.SERVER_AUTH,
Christian Heimes67986f92013-11-23 22:43:47 +0100444 certfile=None, keyfile=None,
445 cafile=None, capath=None, cadata=None):
446 """Create a SSLContext object for Python stdlib modules
447
448 All Python stdlib modules shall use this function to create SSLContext
449 objects in order to keep common settings in one place. The configuration
450 is less restrict than create_default_context()'s to increase backward
451 compatibility.
452 """
453 if not isinstance(purpose, _ASN1Object):
454 raise TypeError(purpose)
455
456 context = SSLContext(protocol)
457 # SSLv2 considered harmful.
458 context.options |= OP_NO_SSLv2
Antoine Pitroua21de3d2014-10-17 19:28:30 +0200459 # SSLv3 has problematic security and is only required for really old
460 # clients such as IE6 on Windows XP
461 context.options |= OP_NO_SSLv3
Christian Heimes67986f92013-11-23 22:43:47 +0100462
463 if cert_reqs is not None:
464 context.verify_mode = cert_reqs
Christian Heimesa02c69a2013-12-02 20:59:28 +0100465 context.check_hostname = check_hostname
Christian Heimes67986f92013-11-23 22:43:47 +0100466
467 if keyfile and not certfile:
468 raise ValueError("certfile must be specified")
469 if certfile or keyfile:
470 context.load_cert_chain(certfile, keyfile)
471
472 # load CA root certs
473 if cafile or capath or cadata:
474 context.load_verify_locations(cafile, capath, cadata)
475 elif context.verify_mode != CERT_NONE:
476 # no explicit cafile, capath or cadata but the verify mode is
477 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
478 # root CA certificates for the given purpose. This may fail silently.
479 context.load_default_certs(purpose)
480
481 return context
482
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500483# Used by http.client if no context is explicitly passed.
484_create_default_https_context = create_default_context
485
486
487# Backwards compatibility alias, even though it's not a public name.
488_create_stdlib_context = _create_unverified_context
489
490
Antoine Pitrou152efa22010-05-16 18:19:27 +0000491class SSLSocket(socket):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000492 """This class implements a subtype of socket.socket that wraps
493 the underlying OS socket in an SSL context when necessary, and
494 provides read and write methods over that channel."""
495
Bill Janssen6e027db2007-11-15 22:23:56 +0000496 def __init__(self, sock=None, keyfile=None, certfile=None,
Thomas Woutersed03b412007-08-28 21:37:11 +0000497 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000498 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
499 do_handshake_on_connect=True,
500 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100501 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Antoine Pitroud5323212010-10-22 18:19:07 +0000502 server_hostname=None,
Antoine Pitrou152efa22010-05-16 18:19:27 +0000503 _context=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000504
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 if _context:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100506 self._context = _context
Antoine Pitrou152efa22010-05-16 18:19:27 +0000507 else:
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000508 if server_side and not certfile:
509 raise ValueError("certfile must be specified for server-side "
510 "operations")
Giampaolo RodolĂ 8b7da622010-08-30 18:28:05 +0000511 if keyfile and not certfile:
512 raise ValueError("certfile must be specified")
Antoine Pitrou152efa22010-05-16 18:19:27 +0000513 if certfile and not keyfile:
514 keyfile = certfile
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100515 self._context = SSLContext(ssl_version)
516 self._context.verify_mode = cert_reqs
Antoine Pitrou152efa22010-05-16 18:19:27 +0000517 if ca_certs:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100518 self._context.load_verify_locations(ca_certs)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000519 if certfile:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100520 self._context.load_cert_chain(certfile, keyfile)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100521 if npn_protocols:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100522 self._context.set_npn_protocols(npn_protocols)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000523 if ciphers:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100524 self._context.set_ciphers(ciphers)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000525 self.keyfile = keyfile
526 self.certfile = certfile
527 self.cert_reqs = cert_reqs
528 self.ssl_version = ssl_version
529 self.ca_certs = ca_certs
530 self.ciphers = ciphers
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100531 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
532 # mixed in.
533 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
534 raise NotImplementedError("only stream sockets are supported")
Antoine Pitroud5323212010-10-22 18:19:07 +0000535 if server_side and server_hostname:
536 raise ValueError("server_hostname can only be specified "
537 "in client mode")
Christian Heimes1aa9a752013-12-02 02:41:19 +0100538 if self._context.check_hostname and not server_hostname:
Benjamin Peterson7243b572014-11-23 17:04:34 -0600539 raise ValueError("check_hostname requires server_hostname")
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000540 self.server_side = server_side
Antoine Pitroud5323212010-10-22 18:19:07 +0000541 self.server_hostname = server_hostname
Antoine Pitrou152efa22010-05-16 18:19:27 +0000542 self.do_handshake_on_connect = do_handshake_on_connect
543 self.suppress_ragged_eofs = suppress_ragged_eofs
Bill Janssen6e027db2007-11-15 22:23:56 +0000544 if sock is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000545 socket.__init__(self,
546 family=sock.family,
547 type=sock.type,
548 proto=sock.proto,
Antoine Pitroue43f9d02010-08-08 23:24:50 +0000549 fileno=sock.fileno())
Antoine Pitrou40f08742010-04-24 22:04:40 +0000550 self.settimeout(sock.gettimeout())
Antoine Pitrou6e451df2010-08-09 20:39:54 +0000551 sock.detach()
Bill Janssen6e027db2007-11-15 22:23:56 +0000552 elif fileno is not None:
553 socket.__init__(self, fileno=fileno)
554 else:
555 socket.__init__(self, family=family, type=type, proto=proto)
556
Antoine Pitrou242db722013-05-01 20:52:07 +0200557 # See if we are connected
558 try:
559 self.getpeername()
560 except OSError as e:
561 if e.errno != errno.ENOTCONN:
562 raise
563 connected = False
564 else:
565 connected = True
566
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000567 self._closed = False
568 self._sslobj = None
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000569 self._connected = connected
Antoine Pitroufa2b9382010-04-26 22:17:47 +0000570 if connected:
571 # create the SSL object
Bill Janssen6e027db2007-11-15 22:23:56 +0000572 try:
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100573 self._sslobj = self._context._wrap_socket(self, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +0000574 server_hostname)
Bill Janssen6e027db2007-11-15 22:23:56 +0000575 if do_handshake_on_connect:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000576 timeout = self.gettimeout()
577 if timeout == 0.0:
578 # non-blocking
579 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
Bill Janssen6e027db2007-11-15 22:23:56 +0000580 self.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000581
Christian Heimes1aa9a752013-12-02 02:41:19 +0100582 except (OSError, ValueError):
Bill Janssen6e027db2007-11-15 22:23:56 +0000583 self.close()
Christian Heimes1aa9a752013-12-02 02:41:19 +0100584 raise
Antoine Pitrou242db722013-05-01 20:52:07 +0200585
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100586 @property
587 def context(self):
588 return self._context
589
590 @context.setter
591 def context(self, ctx):
592 self._context = ctx
593 self._sslobj.context = ctx
Bill Janssen6e027db2007-11-15 22:23:56 +0000594
Guido van Rossumb7b030e2007-11-16 01:28:45 +0000595 def dup(self):
596 raise NotImplemented("Can't dup() %s instances" %
597 self.__class__.__name__)
598
Bill Janssen6e027db2007-11-15 22:23:56 +0000599 def _checkClosed(self, msg=None):
600 # raise an exception here if you wish to check for spurious closes
601 pass
602
Antoine Pitrou242db722013-05-01 20:52:07 +0200603 def _check_connected(self):
604 if not self._connected:
605 # getpeername() will raise ENOTCONN if the socket is really
606 # not connected; note that we can be connected even without
607 # _connected being set, e.g. if connect() first returned
608 # EAGAIN.
609 self.getpeername()
610
Bill Janssen54cc54c2007-12-14 22:08:56 +0000611 def read(self, len=0, buffer=None):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000612 """Read up to LEN bytes and return them.
613 Return zero-length string on EOF."""
614
Bill Janssen6e027db2007-11-15 22:23:56 +0000615 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200616 if not self._sslobj:
617 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen6e027db2007-11-15 22:23:56 +0000618 try:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000619 if buffer is not None:
620 v = self._sslobj.read(len, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000621 else:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000622 v = self._sslobj.read(len or 1024)
623 return v
Bill Janssen6e027db2007-11-15 22:23:56 +0000624 except SSLError as x:
625 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Antoine Pitrou24e561a2010-09-03 18:38:17 +0000626 if buffer is not None:
Bill Janssen54cc54c2007-12-14 22:08:56 +0000627 return 0
628 else:
629 return b''
Bill Janssen6e027db2007-11-15 22:23:56 +0000630 else:
631 raise
Thomas Woutersed03b412007-08-28 21:37:11 +0000632
633 def write(self, data):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000634 """Write DATA to the underlying SSL channel. Returns
635 number of bytes of DATA actually transmitted."""
636
Bill Janssen6e027db2007-11-15 22:23:56 +0000637 self._checkClosed()
Antoine Pitrou60a26e02013-07-20 19:35:16 +0200638 if not self._sslobj:
639 raise ValueError("Write on closed or unwrapped SSL socket.")
Thomas Woutersed03b412007-08-28 21:37:11 +0000640 return self._sslobj.write(data)
641
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642 def getpeercert(self, binary_form=False):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000643 """Returns a formatted version of the data in the
644 certificate provided by the other end of the SSL channel.
645 Return None if no certificate was provided, {} if a
646 certificate was provided, but not validated."""
647
Bill Janssen6e027db2007-11-15 22:23:56 +0000648 self._checkClosed()
Antoine Pitrou242db722013-05-01 20:52:07 +0200649 self._check_connected()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650 return self._sslobj.peer_certificate(binary_form)
651
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100652 def selected_npn_protocol(self):
653 self._checkClosed()
654 if not self._sslobj or not _ssl.HAS_NPN:
655 return None
656 else:
657 return self._sslobj.selected_npn_protocol()
658
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000659 def cipher(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000660 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661 if not self._sslobj:
662 return None
663 else:
664 return self._sslobj.cipher()
Thomas Woutersed03b412007-08-28 21:37:11 +0000665
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100666 def compression(self):
667 self._checkClosed()
668 if not self._sslobj:
669 return None
670 else:
671 return self._sslobj.compression()
672
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000673 def send(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000674 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000675 if self._sslobj:
676 if flags != 0:
677 raise ValueError(
678 "non-zero flags not allowed in calls to send() on %s" %
679 self.__class__)
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200680 try:
681 v = self._sslobj.write(data)
682 except SSLError as x:
683 if x.args[0] == SSL_ERROR_WANT_READ:
684 return 0
685 elif x.args[0] == SSL_ERROR_WANT_WRITE:
686 return 0
Bill Janssen6e027db2007-11-15 22:23:56 +0000687 else:
Giampaolo Rodola'06d0c1e2013-04-03 12:01:44 +0200688 raise
689 else:
690 return v
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000691 else:
692 return socket.send(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000693
Antoine Pitroua468adc2010-09-14 14:43:44 +0000694 def sendto(self, data, flags_or_addr, addr=None):
Bill Janssen6e027db2007-11-15 22:23:56 +0000695 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000696 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000697 raise ValueError("sendto not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000698 self.__class__)
Antoine Pitroua468adc2010-09-14 14:43:44 +0000699 elif addr is None:
700 return socket.sendto(self, data, flags_or_addr)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000701 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000702 return socket.sendto(self, data, flags_or_addr, addr)
Thomas Woutersed03b412007-08-28 21:37:11 +0000703
Nick Coghlan513886a2011-08-28 00:00:27 +1000704 def sendmsg(self, *args, **kwargs):
705 # Ensure programs don't send data unencrypted if they try to
706 # use this method.
707 raise NotImplementedError("sendmsg not allowed on instances of %s" %
708 self.__class__)
709
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000710 def sendall(self, data, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000711 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000712 if self._sslobj:
Giampaolo RodolĂ 374f8352010-08-29 12:08:09 +0000713 if flags != 0:
714 raise ValueError(
715 "non-zero flags not allowed in calls to sendall() on %s" %
716 self.__class__)
Bill Janssen6e027db2007-11-15 22:23:56 +0000717 amount = len(data)
718 count = 0
719 while (count < amount):
720 v = self.send(data[count:])
721 count += v
722 return amount
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000723 else:
724 return socket.sendall(self, data, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000725
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000726 def recv(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000727 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000728 if self._sslobj:
729 if flags != 0:
730 raise ValueError(
Antoine Pitrou5733c082010-03-22 14:49:10 +0000731 "non-zero flags not allowed in calls to recv() on %s" %
732 self.__class__)
733 return self.read(buflen)
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000734 else:
735 return socket.recv(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000736
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000737 def recv_into(self, buffer, nbytes=None, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000738 self._checkClosed()
739 if buffer and (nbytes is None):
740 nbytes = len(buffer)
741 elif nbytes is None:
742 nbytes = 1024
743 if self._sslobj:
744 if flags != 0:
745 raise ValueError(
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000746 "non-zero flags not allowed in calls to recv_into() on %s" %
747 self.__class__)
Antoine Pitrou5733c082010-03-22 14:49:10 +0000748 return self.read(nbytes, buffer)
Bill Janssen6e027db2007-11-15 22:23:56 +0000749 else:
750 return socket.recv_into(self, buffer, nbytes, flags)
751
Antoine Pitroua468adc2010-09-14 14:43:44 +0000752 def recvfrom(self, buflen=1024, flags=0):
Bill Janssen6e027db2007-11-15 22:23:56 +0000753 self._checkClosed()
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000754 if self._sslobj:
Bill Janssen980f3142008-06-29 00:05:51 +0000755 raise ValueError("recvfrom not allowed on instances of %s" %
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000756 self.__class__)
757 else:
Antoine Pitroua468adc2010-09-14 14:43:44 +0000758 return socket.recvfrom(self, buflen, flags)
Thomas Woutersed03b412007-08-28 21:37:11 +0000759
Bill Janssen58afe4c2008-09-08 16:45:19 +0000760 def recvfrom_into(self, buffer, nbytes=None, flags=0):
761 self._checkClosed()
762 if self._sslobj:
763 raise ValueError("recvfrom_into not allowed on instances of %s" %
764 self.__class__)
765 else:
766 return socket.recvfrom_into(self, buffer, nbytes, flags)
767
Nick Coghlan513886a2011-08-28 00:00:27 +1000768 def recvmsg(self, *args, **kwargs):
769 raise NotImplementedError("recvmsg not allowed on instances of %s" %
770 self.__class__)
771
772 def recvmsg_into(self, *args, **kwargs):
773 raise NotImplementedError("recvmsg_into not allowed on instances of "
774 "%s" % self.__class__)
775
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000776 def pending(self):
Bill Janssen6e027db2007-11-15 22:23:56 +0000777 self._checkClosed()
778 if self._sslobj:
779 return self._sslobj.pending()
780 else:
781 return 0
782
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000783 def shutdown(self, how):
Bill Janssen6e027db2007-11-15 22:23:56 +0000784 self._checkClosed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785 self._sslobj = None
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000786 socket.shutdown(self, how)
Thomas Woutersed03b412007-08-28 21:37:11 +0000787
Ezio Melottidc55e672010-01-18 09:15:14 +0000788 def unwrap(self):
Bill Janssen40a0f662008-08-12 16:56:25 +0000789 if self._sslobj:
790 s = self._sslobj.shutdown()
791 self._sslobj = None
792 return s
793 else:
794 raise ValueError("No SSL wrapper around " + str(self))
795
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000796 def _real_close(self):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797 self._sslobj = None
Bill Janssen54cc54c2007-12-14 22:08:56 +0000798 socket._real_close(self)
Bill Janssen6e027db2007-11-15 22:23:56 +0000799
Bill Janssen48dc27c2007-12-05 03:38:10 +0000800 def do_handshake(self, block=False):
Bill Janssen6e027db2007-11-15 22:23:56 +0000801 """Perform a TLS/SSL handshake."""
Antoine Pitrou242db722013-05-01 20:52:07 +0200802 self._check_connected()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000803 timeout = self.gettimeout()
Bill Janssen6e027db2007-11-15 22:23:56 +0000804 try:
Bill Janssen48dc27c2007-12-05 03:38:10 +0000805 if timeout == 0.0 and block:
806 self.settimeout(None)
Bill Janssen6e027db2007-11-15 22:23:56 +0000807 self._sslobj.do_handshake()
Bill Janssen48dc27c2007-12-05 03:38:10 +0000808 finally:
809 self.settimeout(timeout)
Thomas Woutersed03b412007-08-28 21:37:11 +0000810
Christian Heimes1aa9a752013-12-02 02:41:19 +0100811 if self.context.check_hostname:
Christian Heimes1da3ba82013-12-04 20:46:20 +0100812 if not self.server_hostname:
813 raise ValueError("check_hostname needs server_hostname "
814 "argument")
815 match_hostname(self.getpeercert(), self.server_hostname)
Christian Heimes1aa9a752013-12-02 02:41:19 +0100816
Antoine Pitroub4410db2011-05-18 18:51:06 +0200817 def _real_connect(self, addr, connect_ex):
Giampaolo RodolĂ 745ab382010-08-29 19:25:49 +0000818 if self.server_side:
819 raise ValueError("can't connect in server-side mode")
Thomas Woutersed03b412007-08-28 21:37:11 +0000820 # Here we assume that the socket is client-side, and not
821 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000822 if self._connected:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823 raise ValueError("attempt to connect already-connected SSLSocket!")
Antoine Pitroud5323212010-10-22 18:19:07 +0000824 self._sslobj = self.context._wrap_socket(self, False, self.server_hostname)
Bill Janssen54cc54c2007-12-14 22:08:56 +0000825 try:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200826 if connect_ex:
827 rc = socket.connect_ex(self, addr)
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000828 else:
Antoine Pitroub4410db2011-05-18 18:51:06 +0200829 rc = None
830 socket.connect(self, addr)
831 if not rc:
Antoine Pitrou242db722013-05-01 20:52:07 +0200832 self._connected = True
Antoine Pitroub4410db2011-05-18 18:51:06 +0200833 if self.do_handshake_on_connect:
834 self.do_handshake()
Antoine Pitroub4410db2011-05-18 18:51:06 +0200835 return rc
Christian Heimes1aa9a752013-12-02 02:41:19 +0100836 except (OSError, ValueError):
Antoine Pitroub4410db2011-05-18 18:51:06 +0200837 self._sslobj = None
838 raise
Antoine Pitroue93bf7a2011-02-26 23:24:06 +0000839
840 def connect(self, addr):
841 """Connects to remote ADDR, and then wraps the connection in
842 an SSL channel."""
843 self._real_connect(addr, False)
844
845 def connect_ex(self, addr):
846 """Connects to remote ADDR, and then wraps the connection in
847 an SSL channel."""
848 return self._real_connect(addr, True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000849
850 def accept(self):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000851 """Accepts a new connection from a remote client, and returns
852 a tuple containing that new connection wrapped with a server-side
853 SSL channel, and the address of the remote client."""
854
855 newsock, addr = socket.accept(self)
Antoine Pitrou5c89b4e2012-11-11 01:25:36 +0100856 newsock = self.context.wrap_socket(newsock,
857 do_handshake_on_connect=self.do_handshake_on_connect,
858 suppress_ragged_eofs=self.suppress_ragged_eofs,
859 server_side=True)
860 return newsock, addr
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroud6494802011-07-21 01:11:30 +0200862 def get_channel_binding(self, cb_type="tls-unique"):
863 """Get channel binding data for current connection. Raise ValueError
864 if the requested `cb_type` is not supported. Return bytes of the data
865 or None if the data is not available (e.g. before the handshake).
866 """
867 if cb_type not in CHANNEL_BINDING_TYPES:
868 raise ValueError("Unsupported channel binding type")
869 if cb_type != "tls-unique":
870 raise NotImplementedError(
871 "{0} channel binding type not implemented"
872 .format(cb_type))
873 if self._sslobj is None:
874 return None
875 return self._sslobj.tls_unique_cb()
876
Bill Janssen54cc54c2007-12-14 22:08:56 +0000877
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878def wrap_socket(sock, keyfile=None, certfile=None,
879 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen6e027db2007-11-15 22:23:56 +0000880 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000881 do_handshake_on_connect=True,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100882 suppress_ragged_eofs=True,
883 ciphers=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Bill Janssen6e027db2007-11-15 22:23:56 +0000885 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen6e027db2007-11-15 22:23:56 +0000887 ssl_version=ssl_version, ca_certs=ca_certs,
Bill Janssen48dc27c2007-12-05 03:38:10 +0000888 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000889 suppress_ragged_eofs=suppress_ragged_eofs,
890 ciphers=ciphers)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Thomas Woutersed03b412007-08-28 21:37:11 +0000892# some utility functions
893
894def cert_time_to_seconds(cert_time):
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000895 """Takes a date-time string in standard ASN1_print form
896 ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return
897 a Python time value in seconds past the epoch."""
898
Thomas Woutersed03b412007-08-28 21:37:11 +0000899 import time
900 return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
901
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902PEM_HEADER = "-----BEGIN CERTIFICATE-----"
903PEM_FOOTER = "-----END CERTIFICATE-----"
904
905def DER_cert_to_PEM_cert(der_cert_bytes):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906 """Takes a certificate in binary DER format and returns the
907 PEM version of it as a string."""
908
Bill Janssen6e027db2007-11-15 22:23:56 +0000909 f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
910 return (PEM_HEADER + '\n' +
911 textwrap.fill(f, 64) + '\n' +
912 PEM_FOOTER + '\n')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
914def PEM_cert_to_DER_cert(pem_cert_string):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915 """Takes a certificate in ASCII PEM format and returns the
916 DER-encoded version of it as a byte sequence"""
917
918 if not pem_cert_string.startswith(PEM_HEADER):
919 raise ValueError("Invalid PEM encoding; must start with %s"
920 % PEM_HEADER)
921 if not pem_cert_string.strip().endswith(PEM_FOOTER):
922 raise ValueError("Invalid PEM encoding; must end with %s"
923 % PEM_FOOTER)
924 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Georg Brandl706824f2009-06-04 09:42:55 +0000925 return base64.decodebytes(d.encode('ASCII', 'strict'))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Victor Stinner9d017172015-01-06 12:21:26 +0100927def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928 """Retrieve the certificate from the server at the specified address,
929 and return it as a PEM-encoded string.
930 If 'ca_certs' is specified, validate the server cert against it.
931 If 'ssl_version' is specified, use it in the connection attempt."""
932
933 host, port = addr
Christian Heimes67986f92013-11-23 22:43:47 +0100934 if ca_certs is not None:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935 cert_reqs = CERT_REQUIRED
936 else:
937 cert_reqs = CERT_NONE
Christian Heimes67986f92013-11-23 22:43:47 +0100938 context = _create_stdlib_context(ssl_version,
939 cert_reqs=cert_reqs,
940 cafile=ca_certs)
941 with create_connection(addr) as sock:
942 with context.wrap_socket(sock) as sslsock:
943 dercert = sslsock.getpeercert(True)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944 return DER_cert_to_PEM_cert(dercert)
945
Guido van Rossum5b8b1552007-11-16 00:06:11 +0000946def get_protocol_name(protocol_code):
Victor Stinner3de49192011-05-09 00:42:58 +0200947 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')