blob: dea893cf7737fec07456d8f350eb42336c18bf51 [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001# Wrapper module for _ssl, providing some additional facilities
2# implemented in Python. Written by Bill Janssen.
3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004"""This module provides some more Pythonic support for SSL.
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00005
6Object types:
7
Bill Janssen98d19da2007-09-10 21:51:02 +00008 SSLSocket -- subtype of socket.socket which does SSL over the socket
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00009
10Exceptions:
11
Bill Janssen98d19da2007-09-10 21:51:02 +000012 SSLError -- exception raised for I/O errors
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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
Benjamin Petersondaeb9252014-08-20 14:14:50 -050055PROTOCOL_TLSv1_1
56PROTOCOL_TLSv1_2
57
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
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000088"""
89
Christian Heimesc5f05e42008-02-23 17:40:11 +000090import textwrap
Benjamin Petersondaeb9252014-08-20 14:14:50 -050091import re
92import sys
93import os
94from collections import namedtuple
95from contextlib import closing
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000096
97import _ssl # if we can't import it, let the error propagate
Bill Janssen98d19da2007-09-10 21:51:02 +000098
Antoine Pitrouf9de5342010-04-05 21:35:07 +000099from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500100from _ssl import _SSLContext
101from _ssl import (
102 SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
103 SSLSyscallError, SSLEOFError,
104 )
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000105from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500106from _ssl import (VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN,
107 VERIFY_X509_STRICT)
108from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
Bill Janssen98d19da2007-09-10 21:51:02 +0000109from _ssl import RAND_status, RAND_egd, RAND_add
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500110
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_import_symbols('PROTOCOL_')
120
121from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN
122
123from _ssl import _OPENSSL_API_VERSION
124
125_PROTOCOL_NAMES = {value: name for name, value in globals().items() if name.startswith('PROTOCOL_')}
126
Victor Stinnerb1241f92011-05-10 01:52:03 +0200127try:
Antoine Pitroud76088d2012-01-03 22:46:48 +0100128 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500129except NameError:
Antoine Pitroud76088d2012-01-03 22:46:48 +0100130 _SSLv2_IF_EXISTS = None
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000131
Antoine Pitroudfb299b2010-04-23 22:54:59 +0000132from socket import socket, _fileobject, _delegate_methods, error as socket_error
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500133if sys.platform == "win32":
134 from _ssl import enum_certificates, enum_crls
135
136from socket import socket, AF_INET, SOCK_STREAM, create_connection
137from socket import SOL_SOCKET, SO_TYPE
Bill Janssen296a59d2007-09-16 22:06:00 +0000138import base64 # for DER-to-PEM translation
Antoine Pitrou278d6652010-04-26 17:23:33 +0000139import errno
Bill Janssen98d19da2007-09-10 21:51:02 +0000140
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500141if _ssl.HAS_TLS_UNIQUE:
142 CHANNEL_BINDING_TYPES = ['tls-unique']
143else:
144 CHANNEL_BINDING_TYPES = []
145
Antoine Pitroud76088d2012-01-03 22:46:48 +0100146# Disable weak or insecure ciphers by default
147# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500148# Enable a better set of ciphers by default
149# This list has been explicitly chosen to:
150# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
151# * Prefer ECDHE over DHE for better performance
152# * Prefer any AES-GCM over any AES-CBC for better performance and security
153# * Then Use HIGH cipher suites as a fallback
154# * Then Use 3DES as fallback which is secure but slow
155# * Finally use RC4 as a fallback which is problematic but needed for
156# compatibility some times.
157# * Disable NULL authentication, NULL encryption, and MD5 MACs for security
158# reasons
159_DEFAULT_CIPHERS = (
160 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
161 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:'
162 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'
163)
Antoine Pitroud76088d2012-01-03 22:46:48 +0100164
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500165# Restricted and more secure ciphers for the server side
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# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
173# security reasons
174_RESTRICTED_SERVER_CIPHERS = (
175 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
176 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
177 '!eNULL:!MD5:!DSS:!RC4'
178)
179
180
181class CertificateError(ValueError):
182 pass
183
184
185def _dnsname_match(dn, hostname, max_wildcards=1):
186 """Matching according to RFC 6125, section 6.4.3
187
188 http://tools.ietf.org/html/rfc6125#section-6.4.3
189 """
190 pats = []
191 if not dn:
192 return False
193
194 pieces = dn.split(r'.')
195 leftmost = pieces[0]
196 remainder = pieces[1:]
197
198 wildcards = leftmost.count('*')
199 if wildcards > max_wildcards:
200 # Issue #17980: avoid denials of service by refusing more
201 # than one wildcard per fragment. A survery of established
202 # policy among SSL implementations showed it to be a
203 # reasonable choice.
204 raise CertificateError(
205 "too many wildcards in certificate DNS name: " + repr(dn))
206
207 # speed up common case w/o wildcards
208 if not wildcards:
209 return dn.lower() == hostname.lower()
210
211 # RFC 6125, section 6.4.3, subitem 1.
212 # The client SHOULD NOT attempt to match a presented identifier in which
213 # the wildcard character comprises a label other than the left-most label.
214 if leftmost == '*':
215 # When '*' is a fragment by itself, it matches a non-empty dotless
216 # fragment.
217 pats.append('[^.]+')
218 elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
219 # RFC 6125, section 6.4.3, subitem 3.
220 # The client SHOULD NOT attempt to match a presented identifier
221 # where the wildcard character is embedded within an A-label or
222 # U-label of an internationalized domain name.
223 pats.append(re.escape(leftmost))
224 else:
225 # Otherwise, '*' matches any dotless string, e.g. www*
226 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
227
228 # add the remaining fragments, ignore any wildcards
229 for frag in remainder:
230 pats.append(re.escape(frag))
231
232 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
233 return pat.match(hostname)
234
235
236def match_hostname(cert, hostname):
237 """Verify that *cert* (in decoded format as returned by
238 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
239 rules are followed, but IP addresses are not accepted for *hostname*.
240
241 CertificateError is raised on failure. On success, the function
242 returns nothing.
243 """
244 if not cert:
245 raise ValueError("empty or no certificate, match_hostname needs a "
246 "SSL socket or SSL context with either "
247 "CERT_OPTIONAL or CERT_REQUIRED")
248 dnsnames = []
249 san = cert.get('subjectAltName', ())
250 for key, value in san:
251 if key == 'DNS':
252 if _dnsname_match(value, hostname):
253 return
254 dnsnames.append(value)
255 if not dnsnames:
256 # The subject is only checked when there is no dNSName entry
257 # in subjectAltName
258 for sub in cert.get('subject', ()):
259 for key, value in sub:
260 # XXX according to RFC 2818, the most specific Common Name
261 # must be used.
262 if key == 'commonName':
263 if _dnsname_match(value, hostname):
264 return
265 dnsnames.append(value)
266 if len(dnsnames) > 1:
267 raise CertificateError("hostname %r "
268 "doesn't match either of %s"
269 % (hostname, ', '.join(map(repr, dnsnames))))
270 elif len(dnsnames) == 1:
271 raise CertificateError("hostname %r "
272 "doesn't match %r"
273 % (hostname, dnsnames[0]))
274 else:
275 raise CertificateError("no appropriate commonName or "
276 "subjectAltName fields were found")
277
278
279DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
280 "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
281 "openssl_capath")
282
283def get_default_verify_paths():
284 """Return paths to default cafile and capath.
285 """
286 parts = _ssl.get_default_verify_paths()
287
288 # environment vars shadow paths
289 cafile = os.environ.get(parts[0], parts[1])
290 capath = os.environ.get(parts[2], parts[3])
291
292 return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
293 capath if os.path.isdir(capath) else None,
294 *parts)
295
296
297class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
298 """ASN.1 object identifier lookup
299 """
300 __slots__ = ()
301
302 def __new__(cls, oid):
303 return super(_ASN1Object, cls).__new__(cls, *_txt2obj(oid, name=False))
304
305 @classmethod
306 def fromnid(cls, nid):
307 """Create _ASN1Object from OpenSSL numeric ID
308 """
309 return super(_ASN1Object, cls).__new__(cls, *_nid2obj(nid))
310
311 @classmethod
312 def fromname(cls, name):
313 """Create _ASN1Object from short name, long name or OID
314 """
315 return super(_ASN1Object, cls).__new__(cls, *_txt2obj(name, name=True))
316
317
318class Purpose(_ASN1Object):
319 """SSLContext purpose flags with X509v3 Extended Key Usage objects
320 """
321
322Purpose.SERVER_AUTH = Purpose('1.3.6.1.5.5.7.3.1')
323Purpose.CLIENT_AUTH = Purpose('1.3.6.1.5.5.7.3.2')
324
325
326class SSLContext(_SSLContext):
327 """An SSLContext holds various SSL-related configuration options and
328 data, such as certificates and possibly a private key."""
329
330 __slots__ = ('protocol', '__weakref__')
331 _windows_cert_stores = ("CA", "ROOT")
332
333 def __new__(cls, protocol, *args, **kwargs):
334 self = _SSLContext.__new__(cls, protocol)
335 if protocol != _SSLv2_IF_EXISTS:
336 self.set_ciphers(_DEFAULT_CIPHERS)
337 return self
338
339 def __init__(self, protocol):
340 self.protocol = protocol
341
342 def wrap_socket(self, sock, server_side=False,
343 do_handshake_on_connect=True,
344 suppress_ragged_eofs=True,
345 server_hostname=None):
346 return SSLSocket(sock=sock, server_side=server_side,
347 do_handshake_on_connect=do_handshake_on_connect,
348 suppress_ragged_eofs=suppress_ragged_eofs,
349 server_hostname=server_hostname,
350 _context=self)
351
352 def set_npn_protocols(self, npn_protocols):
353 protos = bytearray()
354 for protocol in npn_protocols:
355 b = protocol.encode('ascii')
356 if len(b) == 0 or len(b) > 255:
357 raise SSLError('NPN protocols must be 1 to 255 in length')
358 protos.append(len(b))
359 protos.extend(b)
360
361 self._set_npn_protocols(protos)
362
363 def _load_windows_store_certs(self, storename, purpose):
364 certs = bytearray()
365 for cert, encoding, trust in enum_certificates(storename):
366 # CA certs are never PKCS#7 encoded
367 if encoding == "x509_asn":
368 if trust is True or purpose.oid in trust:
369 certs.extend(cert)
370 self.load_verify_locations(cadata=certs)
371 return certs
372
373 def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
374 if not isinstance(purpose, _ASN1Object):
375 raise TypeError(purpose)
376 if sys.platform == "win32":
377 for storename in self._windows_cert_stores:
378 self._load_windows_store_certs(storename, purpose)
Benjamin Peterson0b30a2b2014-10-03 17:27:05 -0400379 self.set_default_verify_paths()
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500380
381
382def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None,
383 capath=None, cadata=None):
384 """Create a SSLContext object with default settings.
385
386 NOTE: The protocol and settings may change anytime without prior
387 deprecation. The values represent a fair balance between maximum
388 compatibility and security.
389 """
390 if not isinstance(purpose, _ASN1Object):
391 raise TypeError(purpose)
392
393 context = SSLContext(PROTOCOL_SSLv23)
394
395 # SSLv2 considered harmful.
396 context.options |= OP_NO_SSLv2
397
398 # SSLv3 has problematic security and is only required for really old
399 # clients such as IE6 on Windows XP
400 context.options |= OP_NO_SSLv3
401
402 # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
403 context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
404
405 if purpose == Purpose.SERVER_AUTH:
406 # verify certs and host name in client mode
407 context.verify_mode = CERT_REQUIRED
408 context.check_hostname = True
409 elif purpose == Purpose.CLIENT_AUTH:
410 # Prefer the server's ciphers by default so that we get stronger
411 # encryption
412 context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
413
414 # Use single use keys in order to improve forward secrecy
415 context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
416 context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
417
418 # disallow ciphers with known vulnerabilities
419 context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
420
421 if cafile or capath or cadata:
422 context.load_verify_locations(cafile, capath, cadata)
423 elif context.verify_mode != CERT_NONE:
424 # no explicit cafile, capath or cadata but the verify mode is
425 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
426 # root CA certificates for the given purpose. This may fail silently.
427 context.load_default_certs(purpose)
428 return context
429
430
431def _create_stdlib_context(protocol=PROTOCOL_SSLv23, cert_reqs=None,
432 check_hostname=False, purpose=Purpose.SERVER_AUTH,
433 certfile=None, keyfile=None,
434 cafile=None, capath=None, cadata=None):
435 """Create a SSLContext object for Python stdlib modules
436
437 All Python stdlib modules shall use this function to create SSLContext
438 objects in order to keep common settings in one place. The configuration
439 is less restrict than create_default_context()'s to increase backward
440 compatibility.
441 """
442 if not isinstance(purpose, _ASN1Object):
443 raise TypeError(purpose)
444
445 context = SSLContext(protocol)
446 # SSLv2 considered harmful.
447 context.options |= OP_NO_SSLv2
448
449 if cert_reqs is not None:
450 context.verify_mode = cert_reqs
451 context.check_hostname = check_hostname
452
453 if keyfile and not certfile:
454 raise ValueError("certfile must be specified")
455 if certfile or keyfile:
456 context.load_cert_chain(certfile, keyfile)
457
458 # load CA root certs
459 if cafile or capath or cadata:
460 context.load_verify_locations(cafile, capath, cadata)
461 elif context.verify_mode != CERT_NONE:
462 # no explicit cafile, capath or cadata but the verify mode is
463 # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
464 # root CA certificates for the given purpose. This may fail silently.
465 context.load_default_certs(purpose)
466
467 return context
Antoine Pitroud76088d2012-01-03 22:46:48 +0100468
Ezio Melottib01f5e62010-01-18 09:10:26 +0000469class SSLSocket(socket):
Bill Janssen426ea0a2007-08-29 22:35:05 +0000470 """This class implements a subtype of socket.socket that wraps
471 the underlying OS socket in an SSL context when necessary, and
472 provides read and write methods over that channel."""
473
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500474 def __init__(self, sock=None, keyfile=None, certfile=None,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000475 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen934b16d2008-06-28 22:19:33 +0000476 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
477 do_handshake_on_connect=True,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500478 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
479 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
480 server_hostname=None,
481 _context=None):
482
483 if _context:
484 self._context = _context
485 else:
486 if server_side and not certfile:
487 raise ValueError("certfile must be specified for server-side "
488 "operations")
489 if keyfile and not certfile:
490 raise ValueError("certfile must be specified")
491 if certfile and not keyfile:
492 keyfile = certfile
493 self._context = SSLContext(ssl_version)
494 self._context.verify_mode = cert_reqs
495 if ca_certs:
496 self._context.load_verify_locations(ca_certs)
497 if certfile:
498 self._context.load_cert_chain(certfile, keyfile)
499 if npn_protocols:
500 self._context.set_npn_protocols(npn_protocols)
501 if ciphers:
502 self._context.set_ciphers(ciphers)
503 self.keyfile = keyfile
504 self.certfile = certfile
505 self.cert_reqs = cert_reqs
506 self.ssl_version = ssl_version
507 self.ca_certs = ca_certs
508 self.ciphers = ciphers
Antoine Pitrou63cc99d2013-12-28 17:26:33 +0100509 # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
510 # mixed in.
511 if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
512 raise NotImplementedError("only stream sockets are supported")
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000513 socket.__init__(self, _sock=sock._sock)
Antoine Pitroudfb299b2010-04-23 22:54:59 +0000514 # The initializer for socket overrides the methods send(), recv(), etc.
515 # in the instancce, which we don't need -- but we want to provide the
516 # methods defined in SSLSocket.
517 for attr in _delegate_methods:
518 try:
519 delattr(self, attr)
520 except AttributeError:
521 pass
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500522 if server_side and server_hostname:
523 raise ValueError("server_hostname can only be specified "
524 "in client mode")
525 if self._context.check_hostname and not server_hostname:
526 if HAS_SNI:
527 raise ValueError("check_hostname requires server_hostname")
528 else:
529 raise ValueError("check_hostname requires server_hostname, "
530 "but it's not supported by your OpenSSL "
531 "library")
532 self.server_side = server_side
533 self.server_hostname = server_hostname
Bill Janssen934b16d2008-06-28 22:19:33 +0000534 self.do_handshake_on_connect = do_handshake_on_connect
535 self.suppress_ragged_eofs = suppress_ragged_eofs
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500536
537 # See if we are connected
538 try:
539 self.getpeername()
540 except socket_error as e:
541 if e.errno != errno.ENOTCONN:
542 raise
543 connected = False
544 else:
545 connected = True
546
547 self._closed = False
548 self._sslobj = None
549 self._connected = connected
550 if connected:
551 # create the SSL object
552 try:
553 self._sslobj = self._context._wrap_socket(self._sock, server_side,
554 server_hostname, ssl_sock=self)
555 if do_handshake_on_connect:
556 timeout = self.gettimeout()
557 if timeout == 0.0:
558 # non-blocking
559 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
560 self.do_handshake()
561
562 except (OSError, ValueError):
563 self.close()
564 raise
Bill Janssen934b16d2008-06-28 22:19:33 +0000565 self._makefile_refs = 0
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000566
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500567 @property
568 def context(self):
569 return self._context
Bill Janssen24bccf22007-08-30 17:07:28 +0000570
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500571 @context.setter
572 def context(self, ctx):
573 self._context = ctx
574 self._sslobj.context = ctx
575
576 def dup(self):
577 raise NotImplemented("Can't dup() %s instances" %
578 self.__class__.__name__)
579
580 def _checkClosed(self, msg=None):
581 # raise an exception here if you wish to check for spurious closes
582 pass
583
584 def _check_connected(self):
585 if not self._connected:
586 # getpeername() will raise ENOTCONN if the socket is really
587 # not connected; note that we can be connected even without
588 # _connected being set, e.g. if connect() first returned
589 # EAGAIN.
590 self.getpeername()
591
592 def read(self, len=0, buffer=None):
Bill Janssen24bccf22007-08-30 17:07:28 +0000593 """Read up to LEN bytes and return them.
594 Return zero-length string on EOF."""
595
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500596 self._checkClosed()
597 if not self._sslobj:
598 raise ValueError("Read on closed or unwrapped SSL socket.")
Bill Janssen934b16d2008-06-28 22:19:33 +0000599 try:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500600 if buffer is not None:
601 v = self._sslobj.read(len, buffer)
602 else:
603 v = self._sslobj.read(len or 1024)
604 return v
605 except SSLError as x:
Bill Janssen934b16d2008-06-28 22:19:33 +0000606 if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500607 if buffer is not None:
608 return 0
609 else:
610 return b''
Bill Janssen934b16d2008-06-28 22:19:33 +0000611 else:
612 raise
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000613
614 def write(self, data):
Bill Janssen24bccf22007-08-30 17:07:28 +0000615 """Write DATA to the underlying SSL channel. Returns
616 number of bytes of DATA actually transmitted."""
617
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500618 self._checkClosed()
619 if not self._sslobj:
620 raise ValueError("Write on closed or unwrapped SSL socket.")
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000621 return self._sslobj.write(data)
622
Bill Janssen98d19da2007-09-10 21:51:02 +0000623 def getpeercert(self, binary_form=False):
Bill Janssen24bccf22007-08-30 17:07:28 +0000624 """Returns a formatted version of the data in the
625 certificate provided by the other end of the SSL channel.
626 Return None if no certificate was provided, {} if a
627 certificate was provided, but not validated."""
628
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500629 self._checkClosed()
630 self._check_connected()
Bill Janssen98d19da2007-09-10 21:51:02 +0000631 return self._sslobj.peer_certificate(binary_form)
632
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500633 def selected_npn_protocol(self):
634 self._checkClosed()
635 if not self._sslobj or not _ssl.HAS_NPN:
636 return None
637 else:
638 return self._sslobj.selected_npn_protocol()
Bill Janssen98d19da2007-09-10 21:51:02 +0000639
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500640 def cipher(self):
641 self._checkClosed()
Bill Janssen98d19da2007-09-10 21:51:02 +0000642 if not self._sslobj:
643 return None
644 else:
645 return self._sslobj.cipher()
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000646
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500647 def compression(self):
648 self._checkClosed()
649 if not self._sslobj:
650 return None
651 else:
652 return self._sslobj.compression()
653
Ezio Melottib01f5e62010-01-18 09:10:26 +0000654 def send(self, data, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500655 self._checkClosed()
Bill Janssen426ea0a2007-08-29 22:35:05 +0000656 if self._sslobj:
657 if flags != 0:
658 raise ValueError(
659 "non-zero flags not allowed in calls to send() on %s" %
660 self.__class__)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500661 try:
662 v = self._sslobj.write(data)
663 except SSLError as x:
664 if x.args[0] == SSL_ERROR_WANT_READ:
665 return 0
666 elif x.args[0] == SSL_ERROR_WANT_WRITE:
667 return 0
Bill Janssen934b16d2008-06-28 22:19:33 +0000668 else:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500669 raise
670 else:
671 return v
Bill Janssen426ea0a2007-08-29 22:35:05 +0000672 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000673 return self._sock.send(data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000674
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000675 def sendto(self, data, flags_or_addr, addr=None):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500676 self._checkClosed()
Bill Janssen426ea0a2007-08-29 22:35:05 +0000677 if self._sslobj:
Bill Janssen934b16d2008-06-28 22:19:33 +0000678 raise ValueError("sendto not allowed on instances of %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000679 self.__class__)
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000680 elif addr is None:
681 return self._sock.sendto(data, flags_or_addr)
Bill Janssen426ea0a2007-08-29 22:35:05 +0000682 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000683 return self._sock.sendto(data, flags_or_addr, addr)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000684
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500685
Ezio Melottib01f5e62010-01-18 09:10:26 +0000686 def sendall(self, data, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500687 self._checkClosed()
Bill Janssen426ea0a2007-08-29 22:35:05 +0000688 if self._sslobj:
689 if flags != 0:
690 raise ValueError(
691 "non-zero flags not allowed in calls to sendall() on %s" %
692 self.__class__)
Bill Janssen934b16d2008-06-28 22:19:33 +0000693 amount = len(data)
694 count = 0
695 while (count < amount):
696 v = self.send(data[count:])
697 count += v
698 return amount
Bill Janssen426ea0a2007-08-29 22:35:05 +0000699 else:
700 return socket.sendall(self, data, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000701
Ezio Melottib01f5e62010-01-18 09:10:26 +0000702 def recv(self, buflen=1024, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500703 self._checkClosed()
Bill Janssen426ea0a2007-08-29 22:35:05 +0000704 if self._sslobj:
705 if flags != 0:
706 raise ValueError(
Antoine Pitrou448da712010-03-21 19:33:38 +0000707 "non-zero flags not allowed in calls to recv() on %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000708 self.__class__)
Antoine Pitrou448da712010-03-21 19:33:38 +0000709 return self.read(buflen)
Bill Janssen426ea0a2007-08-29 22:35:05 +0000710 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000711 return self._sock.recv(buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000712
Ezio Melottib01f5e62010-01-18 09:10:26 +0000713 def recv_into(self, buffer, nbytes=None, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500714 self._checkClosed()
Bill Janssen61c001a2008-09-08 16:37:24 +0000715 if buffer and (nbytes is None):
716 nbytes = len(buffer)
717 elif nbytes is None:
718 nbytes = 1024
719 if self._sslobj:
720 if flags != 0:
721 raise ValueError(
722 "non-zero flags not allowed in calls to recv_into() on %s" %
723 self.__class__)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500724 return self.read(nbytes, buffer)
Bill Janssen61c001a2008-09-08 16:37:24 +0000725 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000726 return self._sock.recv_into(buffer, nbytes, flags)
Bill Janssen61c001a2008-09-08 16:37:24 +0000727
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000728 def recvfrom(self, buflen=1024, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500729 self._checkClosed()
Bill Janssen426ea0a2007-08-29 22:35:05 +0000730 if self._sslobj:
Bill Janssen934b16d2008-06-28 22:19:33 +0000731 raise ValueError("recvfrom not allowed on instances of %s" %
Bill Janssen426ea0a2007-08-29 22:35:05 +0000732 self.__class__)
733 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000734 return self._sock.recvfrom(buflen, flags)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000735
Ezio Melottib01f5e62010-01-18 09:10:26 +0000736 def recvfrom_into(self, buffer, nbytes=None, flags=0):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500737 self._checkClosed()
Bill Janssen61c001a2008-09-08 16:37:24 +0000738 if self._sslobj:
739 raise ValueError("recvfrom_into not allowed on instances of %s" %
740 self.__class__)
741 else:
Antoine Pitrouf7f390a2010-09-14 14:37:18 +0000742 return self._sock.recvfrom_into(buffer, nbytes, flags)
Bill Janssen61c001a2008-09-08 16:37:24 +0000743
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500744
Ezio Melottib01f5e62010-01-18 09:10:26 +0000745 def pending(self):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500746 self._checkClosed()
Bill Janssen934b16d2008-06-28 22:19:33 +0000747 if self._sslobj:
748 return self._sslobj.pending()
749 else:
750 return 0
751
Ezio Melottib01f5e62010-01-18 09:10:26 +0000752 def shutdown(self, how):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500753 self._checkClosed()
Bill Janssen296a59d2007-09-16 22:06:00 +0000754 self._sslobj = None
Bill Janssen426ea0a2007-08-29 22:35:05 +0000755 socket.shutdown(self, how)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000756
Ezio Melottib01f5e62010-01-18 09:10:26 +0000757 def close(self):
Bill Janssen934b16d2008-06-28 22:19:33 +0000758 if self._makefile_refs < 1:
759 self._sslobj = None
760 socket.close(self)
761 else:
762 self._makefile_refs -= 1
763
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500764 def unwrap(self):
765 if self._sslobj:
766 s = self._sslobj.shutdown()
767 self._sslobj = None
768 return s
769 else:
770 raise ValueError("No SSL wrapper around " + str(self))
Bill Janssen934b16d2008-06-28 22:19:33 +0000771
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500772 def _real_close(self):
773 self._sslobj = None
774 socket._real_close(self)
775
776 def do_handshake(self, block=False):
Bill Janssen934b16d2008-06-28 22:19:33 +0000777 """Perform a TLS/SSL handshake."""
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500778 self._check_connected()
779 timeout = self.gettimeout()
780 try:
781 if timeout == 0.0 and block:
782 self.settimeout(None)
783 self._sslobj.do_handshake()
784 finally:
785 self.settimeout(timeout)
Bill Janssen934b16d2008-06-28 22:19:33 +0000786
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500787 if self.context.check_hostname:
788 if not self.server_hostname:
789 raise ValueError("check_hostname needs server_hostname "
790 "argument")
791 match_hostname(self.getpeercert(), self.server_hostname)
Bill Janssen934b16d2008-06-28 22:19:33 +0000792
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500793 def _real_connect(self, addr, connect_ex):
794 if self.server_side:
795 raise ValueError("can't connect in server-side mode")
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000796 # Here we assume that the socket is client-side, and not
797 # connected at the time of the call. We connect it, then wrap it.
Antoine Pitroud3f6ea12011-02-26 23:35:27 +0000798 if self._connected:
Bill Janssen98d19da2007-09-10 21:51:02 +0000799 raise ValueError("attempt to connect already-connected SSLSocket!")
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500800 self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname, ssl_sock=self)
Antoine Pitroud3f6ea12011-02-26 23:35:27 +0000801 try:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500802 if connect_ex:
Antoine Pitrou40f12ab2012-12-28 19:03:43 +0100803 rc = socket.connect_ex(self, addr)
Antoine Pitroud3f6ea12011-02-26 23:35:27 +0000804 else:
Antoine Pitrou40f12ab2012-12-28 19:03:43 +0100805 rc = None
806 socket.connect(self, addr)
807 if not rc:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500808 self._connected = True
Antoine Pitrou40f12ab2012-12-28 19:03:43 +0100809 if self.do_handshake_on_connect:
810 self.do_handshake()
Antoine Pitrou40f12ab2012-12-28 19:03:43 +0100811 return rc
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500812 except (OSError, ValueError):
Antoine Pitrou40f12ab2012-12-28 19:03:43 +0100813 self._sslobj = None
814 raise
Antoine Pitroud3f6ea12011-02-26 23:35:27 +0000815
816 def connect(self, addr):
817 """Connects to remote ADDR, and then wraps the connection in
818 an SSL channel."""
819 self._real_connect(addr, False)
820
821 def connect_ex(self, addr):
822 """Connects to remote ADDR, and then wraps the connection in
823 an SSL channel."""
824 return self._real_connect(addr, True)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000825
826 def accept(self):
Bill Janssen24bccf22007-08-30 17:07:28 +0000827 """Accepts a new connection from a remote client, and returns
828 a tuple containing that new connection wrapped with a server-side
829 SSL channel, and the address of the remote client."""
830
Bill Janssen426ea0a2007-08-29 22:35:05 +0000831 newsock, addr = socket.accept(self)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500832 newsock = self.context.wrap_socket(newsock,
833 do_handshake_on_connect=self.do_handshake_on_connect,
834 suppress_ragged_eofs=self.suppress_ragged_eofs,
835 server_side=True)
836 return newsock, addr
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000837
Bill Janssen296a59d2007-09-16 22:06:00 +0000838 def makefile(self, mode='r', bufsize=-1):
839
Bill Janssen61c001a2008-09-08 16:37:24 +0000840 """Make and return a file-like object that
841 works with the SSL connection. Just use the code
842 from the socket module."""
Bill Janssen296a59d2007-09-16 22:06:00 +0000843
Bill Janssen934b16d2008-06-28 22:19:33 +0000844 self._makefile_refs += 1
Antoine Pitroub558f172010-04-23 23:25:45 +0000845 # close=True so as to decrement the reference count when done with
846 # the file-like object.
847 return _fileobject(self, mode, bufsize, close=True)
Bill Janssen296a59d2007-09-16 22:06:00 +0000848
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500849 def get_channel_binding(self, cb_type="tls-unique"):
850 """Get channel binding data for current connection. Raise ValueError
851 if the requested `cb_type` is not supported. Return bytes of the data
852 or None if the data is not available (e.g. before the handshake).
853 """
854 if cb_type not in CHANNEL_BINDING_TYPES:
855 raise ValueError("Unsupported channel binding type")
856 if cb_type != "tls-unique":
857 raise NotImplementedError(
858 "{0} channel binding type not implemented"
859 .format(cb_type))
860 if self._sslobj is None:
861 return None
862 return self._sslobj.tls_unique_cb()
Bill Janssen296a59d2007-09-16 22:06:00 +0000863
Alex Gaynore98205d2014-09-04 13:33:22 -0700864 def version(self):
865 """
866 Return a string identifying the protocol version used by the
867 current SSL channel, or None if there is no established channel.
868 """
869 if self._sslobj is None:
870 return None
871 return self._sslobj.version()
872
Bill Janssen296a59d2007-09-16 22:06:00 +0000873
Bill Janssen98d19da2007-09-10 21:51:02 +0000874def wrap_socket(sock, keyfile=None, certfile=None,
875 server_side=False, cert_reqs=CERT_NONE,
Bill Janssen934b16d2008-06-28 22:19:33 +0000876 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
877 do_handshake_on_connect=True,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500878 suppress_ragged_eofs=True,
879 ciphers=None):
Bill Janssen98d19da2007-09-10 21:51:02 +0000880
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500881 return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
Bill Janssen98d19da2007-09-10 21:51:02 +0000882 server_side=server_side, cert_reqs=cert_reqs,
Bill Janssen934b16d2008-06-28 22:19:33 +0000883 ssl_version=ssl_version, ca_certs=ca_certs,
884 do_handshake_on_connect=do_handshake_on_connect,
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000885 suppress_ragged_eofs=suppress_ragged_eofs,
886 ciphers=ciphers)
Bill Janssen934b16d2008-06-28 22:19:33 +0000887
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000888# some utility functions
889
890def cert_time_to_seconds(cert_time):
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500891 """Return the time in seconds since the Epoch, given the timestring
892 representing the "notBefore" or "notAfter" date from a certificate
893 in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
Bill Janssen24bccf22007-08-30 17:07:28 +0000894
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500895 "notBefore" or "notAfter" dates must use UTC (RFC 5280).
Bill Janssen24bccf22007-08-30 17:07:28 +0000896
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500897 Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
898 UTC should be specified as GMT (see ASN1_TIME_print())
899 """
900 from time import strptime
901 from calendar import timegm
902
903 months = (
904 "Jan","Feb","Mar","Apr","May","Jun",
905 "Jul","Aug","Sep","Oct","Nov","Dec"
906 )
907 time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
908 try:
909 month_number = months.index(cert_time[:3].title()) + 1
910 except ValueError:
911 raise ValueError('time data %r does not match '
912 'format "%%b%s"' % (cert_time, time_format))
913 else:
914 # found valid month
915 tt = strptime(cert_time[3:], time_format)
916 # return an integer, the previous mktime()-based implementation
917 # returned a float (fractional seconds are always zero here).
918 return timegm((tt[0], month_number) + tt[2:6])
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000919
Bill Janssen296a59d2007-09-16 22:06:00 +0000920PEM_HEADER = "-----BEGIN CERTIFICATE-----"
921PEM_FOOTER = "-----END CERTIFICATE-----"
922
923def DER_cert_to_PEM_cert(der_cert_bytes):
Bill Janssen296a59d2007-09-16 22:06:00 +0000924 """Takes a certificate in binary DER format and returns the
925 PEM version of it as a string."""
926
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500927 f = base64.standard_b64encode(der_cert_bytes).decode('ascii')
928 return (PEM_HEADER + '\n' +
929 textwrap.fill(f, 64) + '\n' +
930 PEM_FOOTER + '\n')
Bill Janssen296a59d2007-09-16 22:06:00 +0000931
932def PEM_cert_to_DER_cert(pem_cert_string):
Bill Janssen296a59d2007-09-16 22:06:00 +0000933 """Takes a certificate in ASCII PEM format and returns the
934 DER-encoded version of it as a byte sequence"""
935
936 if not pem_cert_string.startswith(PEM_HEADER):
937 raise ValueError("Invalid PEM encoding; must start with %s"
938 % PEM_HEADER)
939 if not pem_cert_string.strip().endswith(PEM_FOOTER):
940 raise ValueError("Invalid PEM encoding; must end with %s"
941 % PEM_FOOTER)
942 d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500943 return base64.decodestring(d.encode('ASCII', 'strict'))
Bill Janssen296a59d2007-09-16 22:06:00 +0000944
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500945def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
Bill Janssen296a59d2007-09-16 22:06:00 +0000946 """Retrieve the certificate from the server at the specified address,
947 and return it as a PEM-encoded string.
948 If 'ca_certs' is specified, validate the server cert against it.
949 If 'ssl_version' is specified, use it in the connection attempt."""
950
951 host, port = addr
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500952 if ca_certs is not None:
Bill Janssen296a59d2007-09-16 22:06:00 +0000953 cert_reqs = CERT_REQUIRED
954 else:
955 cert_reqs = CERT_NONE
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500956 context = _create_stdlib_context(ssl_version,
957 cert_reqs=cert_reqs,
958 cafile=ca_certs)
959 with closing(create_connection(addr)) as sock:
960 with closing(context.wrap_socket(sock)) as sslsock:
961 dercert = sslsock.getpeercert(True)
Bill Janssen296a59d2007-09-16 22:06:00 +0000962 return DER_cert_to_PEM_cert(dercert)
963
Ezio Melottib01f5e62010-01-18 09:10:26 +0000964def get_protocol_name(protocol_code):
Victor Stinnerb1241f92011-05-10 01:52:03 +0200965 return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')
Bill Janssen296a59d2007-09-16 22:06:00 +0000966
967
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000968# a replacement for the old socket.ssl function
969
Ezio Melottib01f5e62010-01-18 09:10:26 +0000970def sslwrap_simple(sock, keyfile=None, certfile=None):
Bill Janssen24bccf22007-08-30 17:07:28 +0000971 """A replacement for the old socket.ssl function. Designed
972 for compability with Python 2.5 and earlier. Will disappear in
973 Python 3.0."""
Bill Jansseneb257ac2008-09-29 18:56:38 +0000974 if hasattr(sock, "_sock"):
975 sock = sock._sock
976
Benjamin Peterson2f334562014-10-01 23:53:01 -0400977 ctx = SSLContext(PROTOCOL_SSLv23)
978 if keyfile or certfile:
979 ctx.load_cert_chain(certfile, keyfile)
980 ssl_sock = ctx._wrap_socket(sock, server_side=False)
Bill Jansseneb257ac2008-09-29 18:56:38 +0000981 try:
982 sock.getpeername()
Benjamin Peterson941db4d2008-12-31 04:08:55 +0000983 except socket_error:
Bill Jansseneb257ac2008-09-29 18:56:38 +0000984 # no, no connection yet
985 pass
986 else:
987 # yes, do the handshake
988 ssl_sock.do_handshake()
989
Bill Janssen934b16d2008-06-28 22:19:33 +0000990 return ssl_sock