Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(168389)

Delta Between Two Patch Sets: Lib/test/test_ssl.py

Issue 23001: Accept mutable bytes-like objects
Left Patch Set: Created 5 years ago
Right Patch Set: Created 4 years, 9 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
LEFTRIGHT
1 # Test the support for SSL and sockets 1 # Test the support for SSL and sockets
2 2
3 import sys 3 import sys
4 import unittest 4 import unittest
5 from test import support 5 from test import support
6 import socket 6 import socket
7 import select 7 import select
8 import time 8 import time
9 import datetime 9 import datetime
10 import gc 10 import gc
11 import os 11 import os
12 import errno 12 import errno
13 import pprint 13 import pprint
14 import tempfile 14 import tempfile
15 import urllib.request 15 import urllib.request
16 import traceback 16 import traceback
17 import asyncore 17 import asyncore
18 import weakref 18 import weakref
19 import platform 19 import platform
20 import functools 20 import functools
21 from unittest import mock
22 21
23 ssl = support.import_module("ssl") 22 ssl = support.import_module("ssl")
24 23
25 PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) 24 PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
26 HOST = support.HOST 25 HOST = support.HOST
27 26
28 def data_file(*name): 27 def data_file(*name):
29 return os.path.join(os.path.dirname(__file__), *name) 28 return os.path.join(os.path.dirname(__file__), *name)
30 29
31 # The custom key and certificate files used in test_ssl are generated 30 # The custom key and certificate files used in test_ssl are generated
(...skipping 104 matching lines...) Expand 10 before | Expand all | Expand 10 after
136 if ssl.HAS_ECDH: 135 if ssl.HAS_ECDH:
137 ssl.OP_SINGLE_ECDH_USE 136 ssl.OP_SINGLE_ECDH_USE
138 if ssl.OPENSSL_VERSION_INFO >= (1, 0): 137 if ssl.OPENSSL_VERSION_INFO >= (1, 0):
139 ssl.OP_NO_COMPRESSION 138 ssl.OP_NO_COMPRESSION
140 self.assertIn(ssl.HAS_SNI, {True, False}) 139 self.assertIn(ssl.HAS_SNI, {True, False})
141 self.assertIn(ssl.HAS_ECDH, {True, False}) 140 self.assertIn(ssl.HAS_ECDH, {True, False})
142 141
143 def test_str_for_enums(self): 142 def test_str_for_enums(self):
144 # Make sure that the PROTOCOL_* constants have enum-like string 143 # Make sure that the PROTOCOL_* constants have enum-like string
145 # reprs. 144 # reprs.
146 proto = ssl.PROTOCOL_SSLv3 145 proto = ssl.PROTOCOL_SSLv23
147 self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_SSLv3') 146 self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_SSLv23')
148 ctx = ssl.SSLContext(proto) 147 ctx = ssl.SSLContext(proto)
149 self.assertIs(ctx.protocol, proto) 148 self.assertIs(ctx.protocol, proto)
150 149
151 def test_random(self): 150 def test_random(self):
152 v = ssl.RAND_status() 151 v = ssl.RAND_status()
153 if support.verbose: 152 if support.verbose:
154 sys.stdout.write("\n RAND_status is %d (%s)\n" 153 sys.stdout.write("\n RAND_status is %d (%s)\n"
155 % (v, (v and "sufficient randomness") or 154 % (v, (v and "sufficient randomness") or
156 "insufficient randomness")) 155 "insufficient randomness"))
157 156
(...skipping 143 matching lines...) Expand 10 before | Expand all | Expand 10 after
301 # < 3.0 300 # < 3.0
302 self.assertLess(n, 0x30000000) 301 self.assertLess(n, 0x30000000)
303 major, minor, fix, patch, status = t 302 major, minor, fix, patch, status = t
304 self.assertGreaterEqual(major, 0) 303 self.assertGreaterEqual(major, 0)
305 self.assertLess(major, 3) 304 self.assertLess(major, 3)
306 self.assertGreaterEqual(minor, 0) 305 self.assertGreaterEqual(minor, 0)
307 self.assertLess(minor, 256) 306 self.assertLess(minor, 256)
308 self.assertGreaterEqual(fix, 0) 307 self.assertGreaterEqual(fix, 0)
309 self.assertLess(fix, 256) 308 self.assertLess(fix, 256)
310 self.assertGreaterEqual(patch, 0) 309 self.assertGreaterEqual(patch, 0)
311 self.assertLessEqual(patch, 26) 310 self.assertLessEqual(patch, 63)
312 self.assertGreaterEqual(status, 0) 311 self.assertGreaterEqual(status, 0)
313 self.assertLessEqual(status, 15) 312 self.assertLessEqual(status, 15)
314 # Version string as returned by {Open,Libre}SSL, the format might change 313 # Version string as returned by {Open,Libre}SSL, the format might change
315 if "LibreSSL" in s: 314 if "LibreSSL" in s:
316 self.assertTrue(s.startswith("LibreSSL {:d}.{:d}".format(major, mino r)), 315 self.assertTrue(s.startswith("LibreSSL {:d}.{:d}".format(major, mino r)),
317 (s, t)) 316 (s, t, hex(n)))
318 else: 317 else:
319 self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)), 318 self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
320 (s, t)) 319 (s, t, hex(n)))
321 320
322 @support.cpython_only 321 @support.cpython_only
323 def test_refcycle(self): 322 def test_refcycle(self):
324 # Issue #7943: an SSL object doesn't create reference cycles with 323 # Issue #7943: an SSL object doesn't create reference cycles with
325 # itself. 324 # itself.
326 s = socket.socket(socket.AF_INET) 325 s = socket.socket(socket.AF_INET)
327 ss = ssl.wrap_socket(s) 326 ss = ssl.wrap_socket(s)
328 wr = weakref.ref(ss) 327 wr = weakref.ref(ss)
329 with support.check_warnings(("", ResourceWarning)): 328 with support.check_warnings(("", ResourceWarning)):
330 del ss 329 del ss
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
378 ssl.wrap_socket(sock, certfile=WRONGCERT, keyfile=WRONGCERT) 377 ssl.wrap_socket(sock, certfile=WRONGCERT, keyfile=WRONGCERT)
379 self.assertEqual(cm.exception.errno, errno.ENOENT) 378 self.assertEqual(cm.exception.errno, errno.ENOENT)
380 379
381 def test_match_hostname(self): 380 def test_match_hostname(self):
382 def ok(cert, hostname): 381 def ok(cert, hostname):
383 ssl.match_hostname(cert, hostname) 382 ssl.match_hostname(cert, hostname)
384 def fail(cert, hostname): 383 def fail(cert, hostname):
385 self.assertRaises(ssl.CertificateError, 384 self.assertRaises(ssl.CertificateError,
386 ssl.match_hostname, cert, hostname) 385 ssl.match_hostname, cert, hostname)
387 386
387 # -- Hostname matching --
388
388 cert = {'subject': ((('commonName', 'example.com'),),)} 389 cert = {'subject': ((('commonName', 'example.com'),),)}
389 ok(cert, 'example.com') 390 ok(cert, 'example.com')
390 ok(cert, 'ExAmple.cOm') 391 ok(cert, 'ExAmple.cOm')
391 fail(cert, 'www.example.com') 392 fail(cert, 'www.example.com')
392 fail(cert, '.example.com') 393 fail(cert, '.example.com')
393 fail(cert, 'example.org') 394 fail(cert, 'example.org')
394 fail(cert, 'exampleXcom') 395 fail(cert, 'exampleXcom')
395 396
396 cert = {'subject': ((('commonName', '*.a.com'),),)} 397 cert = {'subject': ((('commonName', '*.a.com'),),)}
397 ok(cert, 'foo.a.com') 398 ok(cert, 'foo.a.com')
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
462 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', 463 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
463 'subject': ((('countryName', 'US'),), 464 'subject': ((('countryName', 'US'),),
464 (('stateOrProvinceName', 'California'),), 465 (('stateOrProvinceName', 'California'),),
465 (('localityName', 'Mountain View'),), 466 (('localityName', 'Mountain View'),),
466 (('organizationName', 'Google Inc'),), 467 (('organizationName', 'Google Inc'),),
467 (('commonName', 'mail.google.com'),))} 468 (('commonName', 'mail.google.com'),))}
468 ok(cert, 'mail.google.com') 469 ok(cert, 'mail.google.com')
469 fail(cert, 'gmail.com') 470 fail(cert, 'gmail.com')
470 # Only commonName is considered 471 # Only commonName is considered
471 fail(cert, 'California') 472 fail(cert, 'California')
473
474 # -- IPv4 matching --
475 cert = {'subject': ((('commonName', 'example.com'),),),
476 'subjectAltName': (('DNS', 'example.com'),
477 ('IP Address', '10.11.12.13'),
478 ('IP Address', '14.15.16.17'))}
479 ok(cert, '10.11.12.13')
480 ok(cert, '14.15.16.17')
481 fail(cert, '14.15.16.18')
482 fail(cert, 'example.net')
483
484 # -- IPv6 matching --
485 cert = {'subject': ((('commonName', 'example.com'),),),
486 'subjectAltName': (('DNS', 'example.com'),
487 ('IP Address', '2001:0:0:0:0:0:0:CAFE\n'),
488 ('IP Address', '2003:0:0:0:0:0:0:BABA\n'))}
489 ok(cert, '2001::cafe')
490 ok(cert, '2003::baba')
491 fail(cert, '2003::bebe')
492 fail(cert, 'example.net')
493
494 # -- Miscellaneous --
472 495
473 # Neither commonName nor subjectAltName 496 # Neither commonName nor subjectAltName
474 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', 497 cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT',
475 'subject': ((('countryName', 'US'),), 498 'subject': ((('countryName', 'US'),),
476 (('stateOrProvinceName', 'California'),), 499 (('stateOrProvinceName', 'California'),),
477 (('localityName', 'Mountain View'),), 500 (('localityName', 'Mountain View'),),
478 (('organizationName', 'Google Inc'),))} 501 (('organizationName', 'Google Inc'),))}
479 fail(cert, 'mail.google.com') 502 fail(cert, 'mail.google.com')
480 503
481 # No DNS entry in subjectAltName but a commonName 504 # No DNS entry in subjectAltName but a commonName
(...skipping 307 matching lines...) Expand 10 before | Expand all | Expand 10 after
789 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) 812 self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
790 with self.assertRaises(TypeError): 813 with self.assertRaises(TypeError):
791 ctx.verify_mode = None 814 ctx.verify_mode = None
792 with self.assertRaises(ValueError): 815 with self.assertRaises(ValueError):
793 ctx.verify_mode = 42 816 ctx.verify_mode = 42
794 817
795 @unittest.skipUnless(have_verify_flags(), 818 @unittest.skipUnless(have_verify_flags(),
796 "verify_flags need OpenSSL > 0.9.8") 819 "verify_flags need OpenSSL > 0.9.8")
797 def test_verify_flags(self): 820 def test_verify_flags(self):
798 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 821 ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
799 # default value by OpenSSL 822 # default value
800 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT) 823 tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
824 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf)
801 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF 825 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
802 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF) 826 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF)
803 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN 827 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
804 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN) 828 self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN)
805 ctx.verify_flags = ssl.VERIFY_DEFAULT 829 ctx.verify_flags = ssl.VERIFY_DEFAULT
806 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT) 830 self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT)
807 # supports any value 831 # supports any value
808 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT 832 ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT
809 self.assertEqual(ctx.verify_flags, 833 self.assertEqual(ctx.verify_flags,
810 ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT) 834 ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT)
(...skipping 882 matching lines...) Expand 10 before | Expand all | Expand 10 after
1693 sock.connect(("svn.python.org", 443)) 1717 sock.connect(("svn.python.org", 443))
1694 incoming = ssl.MemoryBIO() 1718 incoming = ssl.MemoryBIO()
1695 outgoing = ssl.MemoryBIO() 1719 outgoing = ssl.MemoryBIO()
1696 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 1720 ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1697 ctx.verify_mode = ssl.CERT_REQUIRED 1721 ctx.verify_mode = ssl.CERT_REQUIRED
1698 ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) 1722 ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT)
1699 ctx.check_hostname = True 1723 ctx.check_hostname = True
1700 sslobj = ctx.wrap_bio(incoming, outgoing, False, 'svn.python.org') 1724 sslobj = ctx.wrap_bio(incoming, outgoing, False, 'svn.python.org')
1701 self.assertIs(sslobj._sslobj.owner, sslobj) 1725 self.assertIs(sslobj._sslobj.owner, sslobj)
1702 self.assertIsNone(sslobj.cipher()) 1726 self.assertIsNone(sslobj.cipher())
1727 self.assertIsNone(sslobj.shared_ciphers())
1703 self.assertRaises(ValueError, sslobj.getpeercert) 1728 self.assertRaises(ValueError, sslobj.getpeercert)
1704 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: 1729 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1705 self.assertIsNone(sslobj.get_channel_binding('tls-unique')) 1730 self.assertIsNone(sslobj.get_channel_binding('tls-unique'))
1706 self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) 1731 self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
1707 self.assertTrue(sslobj.cipher()) 1732 self.assertTrue(sslobj.cipher())
1733 self.assertIsNone(sslobj.shared_ciphers())
1708 self.assertTrue(sslobj.getpeercert()) 1734 self.assertTrue(sslobj.getpeercert())
1709 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: 1735 if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1710 self.assertTrue(sslobj.get_channel_binding('tls-unique')) 1736 self.assertTrue(sslobj.get_channel_binding('tls-unique'))
1711 self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) 1737 self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap)
1712 self.assertRaises(ssl.SSLError, sslobj.write, b'foo') 1738 self.assertRaises(ssl.SSLError, sslobj.write, b'foo')
1713 sock.close() 1739 sock.close()
1714 1740
1715 def test_read_write_data(self): 1741 def test_read_write_data(self):
1716 with support.transient_internet("svn.python.org"): 1742 with support.transient_internet("svn.python.org"):
1717 sock = socket.socket(socket.AF_INET) 1743 sock = socket.socket(socket.AF_INET)
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
1754 self.addr = addr 1780 self.addr = addr
1755 self.sock.setblocking(1) 1781 self.sock.setblocking(1)
1756 self.sslconn = None 1782 self.sslconn = None
1757 threading.Thread.__init__(self) 1783 threading.Thread.__init__(self)
1758 self.daemon = True 1784 self.daemon = True
1759 1785
1760 def wrap_conn(self): 1786 def wrap_conn(self):
1761 try: 1787 try:
1762 self.sslconn = self.server.context.wrap_socket( 1788 self.sslconn = self.server.context.wrap_socket(
1763 self.sock, server_side=True) 1789 self.sock, server_side=True)
1764 self.server.selected_protocols.append(self.sslconn.selected_ npn_protocol()) 1790 self.server.selected_npn_protocols.append(self.sslconn.selec ted_npn_protocol())
1791 self.server.selected_alpn_protocols.append(self.sslconn.sele cted_alpn_protocol())
1765 except (ssl.SSLError, ConnectionResetError) as e: 1792 except (ssl.SSLError, ConnectionResetError) as e:
1766 # We treat ConnectionResetError as though it were an 1793 # We treat ConnectionResetError as though it were an
1767 # SSLError - OpenSSL on Ubuntu abruptly closes the 1794 # SSLError - OpenSSL on Ubuntu abruptly closes the
1768 # connection when asked to use an unsupported protocol. 1795 # connection when asked to use an unsupported protocol.
1769 # 1796 #
1770 # XXX Various errors can have happened here, for example 1797 # XXX Various errors can have happened here, for example
1771 # a mismatching protocol version, an invalid certificate, 1798 # a mismatching protocol version, an invalid certificate,
1772 # or a low-level bug. This should be made more discriminatin g. 1799 # or a low-level bug. This should be made more discriminatin g.
1773 self.server.conn_errors.append(e) 1800 self.server.conn_errors.append(e)
1774 if self.server.chatty: 1801 if self.server.chatty:
1775 handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") 1802 handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n")
1776 self.running = False 1803 self.running = False
1777 self.server.stop() 1804 self.server.stop()
1778 self.close() 1805 self.close()
1779 return False 1806 return False
1780 else: 1807 else:
1808 self.server.shared_ciphers.append(self.sslconn.shared_cipher s())
1781 if self.server.context.verify_mode == ssl.CERT_REQUIRED: 1809 if self.server.context.verify_mode == ssl.CERT_REQUIRED:
1782 cert = self.sslconn.getpeercert() 1810 cert = self.sslconn.getpeercert()
1783 if support.verbose and self.server.chatty: 1811 if support.verbose and self.server.chatty:
1784 sys.stdout.write(" client cert is " + pprint.pformat (cert) + "\n") 1812 sys.stdout.write(" client cert is " + pprint.pformat (cert) + "\n")
1785 cert_binary = self.sslconn.getpeercert(True) 1813 cert_binary = self.sslconn.getpeercert(True)
1786 if support.verbose and self.server.chatty: 1814 if support.verbose and self.server.chatty:
1787 sys.stdout.write(" cert binary is " + str(len(cert_b inary)) + " bytes\n") 1815 sys.stdout.write(" cert binary is " + str(len(cert_b inary)) + " bytes\n")
1788 cipher = self.sslconn.cipher() 1816 cipher = self.sslconn.cipher()
1789 if support.verbose and self.server.chatty: 1817 if support.verbose and self.server.chatty:
1790 sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") 1818 sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n")
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
1861 handle_error("Test server failure:\n") 1889 handle_error("Test server failure:\n")
1862 self.close() 1890 self.close()
1863 self.running = False 1891 self.running = False
1864 # normally, we'd just stop here, but for the test 1892 # normally, we'd just stop here, but for the test
1865 # harness, we want to stop the server 1893 # harness, we want to stop the server
1866 self.server.stop() 1894 self.server.stop()
1867 1895
1868 def __init__(self, certificate=None, ssl_version=None, 1896 def __init__(self, certificate=None, ssl_version=None,
1869 certreqs=None, cacerts=None, 1897 certreqs=None, cacerts=None,
1870 chatty=True, connectionchatty=False, starttls_server=False, 1898 chatty=True, connectionchatty=False, starttls_server=False,
1871 npn_protocols=None, ciphers=None, context=None): 1899 npn_protocols=None, alpn_protocols=None,
1900 ciphers=None, context=None):
1872 if context: 1901 if context:
1873 self.context = context 1902 self.context = context
1874 else: 1903 else:
1875 self.context = ssl.SSLContext(ssl_version 1904 self.context = ssl.SSLContext(ssl_version
1876 if ssl_version is not None 1905 if ssl_version is not None
1877 else ssl.PROTOCOL_TLSv1) 1906 else ssl.PROTOCOL_TLSv1)
1878 self.context.verify_mode = (certreqs if certreqs is not None 1907 self.context.verify_mode = (certreqs if certreqs is not None
1879 else ssl.CERT_NONE) 1908 else ssl.CERT_NONE)
1880 if cacerts: 1909 if cacerts:
1881 self.context.load_verify_locations(cacerts) 1910 self.context.load_verify_locations(cacerts)
1882 if certificate: 1911 if certificate:
1883 self.context.load_cert_chain(certificate) 1912 self.context.load_cert_chain(certificate)
1884 if npn_protocols: 1913 if npn_protocols:
1885 self.context.set_npn_protocols(npn_protocols) 1914 self.context.set_npn_protocols(npn_protocols)
1915 if alpn_protocols:
1916 self.context.set_alpn_protocols(alpn_protocols)
1886 if ciphers: 1917 if ciphers:
1887 self.context.set_ciphers(ciphers) 1918 self.context.set_ciphers(ciphers)
1888 self.chatty = chatty 1919 self.chatty = chatty
1889 self.connectionchatty = connectionchatty 1920 self.connectionchatty = connectionchatty
1890 self.starttls_server = starttls_server 1921 self.starttls_server = starttls_server
1891 self.sock = socket.socket() 1922 self.sock = socket.socket()
1892 self.port = support.bind_port(self.sock) 1923 self.port = support.bind_port(self.sock)
1893 self.flag = None 1924 self.flag = None
1894 self.active = False 1925 self.active = False
1895 self.selected_protocols = [] 1926 self.selected_npn_protocols = []
1927 self.selected_alpn_protocols = []
1928 self.shared_ciphers = []
1896 self.conn_errors = [] 1929 self.conn_errors = []
1897 threading.Thread.__init__(self) 1930 threading.Thread.__init__(self)
1898 self.daemon = True 1931 self.daemon = True
1899 1932
1900 def __enter__(self): 1933 def __enter__(self):
1901 self.start(threading.Event()) 1934 self.start(threading.Event())
1902 self.flag.wait() 1935 self.flag.wait()
1903 return self 1936 return self
1904 1937
1905 def __exit__(self, *args): 1938 def __exit__(self, *args):
(...skipping 205 matching lines...) Expand 10 before | Expand all | Expand 10 after
2111 % (outdata[:20], len(outdata), 2144 % (outdata[:20], len(outdata),
2112 indata[:20].lower(), len(indata))) 2145 indata[:20].lower(), len(indata)))
2113 s.write(b"over\n") 2146 s.write(b"over\n")
2114 if connectionchatty: 2147 if connectionchatty:
2115 if support.verbose: 2148 if support.verbose:
2116 sys.stdout.write(" client: closing connection.\n") 2149 sys.stdout.write(" client: closing connection.\n")
2117 stats.update({ 2150 stats.update({
2118 'compression': s.compression(), 2151 'compression': s.compression(),
2119 'cipher': s.cipher(), 2152 'cipher': s.cipher(),
2120 'peercert': s.getpeercert(), 2153 'peercert': s.getpeercert(),
2154 'client_alpn_protocol': s.selected_alpn_protocol(),
2121 'client_npn_protocol': s.selected_npn_protocol(), 2155 'client_npn_protocol': s.selected_npn_protocol(),
2122 'version': s.version(), 2156 'version': s.version(),
2123 }) 2157 })
2124 s.close() 2158 s.close()
2125 stats['server_npn_protocols'] = server.selected_protocols 2159 stats['server_alpn_protocols'] = server.selected_alpn_protocols
2160 stats['server_npn_protocols'] = server.selected_npn_protocols
2161 stats['server_shared_ciphers'] = server.shared_ciphers
2126 return stats 2162 return stats
2127 2163
2128 def try_protocol_combo(server_protocol, client_protocol, expect_success, 2164 def try_protocol_combo(server_protocol, client_protocol, expect_success,
2129 certsreqs=None, server_options=0, client_options=0): 2165 certsreqs=None, server_options=0, client_options=0):
2130 """ 2166 """
2131 Try to SSL-connect using *client_protocol* to *server_protocol*. 2167 Try to SSL-connect using *client_protocol* to *server_protocol*.
2132 If *expect_success* is true, assert that the connection succeeds, 2168 If *expect_success* is true, assert that the connection succeeds,
2133 if it's false, assert that the connection fails. 2169 if it's false, assert that the connection fails.
2134 Also, if *expect_success* is a string, assert that it is the protocol 2170 Also, if *expect_success* is a string, assert that it is the protocol
2135 version actually used by the connection. 2171 version actually used by the connection.
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
2242 def test_crl_check(self): 2278 def test_crl_check(self):
2243 if support.verbose: 2279 if support.verbose:
2244 sys.stdout.write("\n") 2280 sys.stdout.write("\n")
2245 2281
2246 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 2282 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2247 server_context.load_cert_chain(SIGNED_CERTFILE) 2283 server_context.load_cert_chain(SIGNED_CERTFILE)
2248 2284
2249 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 2285 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2250 context.verify_mode = ssl.CERT_REQUIRED 2286 context.verify_mode = ssl.CERT_REQUIRED
2251 context.load_verify_locations(SIGNING_CA) 2287 context.load_verify_locations(SIGNING_CA)
2252 self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT) 2288 tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
2289 self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf)
2253 2290
2254 # VERIFY_DEFAULT should pass 2291 # VERIFY_DEFAULT should pass
2255 server = ThreadedEchoServer(context=server_context, chatty=True) 2292 server = ThreadedEchoServer(context=server_context, chatty=True)
2256 with server: 2293 with server:
2257 with context.wrap_socket(socket.socket()) as s: 2294 with context.wrap_socket(socket.socket()) as s:
2258 s.connect((HOST, server.port)) 2295 s.connect((HOST, server.port))
2259 cert = s.getpeercert() 2296 cert = s.getpeercert()
2260 self.assertTrue(cert, "Can't get peer certificate.") 2297 self.assertTrue(cert, "Can't get peer certificate.")
2261 2298
2262 # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails 2299 # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
2379 @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'), 2416 @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'),
2380 "OpenSSL is compiled without SSLv2 support") 2417 "OpenSSL is compiled without SSLv2 support")
2381 def test_protocol_sslv2(self): 2418 def test_protocol_sslv2(self):
2382 """Connecting to an SSLv2 server with various client options""" 2419 """Connecting to an SSLv2 server with various client options"""
2383 if support.verbose: 2420 if support.verbose:
2384 sys.stdout.write("\n") 2421 sys.stdout.write("\n")
2385 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) 2422 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True)
2386 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl .CERT_OPTIONAL) 2423 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl .CERT_OPTIONAL)
2387 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl .CERT_REQUIRED) 2424 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl .CERT_REQUIRED)
2388 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False) 2425 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False)
2389 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) 2426 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2427 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False )
2390 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) 2428 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False)
2391 # SSLv23 client with specific SSL options 2429 # SSLv23 client with specific SSL options
2392 if no_sslv2_implies_sslv3_hello(): 2430 if no_sslv2_implies_sslv3_hello():
2393 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs 2431 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs
2394 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, Fals e, 2432 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, Fals e,
2395 client_options=ssl.OP_NO_SSLv2) 2433 client_options=ssl.OP_NO_SSLv2)
2396 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, 2434 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False,
2397 client_options=ssl.OP_NO_SSLv3) 2435 client_options=ssl.OP_NO_SSLv3)
2398 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, 2436 try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False,
2399 client_options=ssl.OP_NO_TLSv1) 2437 client_options=ssl.OP_NO_TLSv1)
2400 2438
2401 @skip_if_broken_ubuntu_ssl 2439 @skip_if_broken_ubuntu_ssl
2402 def test_protocol_sslv23(self): 2440 def test_protocol_sslv23(self):
2403 """Connecting to an SSLv23 server with various client options""" 2441 """Connecting to an SSLv23 server with various client options"""
2404 if support.verbose: 2442 if support.verbose:
2405 sys.stdout.write("\n") 2443 sys.stdout.write("\n")
2406 if hasattr(ssl, 'PROTOCOL_SSLv2'): 2444 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2407 try: 2445 try:
2408 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) 2446 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True)
2409 except OSError as x: 2447 except OSError as x:
2410 # this fails on some older versions of OpenSSL (0.9.7l, for instance) 2448 # this fails on some older versions of OpenSSL (0.9.7l, for instance)
2411 if support.verbose: 2449 if support.verbose:
2412 sys.stdout.write( 2450 sys.stdout.write(
2413 " SSL2 client to SSL23 server test unexpectedly fail ed:\n %s\n" 2451 " SSL2 client to SSL23 server test unexpectedly fail ed:\n %s\n"
2414 % str(x)) 2452 % str(x))
2415 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSLv3') 2453 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2454 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSL v3')
2416 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) 2455 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True)
2417 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1') 2456 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1')
2418 2457
2419 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL) 2458 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2459 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSL v3', ssl.CERT_OPTIONAL)
2420 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, s sl.CERT_OPTIONAL) 2460 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, s sl.CERT_OPTIONAL)
2421 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) 2461 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)
2422 2462
2423 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED) 2463 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2464 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, 'SSL v3', ssl.CERT_REQUIRED)
2424 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, s sl.CERT_REQUIRED) 2465 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, s sl.CERT_REQUIRED)
2425 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) 2466 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)
2426 2467
2427 # Server with specific SSL options 2468 # Server with specific SSL options
2428 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, 2469 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2470 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, Fals e,
2429 server_options=ssl.OP_NO_SSLv3) 2471 server_options=ssl.OP_NO_SSLv3)
2430 # Will choose TLSv1 2472 # Will choose TLSv1
2431 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, 2473 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True,
2432 server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) 2474 server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
2433 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, 2475 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False,
2434 server_options=ssl.OP_NO_TLSv1) 2476 server_options=ssl.OP_NO_TLSv1)
2435 2477
2436 2478
2437 @skip_if_broken_ubuntu_ssl 2479 @skip_if_broken_ubuntu_ssl
2480 @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv3'),
2481 "OpenSSL is compiled without SSLv3 support")
2438 def test_protocol_sslv3(self): 2482 def test_protocol_sslv3(self):
2439 """Connecting to an SSLv3 server with various client options""" 2483 """Connecting to an SSLv3 server with various client options"""
2440 if support.verbose: 2484 if support.verbose:
2441 sys.stdout.write("\n") 2485 sys.stdout.write("\n")
2442 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3') 2486 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3')
2443 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL) 2487 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL)
2444 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED) 2488 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED)
2445 if hasattr(ssl, 'PROTOCOL_SSLv2'): 2489 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2446 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False ) 2490 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False )
2447 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False, 2491 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False,
2448 client_options=ssl.OP_NO_SSLv3) 2492 client_options=ssl.OP_NO_SSLv3)
2449 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) 2493 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
2450 if no_sslv2_implies_sslv3_hello(): 2494 if no_sslv2_implies_sslv3_hello():
2451 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs 2495 # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs
2452 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, 'SSL v3', 2496 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, 'SSL v3',
2453 client_options=ssl.OP_NO_SSLv2) 2497 client_options=ssl.OP_NO_SSLv2)
2454 2498
2455 @skip_if_broken_ubuntu_ssl 2499 @skip_if_broken_ubuntu_ssl
2456 def test_protocol_tlsv1(self): 2500 def test_protocol_tlsv1(self):
2457 """Connecting to a TLSv1 server with various client options""" 2501 """Connecting to a TLSv1 server with various client options"""
2458 if support.verbose: 2502 if support.verbose:
2459 sys.stdout.write("\n") 2503 sys.stdout.write("\n")
2460 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1') 2504 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1')
2461 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) 2505 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL)
2462 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) 2506 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED)
2463 if hasattr(ssl, 'PROTOCOL_SSLv2'): 2507 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2464 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False ) 2508 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False )
2465 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) 2509 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2510 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False )
2466 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False, 2511 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False,
2467 client_options=ssl.OP_NO_TLSv1) 2512 client_options=ssl.OP_NO_TLSv1)
2468 2513
2469 @skip_if_broken_ubuntu_ssl 2514 @skip_if_broken_ubuntu_ssl
2470 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_1"), 2515 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_1"),
2471 "TLS version 1.1 not supported.") 2516 "TLS version 1.1 not supported.")
2472 def test_protocol_tlsv1_1(self): 2517 def test_protocol_tlsv1_1(self):
2473 """Connecting to a TLSv1.1 server with various client options. 2518 """Connecting to a TLSv1.1 server with various client options.
2474 Testing against older TLS versions.""" 2519 Testing against older TLS versions."""
2475 if support.verbose: 2520 if support.verbose:
2476 sys.stdout.write("\n") 2521 sys.stdout.write("\n")
2477 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv 1.1') 2522 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv 1.1')
2478 if hasattr(ssl, 'PROTOCOL_SSLv2'): 2523 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2479 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, Fal se) 2524 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, Fal se)
2480 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False) 2525 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2526 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, Fal se)
2481 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv23, False, 2527 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv23, False,
2482 client_options=ssl.OP_NO_TLSv1_1) 2528 client_options=ssl.OP_NO_TLSv1_1)
2483 2529
2484 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_1, 'TLSv1 .1') 2530 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_1, 'TLSv1 .1')
2485 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False) 2531 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False)
2486 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False) 2532 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False)
2487 2533
2488 2534
2489 @skip_if_broken_ubuntu_ssl 2535 @skip_if_broken_ubuntu_ssl
2490 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_2"), 2536 @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_2"),
2491 "TLS version 1.2 not supported.") 2537 "TLS version 1.2 not supported.")
2492 def test_protocol_tlsv1_2(self): 2538 def test_protocol_tlsv1_2(self):
2493 """Connecting to a TLSv1.2 server with various client options. 2539 """Connecting to a TLSv1.2 server with various client options.
2494 Testing against older TLS versions.""" 2540 Testing against older TLS versions."""
2495 if support.verbose: 2541 if support.verbose:
2496 sys.stdout.write("\n") 2542 sys.stdout.write("\n")
2497 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv 1.2', 2543 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv 1.2',
2498 server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2, 2544 server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,
2499 client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,) 2545 client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,)
2500 if hasattr(ssl, 'PROTOCOL_SSLv2'): 2546 if hasattr(ssl, 'PROTOCOL_SSLv2'):
2501 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, Fal se) 2547 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, Fal se)
2502 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False) 2548 if hasattr(ssl, 'PROTOCOL_SSLv3'):
2549 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, Fal se)
2503 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv23, False, 2550 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv23, False,
2504 client_options=ssl.OP_NO_TLSv1_2) 2551 client_options=ssl.OP_NO_TLSv1_2)
2505 2552
2506 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_2, 'TLSv1 .2') 2553 try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_2, 'TLSv1 .2')
2507 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False) 2554 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False)
2508 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False) 2555 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False)
2509 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False ) 2556 try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False )
2510 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False ) 2557 try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False )
2511 2558
2512 def test_starttls(self): 2559 def test_starttls(self):
(...skipping 489 matching lines...) Expand 10 before | Expand all | Expand 10 after
3002 context.load_cert_chain(CERTFILE) 3049 context.load_cert_chain(CERTFILE)
3003 context.load_dh_params(DHFILE) 3050 context.load_dh_params(DHFILE)
3004 context.set_ciphers("kEDH") 3051 context.set_ciphers("kEDH")
3005 stats = server_params_test(context, context, 3052 stats = server_params_test(context, context,
3006 chatty=True, connectionchatty=True) 3053 chatty=True, connectionchatty=True)
3007 cipher = stats["cipher"][0] 3054 cipher = stats["cipher"][0]
3008 parts = cipher.split("-") 3055 parts = cipher.split("-")
3009 if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts: 3056 if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts:
3010 self.fail("Non-DH cipher: " + cipher[0]) 3057 self.fail("Non-DH cipher: " + cipher[0])
3011 3058
3059 def test_selected_alpn_protocol(self):
3060 # selected_alpn_protocol() is None unless ALPN is used.
3061 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3062 context.load_cert_chain(CERTFILE)
3063 stats = server_params_test(context, context,
3064 chatty=True, connectionchatty=True)
3065 self.assertIs(stats['client_alpn_protocol'], None)
3066
3067 @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required")
3068 def test_selected_alpn_protocol_if_server_uses_alpn(self):
3069 # selected_alpn_protocol() is None unless ALPN is used by the client .
3070 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3071 client_context.load_verify_locations(CERTFILE)
3072 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3073 server_context.load_cert_chain(CERTFILE)
3074 server_context.set_alpn_protocols(['foo', 'bar'])
3075 stats = server_params_test(client_context, server_context,
3076 chatty=True, connectionchatty=True)
3077 self.assertIs(stats['client_alpn_protocol'], None)
3078
3079 @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test")
3080 def test_alpn_protocols(self):
3081 server_protocols = ['foo', 'bar', 'milkshake']
3082 protocol_tests = [
3083 (['foo', 'bar'], 'foo'),
3084 (['bar', 'foo'], 'foo'),
3085 (['milkshake'], 'milkshake'),
3086 (['http/3.0', 'http/4.0'], None)
3087 ]
3088 for client_protocols, expected in protocol_tests:
3089 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3090 server_context.load_cert_chain(CERTFILE)
3091 server_context.set_alpn_protocols(server_protocols)
3092 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3093 client_context.load_cert_chain(CERTFILE)
3094 client_context.set_alpn_protocols(client_protocols)
3095 stats = server_params_test(client_context, server_context,
3096 chatty=True, connectionchatty=True)
3097
3098 msg = "failed trying %s (s) and %s (c).\n" \
3099 "was expecting %s, but got %%s from the %%s" \
3100 % (str(server_protocols), str(client_protocols),
3101 str(expected))
3102 client_result = stats['client_alpn_protocol']
3103 self.assertEqual(client_result, expected, msg % (client_result, "client"))
3104 server_result = stats['server_alpn_protocols'][-1] \
3105 if len(stats['server_alpn_protocols']) else 'nothing'
3106 self.assertEqual(server_result, expected, msg % (server_result, "server"))
3107
3012 def test_selected_npn_protocol(self): 3108 def test_selected_npn_protocol(self):
3013 # selected_npn_protocol() is None unless NPN is used 3109 # selected_npn_protocol() is None unless NPN is used
3014 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 3110 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3015 context.load_cert_chain(CERTFILE) 3111 context.load_cert_chain(CERTFILE)
3016 stats = server_params_test(context, context, 3112 stats = server_params_test(context, context,
3017 chatty=True, connectionchatty=True) 3113 chatty=True, connectionchatty=True)
3018 self.assertIs(stats['client_npn_protocol'], None) 3114 self.assertIs(stats['client_npn_protocol'], None)
3019 3115
3020 @unittest.skipUnless(ssl.HAS_NPN, "NPN support needed for this test") 3116 @unittest.skipUnless(ssl.HAS_NPN, "NPN support needed for this test")
3021 def test_npn_protocols(self): 3117 def test_npn_protocols(self):
(...skipping 119 matching lines...) Expand 10 before | Expand all | Expand 10 after
3141 return "foo" 3237 return "foo"
3142 server_context.set_servername_callback(cb_wrong_return_type) 3238 server_context.set_servername_callback(cb_wrong_return_type)
3143 3239
3144 with self.assertRaises(ssl.SSLError) as cm, \ 3240 with self.assertRaises(ssl.SSLError) as cm, \
3145 support.captured_stderr() as stderr: 3241 support.captured_stderr() as stderr:
3146 stats = server_params_test(client_context, server_context, 3242 stats = server_params_test(client_context, server_context,
3147 chatty=False, 3243 chatty=False,
3148 sni_name='supermessage') 3244 sni_name='supermessage')
3149 self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR') 3245 self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR')
3150 self.assertIn("TypeError", stderr.getvalue()) 3246 self.assertIn("TypeError", stderr.getvalue())
3247
3248 def test_shared_ciphers(self):
3249 server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3250 server_context.load_cert_chain(SIGNED_CERTFILE)
3251 client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3252 client_context.verify_mode = ssl.CERT_REQUIRED
3253 client_context.load_verify_locations(SIGNING_CA)
3254 client_context.set_ciphers("RC4")
3255 server_context.set_ciphers("AES:RC4")
3256 stats = server_params_test(client_context, server_context)
3257 ciphers = stats['server_shared_ciphers'][0]
3258 self.assertGreater(len(ciphers), 0)
3259 for name, tls_version, bits in ciphers:
3260 self.assertIn("RC4", name.split("-"))
3151 3261
3152 def test_read_write_after_close_raises_valuerror(self): 3262 def test_read_write_after_close_raises_valuerror(self):
3153 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 3263 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3154 context.verify_mode = ssl.CERT_REQUIRED 3264 context.verify_mode = ssl.CERT_REQUIRED
3155 context.load_verify_locations(CERTFILE) 3265 context.load_verify_locations(CERTFILE)
3156 context.load_cert_chain(CERTFILE) 3266 context.load_cert_chain(CERTFILE)
3157 server = ThreadedEchoServer(context=context, chatty=False) 3267 server = ThreadedEchoServer(context=context, chatty=False)
3158 3268
3159 with server: 3269 with server:
3160 s = context.wrap_socket(socket.socket()) 3270 s = context.wrap_socket(socket.socket())
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
3226 tests.append(ThreadedTests) 3336 tests.append(ThreadedTests)
3227 3337
3228 try: 3338 try:
3229 support.run_unittest(*tests) 3339 support.run_unittest(*tests)
3230 finally: 3340 finally:
3231 if _have_threads: 3341 if _have_threads:
3232 support.threading_cleanup(*thread_info) 3342 support.threading_cleanup(*thread_info)
3233 3343
3234 if __name__ == "__main__": 3344 if __name__ == "__main__":
3235 test_main() 3345 test_main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+