| 1 | n/a | # Test the support for SSL and sockets |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | import sys |
|---|
| 4 | n/a | import unittest |
|---|
| 5 | n/a | from test import support |
|---|
| 6 | n/a | import socket |
|---|
| 7 | n/a | import select |
|---|
| 8 | n/a | import time |
|---|
| 9 | n/a | import datetime |
|---|
| 10 | n/a | import gc |
|---|
| 11 | n/a | import os |
|---|
| 12 | n/a | import errno |
|---|
| 13 | n/a | import pprint |
|---|
| 14 | n/a | import urllib.request |
|---|
| 15 | n/a | import traceback |
|---|
| 16 | n/a | import asyncore |
|---|
| 17 | n/a | import weakref |
|---|
| 18 | n/a | import platform |
|---|
| 19 | n/a | import functools |
|---|
| 20 | n/a | |
|---|
| 21 | n/a | ssl = support.import_module("ssl") |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | try: |
|---|
| 24 | n/a | import threading |
|---|
| 25 | n/a | except ImportError: |
|---|
| 26 | n/a | _have_threads = False |
|---|
| 27 | n/a | else: |
|---|
| 28 | n/a | _have_threads = True |
|---|
| 29 | n/a | |
|---|
| 30 | n/a | PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) |
|---|
| 31 | n/a | HOST = support.HOST |
|---|
| 32 | n/a | IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL') |
|---|
| 33 | n/a | IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0) |
|---|
| 34 | n/a | |
|---|
| 35 | n/a | |
|---|
| 36 | n/a | def data_file(*name): |
|---|
| 37 | n/a | return os.path.join(os.path.dirname(__file__), *name) |
|---|
| 38 | n/a | |
|---|
| 39 | n/a | # The custom key and certificate files used in test_ssl are generated |
|---|
| 40 | n/a | # using Lib/test/make_ssl_certs.py. |
|---|
| 41 | n/a | # Other certificates are simply fetched from the Internet servers they |
|---|
| 42 | n/a | # are meant to authenticate. |
|---|
| 43 | n/a | |
|---|
| 44 | n/a | CERTFILE = data_file("keycert.pem") |
|---|
| 45 | n/a | BYTES_CERTFILE = os.fsencode(CERTFILE) |
|---|
| 46 | n/a | ONLYCERT = data_file("ssl_cert.pem") |
|---|
| 47 | n/a | ONLYKEY = data_file("ssl_key.pem") |
|---|
| 48 | n/a | BYTES_ONLYCERT = os.fsencode(ONLYCERT) |
|---|
| 49 | n/a | BYTES_ONLYKEY = os.fsencode(ONLYKEY) |
|---|
| 50 | n/a | CERTFILE_PROTECTED = data_file("keycert.passwd.pem") |
|---|
| 51 | n/a | ONLYKEY_PROTECTED = data_file("ssl_key.passwd.pem") |
|---|
| 52 | n/a | KEY_PASSWORD = "somepass" |
|---|
| 53 | n/a | CAPATH = data_file("capath") |
|---|
| 54 | n/a | BYTES_CAPATH = os.fsencode(CAPATH) |
|---|
| 55 | n/a | CAFILE_NEURONIO = data_file("capath", "4e1295a3.0") |
|---|
| 56 | n/a | CAFILE_CACERT = data_file("capath", "5ed36f99.0") |
|---|
| 57 | n/a | |
|---|
| 58 | n/a | |
|---|
| 59 | n/a | # empty CRL |
|---|
| 60 | n/a | CRLFILE = data_file("revocation.crl") |
|---|
| 61 | n/a | |
|---|
| 62 | n/a | # Two keys and certs signed by the same CA (for SNI tests) |
|---|
| 63 | n/a | SIGNED_CERTFILE = data_file("keycert3.pem") |
|---|
| 64 | n/a | SIGNED_CERTFILE2 = data_file("keycert4.pem") |
|---|
| 65 | n/a | # Same certificate as pycacert.pem, but without extra text in file |
|---|
| 66 | n/a | SIGNING_CA = data_file("capath", "ceff1710.0") |
|---|
| 67 | n/a | # cert with all kinds of subject alt names |
|---|
| 68 | n/a | ALLSANFILE = data_file("allsans.pem") |
|---|
| 69 | n/a | |
|---|
| 70 | n/a | REMOTE_HOST = "self-signed.pythontest.net" |
|---|
| 71 | n/a | |
|---|
| 72 | n/a | EMPTYCERT = data_file("nullcert.pem") |
|---|
| 73 | n/a | BADCERT = data_file("badcert.pem") |
|---|
| 74 | n/a | NONEXISTINGCERT = data_file("XXXnonexisting.pem") |
|---|
| 75 | n/a | BADKEY = data_file("badkey.pem") |
|---|
| 76 | n/a | NOKIACERT = data_file("nokia.pem") |
|---|
| 77 | n/a | NULLBYTECERT = data_file("nullbytecert.pem") |
|---|
| 78 | n/a | |
|---|
| 79 | n/a | DHFILE = data_file("dh1024.pem") |
|---|
| 80 | n/a | BYTES_DHFILE = os.fsencode(DHFILE) |
|---|
| 81 | n/a | |
|---|
| 82 | n/a | # Not defined in all versions of OpenSSL |
|---|
| 83 | n/a | OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0) |
|---|
| 84 | n/a | OP_SINGLE_DH_USE = getattr(ssl, "OP_SINGLE_DH_USE", 0) |
|---|
| 85 | n/a | OP_SINGLE_ECDH_USE = getattr(ssl, "OP_SINGLE_ECDH_USE", 0) |
|---|
| 86 | n/a | OP_CIPHER_SERVER_PREFERENCE = getattr(ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) |
|---|
| 87 | n/a | |
|---|
| 88 | n/a | |
|---|
| 89 | n/a | def handle_error(prefix): |
|---|
| 90 | n/a | exc_format = ' '.join(traceback.format_exception(*sys.exc_info())) |
|---|
| 91 | n/a | if support.verbose: |
|---|
| 92 | n/a | sys.stdout.write(prefix + exc_format) |
|---|
| 93 | n/a | |
|---|
| 94 | n/a | def can_clear_options(): |
|---|
| 95 | n/a | # 0.9.8m or higher |
|---|
| 96 | n/a | return ssl._OPENSSL_API_VERSION >= (0, 9, 8, 13, 15) |
|---|
| 97 | n/a | |
|---|
| 98 | n/a | def no_sslv2_implies_sslv3_hello(): |
|---|
| 99 | n/a | # 0.9.7h or higher |
|---|
| 100 | n/a | return ssl.OPENSSL_VERSION_INFO >= (0, 9, 7, 8, 15) |
|---|
| 101 | n/a | |
|---|
| 102 | n/a | def have_verify_flags(): |
|---|
| 103 | n/a | # 0.9.8 or higher |
|---|
| 104 | n/a | return ssl.OPENSSL_VERSION_INFO >= (0, 9, 8, 0, 15) |
|---|
| 105 | n/a | |
|---|
| 106 | n/a | def utc_offset(): #NOTE: ignore issues like #1647654 |
|---|
| 107 | n/a | # local time = utc time + utc offset |
|---|
| 108 | n/a | if time.daylight and time.localtime().tm_isdst > 0: |
|---|
| 109 | n/a | return -time.altzone # seconds |
|---|
| 110 | n/a | return -time.timezone |
|---|
| 111 | n/a | |
|---|
| 112 | n/a | def asn1time(cert_time): |
|---|
| 113 | n/a | # Some versions of OpenSSL ignore seconds, see #18207 |
|---|
| 114 | n/a | # 0.9.8.i |
|---|
| 115 | n/a | if ssl._OPENSSL_API_VERSION == (0, 9, 8, 9, 15): |
|---|
| 116 | n/a | fmt = "%b %d %H:%M:%S %Y GMT" |
|---|
| 117 | n/a | dt = datetime.datetime.strptime(cert_time, fmt) |
|---|
| 118 | n/a | dt = dt.replace(second=0) |
|---|
| 119 | n/a | cert_time = dt.strftime(fmt) |
|---|
| 120 | n/a | # %d adds leading zero but ASN1_TIME_print() uses leading space |
|---|
| 121 | n/a | if cert_time[4] == "0": |
|---|
| 122 | n/a | cert_time = cert_time[:4] + " " + cert_time[5:] |
|---|
| 123 | n/a | |
|---|
| 124 | n/a | return cert_time |
|---|
| 125 | n/a | |
|---|
| 126 | n/a | # Issue #9415: Ubuntu hijacks their OpenSSL and forcefully disables SSLv2 |
|---|
| 127 | n/a | def skip_if_broken_ubuntu_ssl(func): |
|---|
| 128 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 129 | n/a | @functools.wraps(func) |
|---|
| 130 | n/a | def f(*args, **kwargs): |
|---|
| 131 | n/a | try: |
|---|
| 132 | n/a | ssl.SSLContext(ssl.PROTOCOL_SSLv2) |
|---|
| 133 | n/a | except ssl.SSLError: |
|---|
| 134 | n/a | if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and |
|---|
| 135 | n/a | platform.linux_distribution() == ('debian', 'squeeze/sid', '')): |
|---|
| 136 | n/a | raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour") |
|---|
| 137 | n/a | return func(*args, **kwargs) |
|---|
| 138 | n/a | return f |
|---|
| 139 | n/a | else: |
|---|
| 140 | n/a | return func |
|---|
| 141 | n/a | |
|---|
| 142 | n/a | needs_sni = unittest.skipUnless(ssl.HAS_SNI, "SNI support needed for this test") |
|---|
| 143 | n/a | |
|---|
| 144 | n/a | |
|---|
| 145 | n/a | def test_wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS, *, |
|---|
| 146 | n/a | cert_reqs=ssl.CERT_NONE, ca_certs=None, |
|---|
| 147 | n/a | ciphers=None, certfile=None, keyfile=None, |
|---|
| 148 | n/a | **kwargs): |
|---|
| 149 | n/a | context = ssl.SSLContext(ssl_version) |
|---|
| 150 | n/a | if cert_reqs is not None: |
|---|
| 151 | n/a | context.verify_mode = cert_reqs |
|---|
| 152 | n/a | if ca_certs is not None: |
|---|
| 153 | n/a | context.load_verify_locations(ca_certs) |
|---|
| 154 | n/a | if certfile is not None or keyfile is not None: |
|---|
| 155 | n/a | context.load_cert_chain(certfile, keyfile) |
|---|
| 156 | n/a | if ciphers is not None: |
|---|
| 157 | n/a | context.set_ciphers(ciphers) |
|---|
| 158 | n/a | return context.wrap_socket(sock, **kwargs) |
|---|
| 159 | n/a | |
|---|
| 160 | n/a | class BasicSocketTests(unittest.TestCase): |
|---|
| 161 | n/a | |
|---|
| 162 | n/a | def test_constants(self): |
|---|
| 163 | n/a | ssl.CERT_NONE |
|---|
| 164 | n/a | ssl.CERT_OPTIONAL |
|---|
| 165 | n/a | ssl.CERT_REQUIRED |
|---|
| 166 | n/a | ssl.OP_CIPHER_SERVER_PREFERENCE |
|---|
| 167 | n/a | ssl.OP_SINGLE_DH_USE |
|---|
| 168 | n/a | if ssl.HAS_ECDH: |
|---|
| 169 | n/a | ssl.OP_SINGLE_ECDH_USE |
|---|
| 170 | n/a | if ssl.OPENSSL_VERSION_INFO >= (1, 0): |
|---|
| 171 | n/a | ssl.OP_NO_COMPRESSION |
|---|
| 172 | n/a | self.assertIn(ssl.HAS_SNI, {True, False}) |
|---|
| 173 | n/a | self.assertIn(ssl.HAS_ECDH, {True, False}) |
|---|
| 174 | n/a | |
|---|
| 175 | n/a | def test_str_for_enums(self): |
|---|
| 176 | n/a | # Make sure that the PROTOCOL_* constants have enum-like string |
|---|
| 177 | n/a | # reprs. |
|---|
| 178 | n/a | proto = ssl.PROTOCOL_TLS |
|---|
| 179 | n/a | self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS') |
|---|
| 180 | n/a | ctx = ssl.SSLContext(proto) |
|---|
| 181 | n/a | self.assertIs(ctx.protocol, proto) |
|---|
| 182 | n/a | |
|---|
| 183 | n/a | def test_random(self): |
|---|
| 184 | n/a | v = ssl.RAND_status() |
|---|
| 185 | n/a | if support.verbose: |
|---|
| 186 | n/a | sys.stdout.write("\n RAND_status is %d (%s)\n" |
|---|
| 187 | n/a | % (v, (v and "sufficient randomness") or |
|---|
| 188 | n/a | "insufficient randomness")) |
|---|
| 189 | n/a | |
|---|
| 190 | n/a | data, is_cryptographic = ssl.RAND_pseudo_bytes(16) |
|---|
| 191 | n/a | self.assertEqual(len(data), 16) |
|---|
| 192 | n/a | self.assertEqual(is_cryptographic, v == 1) |
|---|
| 193 | n/a | if v: |
|---|
| 194 | n/a | data = ssl.RAND_bytes(16) |
|---|
| 195 | n/a | self.assertEqual(len(data), 16) |
|---|
| 196 | n/a | else: |
|---|
| 197 | n/a | self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16) |
|---|
| 198 | n/a | |
|---|
| 199 | n/a | # negative num is invalid |
|---|
| 200 | n/a | self.assertRaises(ValueError, ssl.RAND_bytes, -5) |
|---|
| 201 | n/a | self.assertRaises(ValueError, ssl.RAND_pseudo_bytes, -5) |
|---|
| 202 | n/a | |
|---|
| 203 | n/a | if hasattr(ssl, 'RAND_egd'): |
|---|
| 204 | n/a | self.assertRaises(TypeError, ssl.RAND_egd, 1) |
|---|
| 205 | n/a | self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1) |
|---|
| 206 | n/a | ssl.RAND_add("this is a random string", 75.0) |
|---|
| 207 | n/a | ssl.RAND_add(b"this is a random bytes object", 75.0) |
|---|
| 208 | n/a | ssl.RAND_add(bytearray(b"this is a random bytearray object"), 75.0) |
|---|
| 209 | n/a | |
|---|
| 210 | n/a | @unittest.skipUnless(os.name == 'posix', 'requires posix') |
|---|
| 211 | n/a | def test_random_fork(self): |
|---|
| 212 | n/a | status = ssl.RAND_status() |
|---|
| 213 | n/a | if not status: |
|---|
| 214 | n/a | self.fail("OpenSSL's PRNG has insufficient randomness") |
|---|
| 215 | n/a | |
|---|
| 216 | n/a | rfd, wfd = os.pipe() |
|---|
| 217 | n/a | pid = os.fork() |
|---|
| 218 | n/a | if pid == 0: |
|---|
| 219 | n/a | try: |
|---|
| 220 | n/a | os.close(rfd) |
|---|
| 221 | n/a | child_random = ssl.RAND_pseudo_bytes(16)[0] |
|---|
| 222 | n/a | self.assertEqual(len(child_random), 16) |
|---|
| 223 | n/a | os.write(wfd, child_random) |
|---|
| 224 | n/a | os.close(wfd) |
|---|
| 225 | n/a | except BaseException: |
|---|
| 226 | n/a | os._exit(1) |
|---|
| 227 | n/a | else: |
|---|
| 228 | n/a | os._exit(0) |
|---|
| 229 | n/a | else: |
|---|
| 230 | n/a | os.close(wfd) |
|---|
| 231 | n/a | self.addCleanup(os.close, rfd) |
|---|
| 232 | n/a | _, status = os.waitpid(pid, 0) |
|---|
| 233 | n/a | self.assertEqual(status, 0) |
|---|
| 234 | n/a | |
|---|
| 235 | n/a | child_random = os.read(rfd, 16) |
|---|
| 236 | n/a | self.assertEqual(len(child_random), 16) |
|---|
| 237 | n/a | parent_random = ssl.RAND_pseudo_bytes(16)[0] |
|---|
| 238 | n/a | self.assertEqual(len(parent_random), 16) |
|---|
| 239 | n/a | |
|---|
| 240 | n/a | self.assertNotEqual(child_random, parent_random) |
|---|
| 241 | n/a | |
|---|
| 242 | n/a | def test_parse_cert(self): |
|---|
| 243 | n/a | # note that this uses an 'unofficial' function in _ssl.c, |
|---|
| 244 | n/a | # provided solely for this test, to exercise the certificate |
|---|
| 245 | n/a | # parsing code |
|---|
| 246 | n/a | p = ssl._ssl._test_decode_cert(CERTFILE) |
|---|
| 247 | n/a | if support.verbose: |
|---|
| 248 | n/a | sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
|---|
| 249 | n/a | self.assertEqual(p['issuer'], |
|---|
| 250 | n/a | ((('countryName', 'XY'),), |
|---|
| 251 | n/a | (('localityName', 'Castle Anthrax'),), |
|---|
| 252 | n/a | (('organizationName', 'Python Software Foundation'),), |
|---|
| 253 | n/a | (('commonName', 'localhost'),)) |
|---|
| 254 | n/a | ) |
|---|
| 255 | n/a | # Note the next three asserts will fail if the keys are regenerated |
|---|
| 256 | n/a | self.assertEqual(p['notAfter'], asn1time('Oct 5 23:01:56 2020 GMT')) |
|---|
| 257 | n/a | self.assertEqual(p['notBefore'], asn1time('Oct 8 23:01:56 2010 GMT')) |
|---|
| 258 | n/a | self.assertEqual(p['serialNumber'], 'D7C7381919AFC24E') |
|---|
| 259 | n/a | self.assertEqual(p['subject'], |
|---|
| 260 | n/a | ((('countryName', 'XY'),), |
|---|
| 261 | n/a | (('localityName', 'Castle Anthrax'),), |
|---|
| 262 | n/a | (('organizationName', 'Python Software Foundation'),), |
|---|
| 263 | n/a | (('commonName', 'localhost'),)) |
|---|
| 264 | n/a | ) |
|---|
| 265 | n/a | self.assertEqual(p['subjectAltName'], (('DNS', 'localhost'),)) |
|---|
| 266 | n/a | # Issue #13034: the subjectAltName in some certificates |
|---|
| 267 | n/a | # (notably projects.developer.nokia.com:443) wasn't parsed |
|---|
| 268 | n/a | p = ssl._ssl._test_decode_cert(NOKIACERT) |
|---|
| 269 | n/a | if support.verbose: |
|---|
| 270 | n/a | sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
|---|
| 271 | n/a | self.assertEqual(p['subjectAltName'], |
|---|
| 272 | n/a | (('DNS', 'projects.developer.nokia.com'), |
|---|
| 273 | n/a | ('DNS', 'projects.forum.nokia.com')) |
|---|
| 274 | n/a | ) |
|---|
| 275 | n/a | # extra OCSP and AIA fields |
|---|
| 276 | n/a | self.assertEqual(p['OCSP'], ('http://ocsp.verisign.com',)) |
|---|
| 277 | n/a | self.assertEqual(p['caIssuers'], |
|---|
| 278 | n/a | ('http://SVRIntl-G3-aia.verisign.com/SVRIntlG3.cer',)) |
|---|
| 279 | n/a | self.assertEqual(p['crlDistributionPoints'], |
|---|
| 280 | n/a | ('http://SVRIntl-G3-crl.verisign.com/SVRIntlG3.crl',)) |
|---|
| 281 | n/a | |
|---|
| 282 | n/a | def test_parse_cert_CVE_2013_4238(self): |
|---|
| 283 | n/a | p = ssl._ssl._test_decode_cert(NULLBYTECERT) |
|---|
| 284 | n/a | if support.verbose: |
|---|
| 285 | n/a | sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
|---|
| 286 | n/a | subject = ((('countryName', 'US'),), |
|---|
| 287 | n/a | (('stateOrProvinceName', 'Oregon'),), |
|---|
| 288 | n/a | (('localityName', 'Beaverton'),), |
|---|
| 289 | n/a | (('organizationName', 'Python Software Foundation'),), |
|---|
| 290 | n/a | (('organizationalUnitName', 'Python Core Development'),), |
|---|
| 291 | n/a | (('commonName', 'null.python.org\x00example.org'),), |
|---|
| 292 | n/a | (('emailAddress', 'python-dev@python.org'),)) |
|---|
| 293 | n/a | self.assertEqual(p['subject'], subject) |
|---|
| 294 | n/a | self.assertEqual(p['issuer'], subject) |
|---|
| 295 | n/a | if ssl._OPENSSL_API_VERSION >= (0, 9, 8): |
|---|
| 296 | n/a | san = (('DNS', 'altnull.python.org\x00example.com'), |
|---|
| 297 | n/a | ('email', 'null@python.org\x00user@example.org'), |
|---|
| 298 | n/a | ('URI', 'http://null.python.org\x00http://example.org'), |
|---|
| 299 | n/a | ('IP Address', '192.0.2.1'), |
|---|
| 300 | n/a | ('IP Address', '2001:DB8:0:0:0:0:0:1\n')) |
|---|
| 301 | n/a | else: |
|---|
| 302 | n/a | # OpenSSL 0.9.7 doesn't support IPv6 addresses in subjectAltName |
|---|
| 303 | n/a | san = (('DNS', 'altnull.python.org\x00example.com'), |
|---|
| 304 | n/a | ('email', 'null@python.org\x00user@example.org'), |
|---|
| 305 | n/a | ('URI', 'http://null.python.org\x00http://example.org'), |
|---|
| 306 | n/a | ('IP Address', '192.0.2.1'), |
|---|
| 307 | n/a | ('IP Address', '<invalid>')) |
|---|
| 308 | n/a | |
|---|
| 309 | n/a | self.assertEqual(p['subjectAltName'], san) |
|---|
| 310 | n/a | |
|---|
| 311 | n/a | def test_parse_all_sans(self): |
|---|
| 312 | n/a | p = ssl._ssl._test_decode_cert(ALLSANFILE) |
|---|
| 313 | n/a | self.assertEqual(p['subjectAltName'], |
|---|
| 314 | n/a | ( |
|---|
| 315 | n/a | ('DNS', 'allsans'), |
|---|
| 316 | n/a | ('othername', '<unsupported>'), |
|---|
| 317 | n/a | ('othername', '<unsupported>'), |
|---|
| 318 | n/a | ('email', 'user@example.org'), |
|---|
| 319 | n/a | ('DNS', 'www.example.org'), |
|---|
| 320 | n/a | ('DirName', |
|---|
| 321 | n/a | ((('countryName', 'XY'),), |
|---|
| 322 | n/a | (('localityName', 'Castle Anthrax'),), |
|---|
| 323 | n/a | (('organizationName', 'Python Software Foundation'),), |
|---|
| 324 | n/a | (('commonName', 'dirname example'),))), |
|---|
| 325 | n/a | ('URI', 'https://www.python.org/'), |
|---|
| 326 | n/a | ('IP Address', '127.0.0.1'), |
|---|
| 327 | n/a | ('IP Address', '0:0:0:0:0:0:0:1\n'), |
|---|
| 328 | n/a | ('Registered ID', '1.2.3.4.5') |
|---|
| 329 | n/a | ) |
|---|
| 330 | n/a | ) |
|---|
| 331 | n/a | |
|---|
| 332 | n/a | def test_DER_to_PEM(self): |
|---|
| 333 | n/a | with open(CAFILE_CACERT, 'r') as f: |
|---|
| 334 | n/a | pem = f.read() |
|---|
| 335 | n/a | d1 = ssl.PEM_cert_to_DER_cert(pem) |
|---|
| 336 | n/a | p2 = ssl.DER_cert_to_PEM_cert(d1) |
|---|
| 337 | n/a | d2 = ssl.PEM_cert_to_DER_cert(p2) |
|---|
| 338 | n/a | self.assertEqual(d1, d2) |
|---|
| 339 | n/a | if not p2.startswith(ssl.PEM_HEADER + '\n'): |
|---|
| 340 | n/a | self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2) |
|---|
| 341 | n/a | if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'): |
|---|
| 342 | n/a | self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2) |
|---|
| 343 | n/a | |
|---|
| 344 | n/a | def test_openssl_version(self): |
|---|
| 345 | n/a | n = ssl.OPENSSL_VERSION_NUMBER |
|---|
| 346 | n/a | t = ssl.OPENSSL_VERSION_INFO |
|---|
| 347 | n/a | s = ssl.OPENSSL_VERSION |
|---|
| 348 | n/a | self.assertIsInstance(n, int) |
|---|
| 349 | n/a | self.assertIsInstance(t, tuple) |
|---|
| 350 | n/a | self.assertIsInstance(s, str) |
|---|
| 351 | n/a | # Some sanity checks follow |
|---|
| 352 | n/a | # >= 0.9 |
|---|
| 353 | n/a | self.assertGreaterEqual(n, 0x900000) |
|---|
| 354 | n/a | # < 3.0 |
|---|
| 355 | n/a | self.assertLess(n, 0x30000000) |
|---|
| 356 | n/a | major, minor, fix, patch, status = t |
|---|
| 357 | n/a | self.assertGreaterEqual(major, 0) |
|---|
| 358 | n/a | self.assertLess(major, 3) |
|---|
| 359 | n/a | self.assertGreaterEqual(minor, 0) |
|---|
| 360 | n/a | self.assertLess(minor, 256) |
|---|
| 361 | n/a | self.assertGreaterEqual(fix, 0) |
|---|
| 362 | n/a | self.assertLess(fix, 256) |
|---|
| 363 | n/a | self.assertGreaterEqual(patch, 0) |
|---|
| 364 | n/a | self.assertLessEqual(patch, 63) |
|---|
| 365 | n/a | self.assertGreaterEqual(status, 0) |
|---|
| 366 | n/a | self.assertLessEqual(status, 15) |
|---|
| 367 | n/a | # Version string as returned by {Open,Libre}SSL, the format might change |
|---|
| 368 | n/a | if IS_LIBRESSL: |
|---|
| 369 | n/a | self.assertTrue(s.startswith("LibreSSL {:d}".format(major)), |
|---|
| 370 | n/a | (s, t, hex(n))) |
|---|
| 371 | n/a | else: |
|---|
| 372 | n/a | self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)), |
|---|
| 373 | n/a | (s, t, hex(n))) |
|---|
| 374 | n/a | |
|---|
| 375 | n/a | @support.cpython_only |
|---|
| 376 | n/a | def test_refcycle(self): |
|---|
| 377 | n/a | # Issue #7943: an SSL object doesn't create reference cycles with |
|---|
| 378 | n/a | # itself. |
|---|
| 379 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 380 | n/a | ss = test_wrap_socket(s) |
|---|
| 381 | n/a | wr = weakref.ref(ss) |
|---|
| 382 | n/a | with support.check_warnings(("", ResourceWarning)): |
|---|
| 383 | n/a | del ss |
|---|
| 384 | n/a | self.assertEqual(wr(), None) |
|---|
| 385 | n/a | |
|---|
| 386 | n/a | def test_wrapped_unconnected(self): |
|---|
| 387 | n/a | # Methods on an unconnected SSLSocket propagate the original |
|---|
| 388 | n/a | # OSError raise by the underlying socket object. |
|---|
| 389 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 390 | n/a | with test_wrap_socket(s) as ss: |
|---|
| 391 | n/a | self.assertRaises(OSError, ss.recv, 1) |
|---|
| 392 | n/a | self.assertRaises(OSError, ss.recv_into, bytearray(b'x')) |
|---|
| 393 | n/a | self.assertRaises(OSError, ss.recvfrom, 1) |
|---|
| 394 | n/a | self.assertRaises(OSError, ss.recvfrom_into, bytearray(b'x'), 1) |
|---|
| 395 | n/a | self.assertRaises(OSError, ss.send, b'x') |
|---|
| 396 | n/a | self.assertRaises(OSError, ss.sendto, b'x', ('0.0.0.0', 0)) |
|---|
| 397 | n/a | |
|---|
| 398 | n/a | def test_timeout(self): |
|---|
| 399 | n/a | # Issue #8524: when creating an SSL socket, the timeout of the |
|---|
| 400 | n/a | # original socket should be retained. |
|---|
| 401 | n/a | for timeout in (None, 0.0, 5.0): |
|---|
| 402 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 403 | n/a | s.settimeout(timeout) |
|---|
| 404 | n/a | with test_wrap_socket(s) as ss: |
|---|
| 405 | n/a | self.assertEqual(timeout, ss.gettimeout()) |
|---|
| 406 | n/a | |
|---|
| 407 | n/a | def test_errors_sslwrap(self): |
|---|
| 408 | n/a | sock = socket.socket() |
|---|
| 409 | n/a | self.assertRaisesRegex(ValueError, |
|---|
| 410 | n/a | "certfile must be specified", |
|---|
| 411 | n/a | ssl.wrap_socket, sock, keyfile=CERTFILE) |
|---|
| 412 | n/a | self.assertRaisesRegex(ValueError, |
|---|
| 413 | n/a | "certfile must be specified for server-side operations", |
|---|
| 414 | n/a | ssl.wrap_socket, sock, server_side=True) |
|---|
| 415 | n/a | self.assertRaisesRegex(ValueError, |
|---|
| 416 | n/a | "certfile must be specified for server-side operations", |
|---|
| 417 | n/a | ssl.wrap_socket, sock, server_side=True, certfile="") |
|---|
| 418 | n/a | with ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE) as s: |
|---|
| 419 | n/a | self.assertRaisesRegex(ValueError, "can't connect in server-side mode", |
|---|
| 420 | n/a | s.connect, (HOST, 8080)) |
|---|
| 421 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 422 | n/a | with socket.socket() as sock: |
|---|
| 423 | n/a | ssl.wrap_socket(sock, certfile=NONEXISTINGCERT) |
|---|
| 424 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 425 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 426 | n/a | with socket.socket() as sock: |
|---|
| 427 | n/a | ssl.wrap_socket(sock, |
|---|
| 428 | n/a | certfile=CERTFILE, keyfile=NONEXISTINGCERT) |
|---|
| 429 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 430 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 431 | n/a | with socket.socket() as sock: |
|---|
| 432 | n/a | ssl.wrap_socket(sock, |
|---|
| 433 | n/a | certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT) |
|---|
| 434 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 435 | n/a | |
|---|
| 436 | n/a | def bad_cert_test(self, certfile): |
|---|
| 437 | n/a | """Check that trying to use the given client certificate fails""" |
|---|
| 438 | n/a | certfile = os.path.join(os.path.dirname(__file__) or os.curdir, |
|---|
| 439 | n/a | certfile) |
|---|
| 440 | n/a | sock = socket.socket() |
|---|
| 441 | n/a | self.addCleanup(sock.close) |
|---|
| 442 | n/a | with self.assertRaises(ssl.SSLError): |
|---|
| 443 | n/a | test_wrap_socket(sock, |
|---|
| 444 | n/a | certfile=certfile, |
|---|
| 445 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 446 | n/a | |
|---|
| 447 | n/a | def test_empty_cert(self): |
|---|
| 448 | n/a | """Wrapping with an empty cert file""" |
|---|
| 449 | n/a | self.bad_cert_test("nullcert.pem") |
|---|
| 450 | n/a | |
|---|
| 451 | n/a | def test_malformed_cert(self): |
|---|
| 452 | n/a | """Wrapping with a badly formatted certificate (syntax error)""" |
|---|
| 453 | n/a | self.bad_cert_test("badcert.pem") |
|---|
| 454 | n/a | |
|---|
| 455 | n/a | def test_malformed_key(self): |
|---|
| 456 | n/a | """Wrapping with a badly formatted key (syntax error)""" |
|---|
| 457 | n/a | self.bad_cert_test("badkey.pem") |
|---|
| 458 | n/a | |
|---|
| 459 | n/a | def test_match_hostname(self): |
|---|
| 460 | n/a | def ok(cert, hostname): |
|---|
| 461 | n/a | ssl.match_hostname(cert, hostname) |
|---|
| 462 | n/a | def fail(cert, hostname): |
|---|
| 463 | n/a | self.assertRaises(ssl.CertificateError, |
|---|
| 464 | n/a | ssl.match_hostname, cert, hostname) |
|---|
| 465 | n/a | |
|---|
| 466 | n/a | # -- Hostname matching -- |
|---|
| 467 | n/a | |
|---|
| 468 | n/a | cert = {'subject': ((('commonName', 'example.com'),),)} |
|---|
| 469 | n/a | ok(cert, 'example.com') |
|---|
| 470 | n/a | ok(cert, 'ExAmple.cOm') |
|---|
| 471 | n/a | fail(cert, 'www.example.com') |
|---|
| 472 | n/a | fail(cert, '.example.com') |
|---|
| 473 | n/a | fail(cert, 'example.org') |
|---|
| 474 | n/a | fail(cert, 'exampleXcom') |
|---|
| 475 | n/a | |
|---|
| 476 | n/a | cert = {'subject': ((('commonName', '*.a.com'),),)} |
|---|
| 477 | n/a | ok(cert, 'foo.a.com') |
|---|
| 478 | n/a | fail(cert, 'bar.foo.a.com') |
|---|
| 479 | n/a | fail(cert, 'a.com') |
|---|
| 480 | n/a | fail(cert, 'Xa.com') |
|---|
| 481 | n/a | fail(cert, '.a.com') |
|---|
| 482 | n/a | |
|---|
| 483 | n/a | # only match one left-most wildcard |
|---|
| 484 | n/a | cert = {'subject': ((('commonName', 'f*.com'),),)} |
|---|
| 485 | n/a | ok(cert, 'foo.com') |
|---|
| 486 | n/a | ok(cert, 'f.com') |
|---|
| 487 | n/a | fail(cert, 'bar.com') |
|---|
| 488 | n/a | fail(cert, 'foo.a.com') |
|---|
| 489 | n/a | fail(cert, 'bar.foo.com') |
|---|
| 490 | n/a | |
|---|
| 491 | n/a | # NULL bytes are bad, CVE-2013-4073 |
|---|
| 492 | n/a | cert = {'subject': ((('commonName', |
|---|
| 493 | n/a | 'null.python.org\x00example.org'),),)} |
|---|
| 494 | n/a | ok(cert, 'null.python.org\x00example.org') # or raise an error? |
|---|
| 495 | n/a | fail(cert, 'example.org') |
|---|
| 496 | n/a | fail(cert, 'null.python.org') |
|---|
| 497 | n/a | |
|---|
| 498 | n/a | # error cases with wildcards |
|---|
| 499 | n/a | cert = {'subject': ((('commonName', '*.*.a.com'),),)} |
|---|
| 500 | n/a | fail(cert, 'bar.foo.a.com') |
|---|
| 501 | n/a | fail(cert, 'a.com') |
|---|
| 502 | n/a | fail(cert, 'Xa.com') |
|---|
| 503 | n/a | fail(cert, '.a.com') |
|---|
| 504 | n/a | |
|---|
| 505 | n/a | cert = {'subject': ((('commonName', 'a.*.com'),),)} |
|---|
| 506 | n/a | fail(cert, 'a.foo.com') |
|---|
| 507 | n/a | fail(cert, 'a..com') |
|---|
| 508 | n/a | fail(cert, 'a.com') |
|---|
| 509 | n/a | |
|---|
| 510 | n/a | # wildcard doesn't match IDNA prefix 'xn--' |
|---|
| 511 | n/a | idna = 'pรยผthon.python.org'.encode("idna").decode("ascii") |
|---|
| 512 | n/a | cert = {'subject': ((('commonName', idna),),)} |
|---|
| 513 | n/a | ok(cert, idna) |
|---|
| 514 | n/a | cert = {'subject': ((('commonName', 'x*.python.org'),),)} |
|---|
| 515 | n/a | fail(cert, idna) |
|---|
| 516 | n/a | cert = {'subject': ((('commonName', 'xn--p*.python.org'),),)} |
|---|
| 517 | n/a | fail(cert, idna) |
|---|
| 518 | n/a | |
|---|
| 519 | n/a | # wildcard in first fragment and IDNA A-labels in sequent fragments |
|---|
| 520 | n/a | # are supported. |
|---|
| 521 | n/a | idna = 'www*.pythรยถn.org'.encode("idna").decode("ascii") |
|---|
| 522 | n/a | cert = {'subject': ((('commonName', idna),),)} |
|---|
| 523 | n/a | ok(cert, 'www.pythรยถn.org'.encode("idna").decode("ascii")) |
|---|
| 524 | n/a | ok(cert, 'www1.pythรยถn.org'.encode("idna").decode("ascii")) |
|---|
| 525 | n/a | fail(cert, 'ftp.pythรยถn.org'.encode("idna").decode("ascii")) |
|---|
| 526 | n/a | fail(cert, 'pythรยถn.org'.encode("idna").decode("ascii")) |
|---|
| 527 | n/a | |
|---|
| 528 | n/a | # Slightly fake real-world example |
|---|
| 529 | n/a | cert = {'notAfter': 'Jun 26 21:41:46 2011 GMT', |
|---|
| 530 | n/a | 'subject': ((('commonName', 'linuxfrz.org'),),), |
|---|
| 531 | n/a | 'subjectAltName': (('DNS', 'linuxfr.org'), |
|---|
| 532 | n/a | ('DNS', 'linuxfr.com'), |
|---|
| 533 | n/a | ('othername', '<unsupported>'))} |
|---|
| 534 | n/a | ok(cert, 'linuxfr.org') |
|---|
| 535 | n/a | ok(cert, 'linuxfr.com') |
|---|
| 536 | n/a | # Not a "DNS" entry |
|---|
| 537 | n/a | fail(cert, '<unsupported>') |
|---|
| 538 | n/a | # When there is a subjectAltName, commonName isn't used |
|---|
| 539 | n/a | fail(cert, 'linuxfrz.org') |
|---|
| 540 | n/a | |
|---|
| 541 | n/a | # A pristine real-world example |
|---|
| 542 | n/a | cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', |
|---|
| 543 | n/a | 'subject': ((('countryName', 'US'),), |
|---|
| 544 | n/a | (('stateOrProvinceName', 'California'),), |
|---|
| 545 | n/a | (('localityName', 'Mountain View'),), |
|---|
| 546 | n/a | (('organizationName', 'Google Inc'),), |
|---|
| 547 | n/a | (('commonName', 'mail.google.com'),))} |
|---|
| 548 | n/a | ok(cert, 'mail.google.com') |
|---|
| 549 | n/a | fail(cert, 'gmail.com') |
|---|
| 550 | n/a | # Only commonName is considered |
|---|
| 551 | n/a | fail(cert, 'California') |
|---|
| 552 | n/a | |
|---|
| 553 | n/a | # -- IPv4 matching -- |
|---|
| 554 | n/a | cert = {'subject': ((('commonName', 'example.com'),),), |
|---|
| 555 | n/a | 'subjectAltName': (('DNS', 'example.com'), |
|---|
| 556 | n/a | ('IP Address', '10.11.12.13'), |
|---|
| 557 | n/a | ('IP Address', '14.15.16.17'))} |
|---|
| 558 | n/a | ok(cert, '10.11.12.13') |
|---|
| 559 | n/a | ok(cert, '14.15.16.17') |
|---|
| 560 | n/a | fail(cert, '14.15.16.18') |
|---|
| 561 | n/a | fail(cert, 'example.net') |
|---|
| 562 | n/a | |
|---|
| 563 | n/a | # -- IPv6 matching -- |
|---|
| 564 | n/a | cert = {'subject': ((('commonName', 'example.com'),),), |
|---|
| 565 | n/a | 'subjectAltName': (('DNS', 'example.com'), |
|---|
| 566 | n/a | ('IP Address', '2001:0:0:0:0:0:0:CAFE\n'), |
|---|
| 567 | n/a | ('IP Address', '2003:0:0:0:0:0:0:BABA\n'))} |
|---|
| 568 | n/a | ok(cert, '2001::cafe') |
|---|
| 569 | n/a | ok(cert, '2003::baba') |
|---|
| 570 | n/a | fail(cert, '2003::bebe') |
|---|
| 571 | n/a | fail(cert, 'example.net') |
|---|
| 572 | n/a | |
|---|
| 573 | n/a | # -- Miscellaneous -- |
|---|
| 574 | n/a | |
|---|
| 575 | n/a | # Neither commonName nor subjectAltName |
|---|
| 576 | n/a | cert = {'notAfter': 'Dec 18 23:59:59 2011 GMT', |
|---|
| 577 | n/a | 'subject': ((('countryName', 'US'),), |
|---|
| 578 | n/a | (('stateOrProvinceName', 'California'),), |
|---|
| 579 | n/a | (('localityName', 'Mountain View'),), |
|---|
| 580 | n/a | (('organizationName', 'Google Inc'),))} |
|---|
| 581 | n/a | fail(cert, 'mail.google.com') |
|---|
| 582 | n/a | |
|---|
| 583 | n/a | # No DNS entry in subjectAltName but a commonName |
|---|
| 584 | n/a | cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', |
|---|
| 585 | n/a | 'subject': ((('countryName', 'US'),), |
|---|
| 586 | n/a | (('stateOrProvinceName', 'California'),), |
|---|
| 587 | n/a | (('localityName', 'Mountain View'),), |
|---|
| 588 | n/a | (('commonName', 'mail.google.com'),)), |
|---|
| 589 | n/a | 'subjectAltName': (('othername', 'blabla'), )} |
|---|
| 590 | n/a | ok(cert, 'mail.google.com') |
|---|
| 591 | n/a | |
|---|
| 592 | n/a | # No DNS entry subjectAltName and no commonName |
|---|
| 593 | n/a | cert = {'notAfter': 'Dec 18 23:59:59 2099 GMT', |
|---|
| 594 | n/a | 'subject': ((('countryName', 'US'),), |
|---|
| 595 | n/a | (('stateOrProvinceName', 'California'),), |
|---|
| 596 | n/a | (('localityName', 'Mountain View'),), |
|---|
| 597 | n/a | (('organizationName', 'Google Inc'),)), |
|---|
| 598 | n/a | 'subjectAltName': (('othername', 'blabla'),)} |
|---|
| 599 | n/a | fail(cert, 'google.com') |
|---|
| 600 | n/a | |
|---|
| 601 | n/a | # Empty cert / no cert |
|---|
| 602 | n/a | self.assertRaises(ValueError, ssl.match_hostname, None, 'example.com') |
|---|
| 603 | n/a | self.assertRaises(ValueError, ssl.match_hostname, {}, 'example.com') |
|---|
| 604 | n/a | |
|---|
| 605 | n/a | # Issue #17980: avoid denials of service by refusing more than one |
|---|
| 606 | n/a | # wildcard per fragment. |
|---|
| 607 | n/a | cert = {'subject': ((('commonName', 'a*b.com'),),)} |
|---|
| 608 | n/a | ok(cert, 'axxb.com') |
|---|
| 609 | n/a | cert = {'subject': ((('commonName', 'a*b.co*'),),)} |
|---|
| 610 | n/a | fail(cert, 'axxb.com') |
|---|
| 611 | n/a | cert = {'subject': ((('commonName', 'a*b*.com'),),)} |
|---|
| 612 | n/a | with self.assertRaises(ssl.CertificateError) as cm: |
|---|
| 613 | n/a | ssl.match_hostname(cert, 'axxbxxc.com') |
|---|
| 614 | n/a | self.assertIn("too many wildcards", str(cm.exception)) |
|---|
| 615 | n/a | |
|---|
| 616 | n/a | def test_server_side(self): |
|---|
| 617 | n/a | # server_hostname doesn't work for server sockets |
|---|
| 618 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 619 | n/a | with socket.socket() as sock: |
|---|
| 620 | n/a | self.assertRaises(ValueError, ctx.wrap_socket, sock, True, |
|---|
| 621 | n/a | server_hostname="some.hostname") |
|---|
| 622 | n/a | |
|---|
| 623 | n/a | def test_unknown_channel_binding(self): |
|---|
| 624 | n/a | # should raise ValueError for unknown type |
|---|
| 625 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 626 | n/a | s.bind(('127.0.0.1', 0)) |
|---|
| 627 | n/a | s.listen() |
|---|
| 628 | n/a | c = socket.socket(socket.AF_INET) |
|---|
| 629 | n/a | c.connect(s.getsockname()) |
|---|
| 630 | n/a | with test_wrap_socket(c, do_handshake_on_connect=False) as ss: |
|---|
| 631 | n/a | with self.assertRaises(ValueError): |
|---|
| 632 | n/a | ss.get_channel_binding("unknown-type") |
|---|
| 633 | n/a | s.close() |
|---|
| 634 | n/a | |
|---|
| 635 | n/a | @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, |
|---|
| 636 | n/a | "'tls-unique' channel binding not available") |
|---|
| 637 | n/a | def test_tls_unique_channel_binding(self): |
|---|
| 638 | n/a | # unconnected should return None for known type |
|---|
| 639 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 640 | n/a | with test_wrap_socket(s) as ss: |
|---|
| 641 | n/a | self.assertIsNone(ss.get_channel_binding("tls-unique")) |
|---|
| 642 | n/a | # the same for server-side |
|---|
| 643 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 644 | n/a | with test_wrap_socket(s, server_side=True, certfile=CERTFILE) as ss: |
|---|
| 645 | n/a | self.assertIsNone(ss.get_channel_binding("tls-unique")) |
|---|
| 646 | n/a | |
|---|
| 647 | n/a | def test_dealloc_warn(self): |
|---|
| 648 | n/a | ss = test_wrap_socket(socket.socket(socket.AF_INET)) |
|---|
| 649 | n/a | r = repr(ss) |
|---|
| 650 | n/a | with self.assertWarns(ResourceWarning) as cm: |
|---|
| 651 | n/a | ss = None |
|---|
| 652 | n/a | support.gc_collect() |
|---|
| 653 | n/a | self.assertIn(r, str(cm.warning.args[0])) |
|---|
| 654 | n/a | |
|---|
| 655 | n/a | def test_get_default_verify_paths(self): |
|---|
| 656 | n/a | paths = ssl.get_default_verify_paths() |
|---|
| 657 | n/a | self.assertEqual(len(paths), 6) |
|---|
| 658 | n/a | self.assertIsInstance(paths, ssl.DefaultVerifyPaths) |
|---|
| 659 | n/a | |
|---|
| 660 | n/a | with support.EnvironmentVarGuard() as env: |
|---|
| 661 | n/a | env["SSL_CERT_DIR"] = CAPATH |
|---|
| 662 | n/a | env["SSL_CERT_FILE"] = CERTFILE |
|---|
| 663 | n/a | paths = ssl.get_default_verify_paths() |
|---|
| 664 | n/a | self.assertEqual(paths.cafile, CERTFILE) |
|---|
| 665 | n/a | self.assertEqual(paths.capath, CAPATH) |
|---|
| 666 | n/a | |
|---|
| 667 | n/a | @unittest.skipUnless(sys.platform == "win32", "Windows specific") |
|---|
| 668 | n/a | def test_enum_certificates(self): |
|---|
| 669 | n/a | self.assertTrue(ssl.enum_certificates("CA")) |
|---|
| 670 | n/a | self.assertTrue(ssl.enum_certificates("ROOT")) |
|---|
| 671 | n/a | |
|---|
| 672 | n/a | self.assertRaises(TypeError, ssl.enum_certificates) |
|---|
| 673 | n/a | self.assertRaises(WindowsError, ssl.enum_certificates, "") |
|---|
| 674 | n/a | |
|---|
| 675 | n/a | trust_oids = set() |
|---|
| 676 | n/a | for storename in ("CA", "ROOT"): |
|---|
| 677 | n/a | store = ssl.enum_certificates(storename) |
|---|
| 678 | n/a | self.assertIsInstance(store, list) |
|---|
| 679 | n/a | for element in store: |
|---|
| 680 | n/a | self.assertIsInstance(element, tuple) |
|---|
| 681 | n/a | self.assertEqual(len(element), 3) |
|---|
| 682 | n/a | cert, enc, trust = element |
|---|
| 683 | n/a | self.assertIsInstance(cert, bytes) |
|---|
| 684 | n/a | self.assertIn(enc, {"x509_asn", "pkcs_7_asn"}) |
|---|
| 685 | n/a | self.assertIsInstance(trust, (set, bool)) |
|---|
| 686 | n/a | if isinstance(trust, set): |
|---|
| 687 | n/a | trust_oids.update(trust) |
|---|
| 688 | n/a | |
|---|
| 689 | n/a | serverAuth = "1.3.6.1.5.5.7.3.1" |
|---|
| 690 | n/a | self.assertIn(serverAuth, trust_oids) |
|---|
| 691 | n/a | |
|---|
| 692 | n/a | @unittest.skipUnless(sys.platform == "win32", "Windows specific") |
|---|
| 693 | n/a | def test_enum_crls(self): |
|---|
| 694 | n/a | self.assertTrue(ssl.enum_crls("CA")) |
|---|
| 695 | n/a | self.assertRaises(TypeError, ssl.enum_crls) |
|---|
| 696 | n/a | self.assertRaises(WindowsError, ssl.enum_crls, "") |
|---|
| 697 | n/a | |
|---|
| 698 | n/a | crls = ssl.enum_crls("CA") |
|---|
| 699 | n/a | self.assertIsInstance(crls, list) |
|---|
| 700 | n/a | for element in crls: |
|---|
| 701 | n/a | self.assertIsInstance(element, tuple) |
|---|
| 702 | n/a | self.assertEqual(len(element), 2) |
|---|
| 703 | n/a | self.assertIsInstance(element[0], bytes) |
|---|
| 704 | n/a | self.assertIn(element[1], {"x509_asn", "pkcs_7_asn"}) |
|---|
| 705 | n/a | |
|---|
| 706 | n/a | |
|---|
| 707 | n/a | def test_asn1object(self): |
|---|
| 708 | n/a | expected = (129, 'serverAuth', 'TLS Web Server Authentication', |
|---|
| 709 | n/a | '1.3.6.1.5.5.7.3.1') |
|---|
| 710 | n/a | |
|---|
| 711 | n/a | val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') |
|---|
| 712 | n/a | self.assertEqual(val, expected) |
|---|
| 713 | n/a | self.assertEqual(val.nid, 129) |
|---|
| 714 | n/a | self.assertEqual(val.shortname, 'serverAuth') |
|---|
| 715 | n/a | self.assertEqual(val.longname, 'TLS Web Server Authentication') |
|---|
| 716 | n/a | self.assertEqual(val.oid, '1.3.6.1.5.5.7.3.1') |
|---|
| 717 | n/a | self.assertIsInstance(val, ssl._ASN1Object) |
|---|
| 718 | n/a | self.assertRaises(ValueError, ssl._ASN1Object, 'serverAuth') |
|---|
| 719 | n/a | |
|---|
| 720 | n/a | val = ssl._ASN1Object.fromnid(129) |
|---|
| 721 | n/a | self.assertEqual(val, expected) |
|---|
| 722 | n/a | self.assertIsInstance(val, ssl._ASN1Object) |
|---|
| 723 | n/a | self.assertRaises(ValueError, ssl._ASN1Object.fromnid, -1) |
|---|
| 724 | n/a | with self.assertRaisesRegex(ValueError, "unknown NID 100000"): |
|---|
| 725 | n/a | ssl._ASN1Object.fromnid(100000) |
|---|
| 726 | n/a | for i in range(1000): |
|---|
| 727 | n/a | try: |
|---|
| 728 | n/a | obj = ssl._ASN1Object.fromnid(i) |
|---|
| 729 | n/a | except ValueError: |
|---|
| 730 | n/a | pass |
|---|
| 731 | n/a | else: |
|---|
| 732 | n/a | self.assertIsInstance(obj.nid, int) |
|---|
| 733 | n/a | self.assertIsInstance(obj.shortname, str) |
|---|
| 734 | n/a | self.assertIsInstance(obj.longname, str) |
|---|
| 735 | n/a | self.assertIsInstance(obj.oid, (str, type(None))) |
|---|
| 736 | n/a | |
|---|
| 737 | n/a | val = ssl._ASN1Object.fromname('TLS Web Server Authentication') |
|---|
| 738 | n/a | self.assertEqual(val, expected) |
|---|
| 739 | n/a | self.assertIsInstance(val, ssl._ASN1Object) |
|---|
| 740 | n/a | self.assertEqual(ssl._ASN1Object.fromname('serverAuth'), expected) |
|---|
| 741 | n/a | self.assertEqual(ssl._ASN1Object.fromname('1.3.6.1.5.5.7.3.1'), |
|---|
| 742 | n/a | expected) |
|---|
| 743 | n/a | with self.assertRaisesRegex(ValueError, "unknown object 'serverauth'"): |
|---|
| 744 | n/a | ssl._ASN1Object.fromname('serverauth') |
|---|
| 745 | n/a | |
|---|
| 746 | n/a | def test_purpose_enum(self): |
|---|
| 747 | n/a | val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') |
|---|
| 748 | n/a | self.assertIsInstance(ssl.Purpose.SERVER_AUTH, ssl._ASN1Object) |
|---|
| 749 | n/a | self.assertEqual(ssl.Purpose.SERVER_AUTH, val) |
|---|
| 750 | n/a | self.assertEqual(ssl.Purpose.SERVER_AUTH.nid, 129) |
|---|
| 751 | n/a | self.assertEqual(ssl.Purpose.SERVER_AUTH.shortname, 'serverAuth') |
|---|
| 752 | n/a | self.assertEqual(ssl.Purpose.SERVER_AUTH.oid, |
|---|
| 753 | n/a | '1.3.6.1.5.5.7.3.1') |
|---|
| 754 | n/a | |
|---|
| 755 | n/a | val = ssl._ASN1Object('1.3.6.1.5.5.7.3.2') |
|---|
| 756 | n/a | self.assertIsInstance(ssl.Purpose.CLIENT_AUTH, ssl._ASN1Object) |
|---|
| 757 | n/a | self.assertEqual(ssl.Purpose.CLIENT_AUTH, val) |
|---|
| 758 | n/a | self.assertEqual(ssl.Purpose.CLIENT_AUTH.nid, 130) |
|---|
| 759 | n/a | self.assertEqual(ssl.Purpose.CLIENT_AUTH.shortname, 'clientAuth') |
|---|
| 760 | n/a | self.assertEqual(ssl.Purpose.CLIENT_AUTH.oid, |
|---|
| 761 | n/a | '1.3.6.1.5.5.7.3.2') |
|---|
| 762 | n/a | |
|---|
| 763 | n/a | def test_unsupported_dtls(self): |
|---|
| 764 | n/a | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
|---|
| 765 | n/a | self.addCleanup(s.close) |
|---|
| 766 | n/a | with self.assertRaises(NotImplementedError) as cx: |
|---|
| 767 | n/a | test_wrap_socket(s, cert_reqs=ssl.CERT_NONE) |
|---|
| 768 | n/a | self.assertEqual(str(cx.exception), "only stream sockets are supported") |
|---|
| 769 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 770 | n/a | with self.assertRaises(NotImplementedError) as cx: |
|---|
| 771 | n/a | ctx.wrap_socket(s) |
|---|
| 772 | n/a | self.assertEqual(str(cx.exception), "only stream sockets are supported") |
|---|
| 773 | n/a | |
|---|
| 774 | n/a | def cert_time_ok(self, timestring, timestamp): |
|---|
| 775 | n/a | self.assertEqual(ssl.cert_time_to_seconds(timestring), timestamp) |
|---|
| 776 | n/a | |
|---|
| 777 | n/a | def cert_time_fail(self, timestring): |
|---|
| 778 | n/a | with self.assertRaises(ValueError): |
|---|
| 779 | n/a | ssl.cert_time_to_seconds(timestring) |
|---|
| 780 | n/a | |
|---|
| 781 | n/a | @unittest.skipUnless(utc_offset(), |
|---|
| 782 | n/a | 'local time needs to be different from UTC') |
|---|
| 783 | n/a | def test_cert_time_to_seconds_timezone(self): |
|---|
| 784 | n/a | # Issue #19940: ssl.cert_time_to_seconds() returns wrong |
|---|
| 785 | n/a | # results if local timezone is not UTC |
|---|
| 786 | n/a | self.cert_time_ok("May 9 00:00:00 2007 GMT", 1178668800.0) |
|---|
| 787 | n/a | self.cert_time_ok("Jan 5 09:34:43 2018 GMT", 1515144883.0) |
|---|
| 788 | n/a | |
|---|
| 789 | n/a | def test_cert_time_to_seconds(self): |
|---|
| 790 | n/a | timestring = "Jan 5 09:34:43 2018 GMT" |
|---|
| 791 | n/a | ts = 1515144883.0 |
|---|
| 792 | n/a | self.cert_time_ok(timestring, ts) |
|---|
| 793 | n/a | # accept keyword parameter, assert its name |
|---|
| 794 | n/a | self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts) |
|---|
| 795 | n/a | # accept both %e and %d (space or zero generated by strftime) |
|---|
| 796 | n/a | self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts) |
|---|
| 797 | n/a | # case-insensitive |
|---|
| 798 | n/a | self.cert_time_ok("JaN 5 09:34:43 2018 GmT", ts) |
|---|
| 799 | n/a | self.cert_time_fail("Jan 5 09:34 2018 GMT") # no seconds |
|---|
| 800 | n/a | self.cert_time_fail("Jan 5 09:34:43 2018") # no GMT |
|---|
| 801 | n/a | self.cert_time_fail("Jan 5 09:34:43 2018 UTC") # not GMT timezone |
|---|
| 802 | n/a | self.cert_time_fail("Jan 35 09:34:43 2018 GMT") # invalid day |
|---|
| 803 | n/a | self.cert_time_fail("Jon 5 09:34:43 2018 GMT") # invalid month |
|---|
| 804 | n/a | self.cert_time_fail("Jan 5 24:00:00 2018 GMT") # invalid hour |
|---|
| 805 | n/a | self.cert_time_fail("Jan 5 09:60:43 2018 GMT") # invalid minute |
|---|
| 806 | n/a | |
|---|
| 807 | n/a | newyear_ts = 1230768000.0 |
|---|
| 808 | n/a | # leap seconds |
|---|
| 809 | n/a | self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts) |
|---|
| 810 | n/a | # same timestamp |
|---|
| 811 | n/a | self.cert_time_ok("Jan 1 00:00:00 2009 GMT", newyear_ts) |
|---|
| 812 | n/a | |
|---|
| 813 | n/a | self.cert_time_ok("Jan 5 09:34:59 2018 GMT", 1515144899) |
|---|
| 814 | n/a | # allow 60th second (even if it is not a leap second) |
|---|
| 815 | n/a | self.cert_time_ok("Jan 5 09:34:60 2018 GMT", 1515144900) |
|---|
| 816 | n/a | # allow 2nd leap second for compatibility with time.strptime() |
|---|
| 817 | n/a | self.cert_time_ok("Jan 5 09:34:61 2018 GMT", 1515144901) |
|---|
| 818 | n/a | self.cert_time_fail("Jan 5 09:34:62 2018 GMT") # invalid seconds |
|---|
| 819 | n/a | |
|---|
| 820 | n/a | # no special treatement for the special value: |
|---|
| 821 | n/a | # 99991231235959Z (rfc 5280) |
|---|
| 822 | n/a | self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0) |
|---|
| 823 | n/a | |
|---|
| 824 | n/a | @support.run_with_locale('LC_ALL', '') |
|---|
| 825 | n/a | def test_cert_time_to_seconds_locale(self): |
|---|
| 826 | n/a | # `cert_time_to_seconds()` should be locale independent |
|---|
| 827 | n/a | |
|---|
| 828 | n/a | def local_february_name(): |
|---|
| 829 | n/a | return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0)) |
|---|
| 830 | n/a | |
|---|
| 831 | n/a | if local_february_name().lower() == 'feb': |
|---|
| 832 | n/a | self.skipTest("locale-specific month name needs to be " |
|---|
| 833 | n/a | "different from C locale") |
|---|
| 834 | n/a | |
|---|
| 835 | n/a | # locale-independent |
|---|
| 836 | n/a | self.cert_time_ok("Feb 9 00:00:00 2007 GMT", 1170979200.0) |
|---|
| 837 | n/a | self.cert_time_fail(local_february_name() + " 9 00:00:00 2007 GMT") |
|---|
| 838 | n/a | |
|---|
| 839 | n/a | def test_connect_ex_error(self): |
|---|
| 840 | n/a | server = socket.socket(socket.AF_INET) |
|---|
| 841 | n/a | self.addCleanup(server.close) |
|---|
| 842 | n/a | port = support.bind_port(server) # Reserve port but don't listen |
|---|
| 843 | n/a | s = test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 844 | n/a | cert_reqs=ssl.CERT_REQUIRED) |
|---|
| 845 | n/a | self.addCleanup(s.close) |
|---|
| 846 | n/a | rc = s.connect_ex((HOST, port)) |
|---|
| 847 | n/a | # Issue #19919: Windows machines or VMs hosted on Windows |
|---|
| 848 | n/a | # machines sometimes return EWOULDBLOCK. |
|---|
| 849 | n/a | errors = ( |
|---|
| 850 | n/a | errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, |
|---|
| 851 | n/a | errno.EWOULDBLOCK, |
|---|
| 852 | n/a | ) |
|---|
| 853 | n/a | self.assertIn(rc, errors) |
|---|
| 854 | n/a | |
|---|
| 855 | n/a | |
|---|
| 856 | n/a | class ContextTests(unittest.TestCase): |
|---|
| 857 | n/a | |
|---|
| 858 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 859 | n/a | def test_constructor(self): |
|---|
| 860 | n/a | for protocol in PROTOCOLS: |
|---|
| 861 | n/a | ssl.SSLContext(protocol) |
|---|
| 862 | n/a | ctx = ssl.SSLContext() |
|---|
| 863 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) |
|---|
| 864 | n/a | self.assertRaises(ValueError, ssl.SSLContext, -1) |
|---|
| 865 | n/a | self.assertRaises(ValueError, ssl.SSLContext, 42) |
|---|
| 866 | n/a | |
|---|
| 867 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 868 | n/a | def test_protocol(self): |
|---|
| 869 | n/a | for proto in PROTOCOLS: |
|---|
| 870 | n/a | ctx = ssl.SSLContext(proto) |
|---|
| 871 | n/a | self.assertEqual(ctx.protocol, proto) |
|---|
| 872 | n/a | |
|---|
| 873 | n/a | def test_ciphers(self): |
|---|
| 874 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 875 | n/a | ctx.set_ciphers("ALL") |
|---|
| 876 | n/a | ctx.set_ciphers("DEFAULT") |
|---|
| 877 | n/a | with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
|---|
| 878 | n/a | ctx.set_ciphers("^$:,;?*'dorothyx") |
|---|
| 879 | n/a | |
|---|
| 880 | n/a | @unittest.skipIf(ssl.OPENSSL_VERSION_INFO < (1, 0, 2, 0, 0), 'OpenSSL too old') |
|---|
| 881 | n/a | def test_get_ciphers(self): |
|---|
| 882 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 883 | n/a | ctx.set_ciphers('AESGCM') |
|---|
| 884 | n/a | names = set(d['name'] for d in ctx.get_ciphers()) |
|---|
| 885 | n/a | self.assertIn('AES256-GCM-SHA384', names) |
|---|
| 886 | n/a | self.assertIn('AES128-GCM-SHA256', names) |
|---|
| 887 | n/a | |
|---|
| 888 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 889 | n/a | def test_options(self): |
|---|
| 890 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 891 | n/a | # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value |
|---|
| 892 | n/a | default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
|---|
| 893 | n/a | # SSLContext also enables these by default |
|---|
| 894 | n/a | default |= (OP_NO_COMPRESSION | OP_CIPHER_SERVER_PREFERENCE | |
|---|
| 895 | n/a | OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE) |
|---|
| 896 | n/a | self.assertEqual(default, ctx.options) |
|---|
| 897 | n/a | ctx.options |= ssl.OP_NO_TLSv1 |
|---|
| 898 | n/a | self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options) |
|---|
| 899 | n/a | if can_clear_options(): |
|---|
| 900 | n/a | ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1) |
|---|
| 901 | n/a | self.assertEqual(default, ctx.options) |
|---|
| 902 | n/a | ctx.options = 0 |
|---|
| 903 | n/a | # Ubuntu has OP_NO_SSLv3 forced on by default |
|---|
| 904 | n/a | self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) |
|---|
| 905 | n/a | else: |
|---|
| 906 | n/a | with self.assertRaises(ValueError): |
|---|
| 907 | n/a | ctx.options = 0 |
|---|
| 908 | n/a | |
|---|
| 909 | n/a | def test_verify_mode(self): |
|---|
| 910 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 911 | n/a | # Default value |
|---|
| 912 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 913 | n/a | ctx.verify_mode = ssl.CERT_OPTIONAL |
|---|
| 914 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
|---|
| 915 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 916 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
|---|
| 917 | n/a | ctx.verify_mode = ssl.CERT_NONE |
|---|
| 918 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 919 | n/a | with self.assertRaises(TypeError): |
|---|
| 920 | n/a | ctx.verify_mode = None |
|---|
| 921 | n/a | with self.assertRaises(ValueError): |
|---|
| 922 | n/a | ctx.verify_mode = 42 |
|---|
| 923 | n/a | |
|---|
| 924 | n/a | @unittest.skipUnless(have_verify_flags(), |
|---|
| 925 | n/a | "verify_flags need OpenSSL > 0.9.8") |
|---|
| 926 | n/a | def test_verify_flags(self): |
|---|
| 927 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 928 | n/a | # default value |
|---|
| 929 | n/a | tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) |
|---|
| 930 | n/a | self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf) |
|---|
| 931 | n/a | ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF |
|---|
| 932 | n/a | self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF) |
|---|
| 933 | n/a | ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN |
|---|
| 934 | n/a | self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN) |
|---|
| 935 | n/a | ctx.verify_flags = ssl.VERIFY_DEFAULT |
|---|
| 936 | n/a | self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT) |
|---|
| 937 | n/a | # supports any value |
|---|
| 938 | n/a | ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT |
|---|
| 939 | n/a | self.assertEqual(ctx.verify_flags, |
|---|
| 940 | n/a | ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT) |
|---|
| 941 | n/a | with self.assertRaises(TypeError): |
|---|
| 942 | n/a | ctx.verify_flags = None |
|---|
| 943 | n/a | |
|---|
| 944 | n/a | def test_load_cert_chain(self): |
|---|
| 945 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 946 | n/a | # Combined key and cert in a single file |
|---|
| 947 | n/a | ctx.load_cert_chain(CERTFILE, keyfile=None) |
|---|
| 948 | n/a | ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) |
|---|
| 949 | n/a | self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) |
|---|
| 950 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 951 | n/a | ctx.load_cert_chain(NONEXISTINGCERT) |
|---|
| 952 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 953 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 954 | n/a | ctx.load_cert_chain(BADCERT) |
|---|
| 955 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 956 | n/a | ctx.load_cert_chain(EMPTYCERT) |
|---|
| 957 | n/a | # Separate key and cert |
|---|
| 958 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 959 | n/a | ctx.load_cert_chain(ONLYCERT, ONLYKEY) |
|---|
| 960 | n/a | ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) |
|---|
| 961 | n/a | ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) |
|---|
| 962 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 963 | n/a | ctx.load_cert_chain(ONLYCERT) |
|---|
| 964 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 965 | n/a | ctx.load_cert_chain(ONLYKEY) |
|---|
| 966 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 967 | n/a | ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) |
|---|
| 968 | n/a | # Mismatching key and cert |
|---|
| 969 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 970 | n/a | with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"): |
|---|
| 971 | n/a | ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY) |
|---|
| 972 | n/a | # Password protected key and cert |
|---|
| 973 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD) |
|---|
| 974 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode()) |
|---|
| 975 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, |
|---|
| 976 | n/a | password=bytearray(KEY_PASSWORD.encode())) |
|---|
| 977 | n/a | ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD) |
|---|
| 978 | n/a | ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode()) |
|---|
| 979 | n/a | ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, |
|---|
| 980 | n/a | bytearray(KEY_PASSWORD.encode())) |
|---|
| 981 | n/a | with self.assertRaisesRegex(TypeError, "should be a string"): |
|---|
| 982 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=True) |
|---|
| 983 | n/a | with self.assertRaises(ssl.SSLError): |
|---|
| 984 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password="badpass") |
|---|
| 985 | n/a | with self.assertRaisesRegex(ValueError, "cannot be longer"): |
|---|
| 986 | n/a | # openssl has a fixed limit on the password buffer. |
|---|
| 987 | n/a | # PEM_BUFSIZE is generally set to 1kb. |
|---|
| 988 | n/a | # Return a string larger than this. |
|---|
| 989 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400) |
|---|
| 990 | n/a | # Password callback |
|---|
| 991 | n/a | def getpass_unicode(): |
|---|
| 992 | n/a | return KEY_PASSWORD |
|---|
| 993 | n/a | def getpass_bytes(): |
|---|
| 994 | n/a | return KEY_PASSWORD.encode() |
|---|
| 995 | n/a | def getpass_bytearray(): |
|---|
| 996 | n/a | return bytearray(KEY_PASSWORD.encode()) |
|---|
| 997 | n/a | def getpass_badpass(): |
|---|
| 998 | n/a | return "badpass" |
|---|
| 999 | n/a | def getpass_huge(): |
|---|
| 1000 | n/a | return b'a' * (1024 * 1024) |
|---|
| 1001 | n/a | def getpass_bad_type(): |
|---|
| 1002 | n/a | return 9 |
|---|
| 1003 | n/a | def getpass_exception(): |
|---|
| 1004 | n/a | raise Exception('getpass error') |
|---|
| 1005 | n/a | class GetPassCallable: |
|---|
| 1006 | n/a | def __call__(self): |
|---|
| 1007 | n/a | return KEY_PASSWORD |
|---|
| 1008 | n/a | def getpass(self): |
|---|
| 1009 | n/a | return KEY_PASSWORD |
|---|
| 1010 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode) |
|---|
| 1011 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes) |
|---|
| 1012 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray) |
|---|
| 1013 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable()) |
|---|
| 1014 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, |
|---|
| 1015 | n/a | password=GetPassCallable().getpass) |
|---|
| 1016 | n/a | with self.assertRaises(ssl.SSLError): |
|---|
| 1017 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass) |
|---|
| 1018 | n/a | with self.assertRaisesRegex(ValueError, "cannot be longer"): |
|---|
| 1019 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge) |
|---|
| 1020 | n/a | with self.assertRaisesRegex(TypeError, "must return a string"): |
|---|
| 1021 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type) |
|---|
| 1022 | n/a | with self.assertRaisesRegex(Exception, "getpass error"): |
|---|
| 1023 | n/a | ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception) |
|---|
| 1024 | n/a | # Make sure the password function isn't called if it isn't needed |
|---|
| 1025 | n/a | ctx.load_cert_chain(CERTFILE, password=getpass_exception) |
|---|
| 1026 | n/a | |
|---|
| 1027 | n/a | def test_load_verify_locations(self): |
|---|
| 1028 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1029 | n/a | ctx.load_verify_locations(CERTFILE) |
|---|
| 1030 | n/a | ctx.load_verify_locations(cafile=CERTFILE, capath=None) |
|---|
| 1031 | n/a | ctx.load_verify_locations(BYTES_CERTFILE) |
|---|
| 1032 | n/a | ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) |
|---|
| 1033 | n/a | self.assertRaises(TypeError, ctx.load_verify_locations) |
|---|
| 1034 | n/a | self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None) |
|---|
| 1035 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 1036 | n/a | ctx.load_verify_locations(NONEXISTINGCERT) |
|---|
| 1037 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 1038 | n/a | with self.assertRaisesRegex(ssl.SSLError, "PEM lib"): |
|---|
| 1039 | n/a | ctx.load_verify_locations(BADCERT) |
|---|
| 1040 | n/a | ctx.load_verify_locations(CERTFILE, CAPATH) |
|---|
| 1041 | n/a | ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) |
|---|
| 1042 | n/a | |
|---|
| 1043 | n/a | # Issue #10989: crash if the second argument type is invalid |
|---|
| 1044 | n/a | self.assertRaises(TypeError, ctx.load_verify_locations, None, True) |
|---|
| 1045 | n/a | |
|---|
| 1046 | n/a | def test_load_verify_cadata(self): |
|---|
| 1047 | n/a | # test cadata |
|---|
| 1048 | n/a | with open(CAFILE_CACERT) as f: |
|---|
| 1049 | n/a | cacert_pem = f.read() |
|---|
| 1050 | n/a | cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem) |
|---|
| 1051 | n/a | with open(CAFILE_NEURONIO) as f: |
|---|
| 1052 | n/a | neuronio_pem = f.read() |
|---|
| 1053 | n/a | neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem) |
|---|
| 1054 | n/a | |
|---|
| 1055 | n/a | # test PEM |
|---|
| 1056 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1057 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 0) |
|---|
| 1058 | n/a | ctx.load_verify_locations(cadata=cacert_pem) |
|---|
| 1059 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 1) |
|---|
| 1060 | n/a | ctx.load_verify_locations(cadata=neuronio_pem) |
|---|
| 1061 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1062 | n/a | # cert already in hash table |
|---|
| 1063 | n/a | ctx.load_verify_locations(cadata=neuronio_pem) |
|---|
| 1064 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1065 | n/a | |
|---|
| 1066 | n/a | # combined |
|---|
| 1067 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1068 | n/a | combined = "\n".join((cacert_pem, neuronio_pem)) |
|---|
| 1069 | n/a | ctx.load_verify_locations(cadata=combined) |
|---|
| 1070 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1071 | n/a | |
|---|
| 1072 | n/a | # with junk around the certs |
|---|
| 1073 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1074 | n/a | combined = ["head", cacert_pem, "other", neuronio_pem, "again", |
|---|
| 1075 | n/a | neuronio_pem, "tail"] |
|---|
| 1076 | n/a | ctx.load_verify_locations(cadata="\n".join(combined)) |
|---|
| 1077 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1078 | n/a | |
|---|
| 1079 | n/a | # test DER |
|---|
| 1080 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1081 | n/a | ctx.load_verify_locations(cadata=cacert_der) |
|---|
| 1082 | n/a | ctx.load_verify_locations(cadata=neuronio_der) |
|---|
| 1083 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1084 | n/a | # cert already in hash table |
|---|
| 1085 | n/a | ctx.load_verify_locations(cadata=cacert_der) |
|---|
| 1086 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1087 | n/a | |
|---|
| 1088 | n/a | # combined |
|---|
| 1089 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1090 | n/a | combined = b"".join((cacert_der, neuronio_der)) |
|---|
| 1091 | n/a | ctx.load_verify_locations(cadata=combined) |
|---|
| 1092 | n/a | self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
|---|
| 1093 | n/a | |
|---|
| 1094 | n/a | # error cases |
|---|
| 1095 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1096 | n/a | self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object) |
|---|
| 1097 | n/a | |
|---|
| 1098 | n/a | with self.assertRaisesRegex(ssl.SSLError, "no start line"): |
|---|
| 1099 | n/a | ctx.load_verify_locations(cadata="broken") |
|---|
| 1100 | n/a | with self.assertRaisesRegex(ssl.SSLError, "not enough data"): |
|---|
| 1101 | n/a | ctx.load_verify_locations(cadata=b"broken") |
|---|
| 1102 | n/a | |
|---|
| 1103 | n/a | |
|---|
| 1104 | n/a | def test_load_dh_params(self): |
|---|
| 1105 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1106 | n/a | ctx.load_dh_params(DHFILE) |
|---|
| 1107 | n/a | if os.name != 'nt': |
|---|
| 1108 | n/a | ctx.load_dh_params(BYTES_DHFILE) |
|---|
| 1109 | n/a | self.assertRaises(TypeError, ctx.load_dh_params) |
|---|
| 1110 | n/a | self.assertRaises(TypeError, ctx.load_dh_params, None) |
|---|
| 1111 | n/a | with self.assertRaises(FileNotFoundError) as cm: |
|---|
| 1112 | n/a | ctx.load_dh_params(NONEXISTINGCERT) |
|---|
| 1113 | n/a | self.assertEqual(cm.exception.errno, errno.ENOENT) |
|---|
| 1114 | n/a | with self.assertRaises(ssl.SSLError) as cm: |
|---|
| 1115 | n/a | ctx.load_dh_params(CERTFILE) |
|---|
| 1116 | n/a | |
|---|
| 1117 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 1118 | n/a | def test_session_stats(self): |
|---|
| 1119 | n/a | for proto in PROTOCOLS: |
|---|
| 1120 | n/a | ctx = ssl.SSLContext(proto) |
|---|
| 1121 | n/a | self.assertEqual(ctx.session_stats(), { |
|---|
| 1122 | n/a | 'number': 0, |
|---|
| 1123 | n/a | 'connect': 0, |
|---|
| 1124 | n/a | 'connect_good': 0, |
|---|
| 1125 | n/a | 'connect_renegotiate': 0, |
|---|
| 1126 | n/a | 'accept': 0, |
|---|
| 1127 | n/a | 'accept_good': 0, |
|---|
| 1128 | n/a | 'accept_renegotiate': 0, |
|---|
| 1129 | n/a | 'hits': 0, |
|---|
| 1130 | n/a | 'misses': 0, |
|---|
| 1131 | n/a | 'timeouts': 0, |
|---|
| 1132 | n/a | 'cache_full': 0, |
|---|
| 1133 | n/a | }) |
|---|
| 1134 | n/a | |
|---|
| 1135 | n/a | def test_set_default_verify_paths(self): |
|---|
| 1136 | n/a | # There's not much we can do to test that it acts as expected, |
|---|
| 1137 | n/a | # so just check it doesn't crash or raise an exception. |
|---|
| 1138 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1139 | n/a | ctx.set_default_verify_paths() |
|---|
| 1140 | n/a | |
|---|
| 1141 | n/a | @unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build") |
|---|
| 1142 | n/a | def test_set_ecdh_curve(self): |
|---|
| 1143 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1144 | n/a | ctx.set_ecdh_curve("prime256v1") |
|---|
| 1145 | n/a | ctx.set_ecdh_curve(b"prime256v1") |
|---|
| 1146 | n/a | self.assertRaises(TypeError, ctx.set_ecdh_curve) |
|---|
| 1147 | n/a | self.assertRaises(TypeError, ctx.set_ecdh_curve, None) |
|---|
| 1148 | n/a | self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo") |
|---|
| 1149 | n/a | self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo") |
|---|
| 1150 | n/a | |
|---|
| 1151 | n/a | @needs_sni |
|---|
| 1152 | n/a | def test_sni_callback(self): |
|---|
| 1153 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1154 | n/a | |
|---|
| 1155 | n/a | # set_servername_callback expects a callable, or None |
|---|
| 1156 | n/a | self.assertRaises(TypeError, ctx.set_servername_callback) |
|---|
| 1157 | n/a | self.assertRaises(TypeError, ctx.set_servername_callback, 4) |
|---|
| 1158 | n/a | self.assertRaises(TypeError, ctx.set_servername_callback, "") |
|---|
| 1159 | n/a | self.assertRaises(TypeError, ctx.set_servername_callback, ctx) |
|---|
| 1160 | n/a | |
|---|
| 1161 | n/a | def dummycallback(sock, servername, ctx): |
|---|
| 1162 | n/a | pass |
|---|
| 1163 | n/a | ctx.set_servername_callback(None) |
|---|
| 1164 | n/a | ctx.set_servername_callback(dummycallback) |
|---|
| 1165 | n/a | |
|---|
| 1166 | n/a | @needs_sni |
|---|
| 1167 | n/a | def test_sni_callback_refcycle(self): |
|---|
| 1168 | n/a | # Reference cycles through the servername callback are detected |
|---|
| 1169 | n/a | # and cleared. |
|---|
| 1170 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1171 | n/a | def dummycallback(sock, servername, ctx, cycle=ctx): |
|---|
| 1172 | n/a | pass |
|---|
| 1173 | n/a | ctx.set_servername_callback(dummycallback) |
|---|
| 1174 | n/a | wr = weakref.ref(ctx) |
|---|
| 1175 | n/a | del ctx, dummycallback |
|---|
| 1176 | n/a | gc.collect() |
|---|
| 1177 | n/a | self.assertIs(wr(), None) |
|---|
| 1178 | n/a | |
|---|
| 1179 | n/a | def test_cert_store_stats(self): |
|---|
| 1180 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1181 | n/a | self.assertEqual(ctx.cert_store_stats(), |
|---|
| 1182 | n/a | {'x509_ca': 0, 'crl': 0, 'x509': 0}) |
|---|
| 1183 | n/a | ctx.load_cert_chain(CERTFILE) |
|---|
| 1184 | n/a | self.assertEqual(ctx.cert_store_stats(), |
|---|
| 1185 | n/a | {'x509_ca': 0, 'crl': 0, 'x509': 0}) |
|---|
| 1186 | n/a | ctx.load_verify_locations(CERTFILE) |
|---|
| 1187 | n/a | self.assertEqual(ctx.cert_store_stats(), |
|---|
| 1188 | n/a | {'x509_ca': 0, 'crl': 0, 'x509': 1}) |
|---|
| 1189 | n/a | ctx.load_verify_locations(CAFILE_CACERT) |
|---|
| 1190 | n/a | self.assertEqual(ctx.cert_store_stats(), |
|---|
| 1191 | n/a | {'x509_ca': 1, 'crl': 0, 'x509': 2}) |
|---|
| 1192 | n/a | |
|---|
| 1193 | n/a | def test_get_ca_certs(self): |
|---|
| 1194 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1195 | n/a | self.assertEqual(ctx.get_ca_certs(), []) |
|---|
| 1196 | n/a | # CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE |
|---|
| 1197 | n/a | ctx.load_verify_locations(CERTFILE) |
|---|
| 1198 | n/a | self.assertEqual(ctx.get_ca_certs(), []) |
|---|
| 1199 | n/a | # but CAFILE_CACERT is a CA cert |
|---|
| 1200 | n/a | ctx.load_verify_locations(CAFILE_CACERT) |
|---|
| 1201 | n/a | self.assertEqual(ctx.get_ca_certs(), |
|---|
| 1202 | n/a | [{'issuer': ((('organizationName', 'Root CA'),), |
|---|
| 1203 | n/a | (('organizationalUnitName', 'http://www.cacert.org'),), |
|---|
| 1204 | n/a | (('commonName', 'CA Cert Signing Authority'),), |
|---|
| 1205 | n/a | (('emailAddress', 'support@cacert.org'),)), |
|---|
| 1206 | n/a | 'notAfter': asn1time('Mar 29 12:29:49 2033 GMT'), |
|---|
| 1207 | n/a | 'notBefore': asn1time('Mar 30 12:29:49 2003 GMT'), |
|---|
| 1208 | n/a | 'serialNumber': '00', |
|---|
| 1209 | n/a | 'crlDistributionPoints': ('https://www.cacert.org/revoke.crl',), |
|---|
| 1210 | n/a | 'subject': ((('organizationName', 'Root CA'),), |
|---|
| 1211 | n/a | (('organizationalUnitName', 'http://www.cacert.org'),), |
|---|
| 1212 | n/a | (('commonName', 'CA Cert Signing Authority'),), |
|---|
| 1213 | n/a | (('emailAddress', 'support@cacert.org'),)), |
|---|
| 1214 | n/a | 'version': 3}]) |
|---|
| 1215 | n/a | |
|---|
| 1216 | n/a | with open(CAFILE_CACERT) as f: |
|---|
| 1217 | n/a | pem = f.read() |
|---|
| 1218 | n/a | der = ssl.PEM_cert_to_DER_cert(pem) |
|---|
| 1219 | n/a | self.assertEqual(ctx.get_ca_certs(True), [der]) |
|---|
| 1220 | n/a | |
|---|
| 1221 | n/a | def test_load_default_certs(self): |
|---|
| 1222 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1223 | n/a | ctx.load_default_certs() |
|---|
| 1224 | n/a | |
|---|
| 1225 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1226 | n/a | ctx.load_default_certs(ssl.Purpose.SERVER_AUTH) |
|---|
| 1227 | n/a | ctx.load_default_certs() |
|---|
| 1228 | n/a | |
|---|
| 1229 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1230 | n/a | ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH) |
|---|
| 1231 | n/a | |
|---|
| 1232 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1233 | n/a | self.assertRaises(TypeError, ctx.load_default_certs, None) |
|---|
| 1234 | n/a | self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH') |
|---|
| 1235 | n/a | |
|---|
| 1236 | n/a | @unittest.skipIf(sys.platform == "win32", "not-Windows specific") |
|---|
| 1237 | n/a | @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars") |
|---|
| 1238 | n/a | def test_load_default_certs_env(self): |
|---|
| 1239 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1240 | n/a | with support.EnvironmentVarGuard() as env: |
|---|
| 1241 | n/a | env["SSL_CERT_DIR"] = CAPATH |
|---|
| 1242 | n/a | env["SSL_CERT_FILE"] = CERTFILE |
|---|
| 1243 | n/a | ctx.load_default_certs() |
|---|
| 1244 | n/a | self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0}) |
|---|
| 1245 | n/a | |
|---|
| 1246 | n/a | @unittest.skipUnless(sys.platform == "win32", "Windows specific") |
|---|
| 1247 | n/a | def test_load_default_certs_env_windows(self): |
|---|
| 1248 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1249 | n/a | ctx.load_default_certs() |
|---|
| 1250 | n/a | stats = ctx.cert_store_stats() |
|---|
| 1251 | n/a | |
|---|
| 1252 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1253 | n/a | with support.EnvironmentVarGuard() as env: |
|---|
| 1254 | n/a | env["SSL_CERT_DIR"] = CAPATH |
|---|
| 1255 | n/a | env["SSL_CERT_FILE"] = CERTFILE |
|---|
| 1256 | n/a | ctx.load_default_certs() |
|---|
| 1257 | n/a | stats["x509"] += 1 |
|---|
| 1258 | n/a | self.assertEqual(ctx.cert_store_stats(), stats) |
|---|
| 1259 | n/a | |
|---|
| 1260 | n/a | def _assert_context_options(self, ctx): |
|---|
| 1261 | n/a | self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2) |
|---|
| 1262 | n/a | if OP_NO_COMPRESSION != 0: |
|---|
| 1263 | n/a | self.assertEqual(ctx.options & OP_NO_COMPRESSION, |
|---|
| 1264 | n/a | OP_NO_COMPRESSION) |
|---|
| 1265 | n/a | if OP_SINGLE_DH_USE != 0: |
|---|
| 1266 | n/a | self.assertEqual(ctx.options & OP_SINGLE_DH_USE, |
|---|
| 1267 | n/a | OP_SINGLE_DH_USE) |
|---|
| 1268 | n/a | if OP_SINGLE_ECDH_USE != 0: |
|---|
| 1269 | n/a | self.assertEqual(ctx.options & OP_SINGLE_ECDH_USE, |
|---|
| 1270 | n/a | OP_SINGLE_ECDH_USE) |
|---|
| 1271 | n/a | if OP_CIPHER_SERVER_PREFERENCE != 0: |
|---|
| 1272 | n/a | self.assertEqual(ctx.options & OP_CIPHER_SERVER_PREFERENCE, |
|---|
| 1273 | n/a | OP_CIPHER_SERVER_PREFERENCE) |
|---|
| 1274 | n/a | |
|---|
| 1275 | n/a | def test_create_default_context(self): |
|---|
| 1276 | n/a | ctx = ssl.create_default_context() |
|---|
| 1277 | n/a | |
|---|
| 1278 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) |
|---|
| 1279 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
|---|
| 1280 | n/a | self.assertTrue(ctx.check_hostname) |
|---|
| 1281 | n/a | self._assert_context_options(ctx) |
|---|
| 1282 | n/a | |
|---|
| 1283 | n/a | |
|---|
| 1284 | n/a | with open(SIGNING_CA) as f: |
|---|
| 1285 | n/a | cadata = f.read() |
|---|
| 1286 | n/a | ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH, |
|---|
| 1287 | n/a | cadata=cadata) |
|---|
| 1288 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) |
|---|
| 1289 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
|---|
| 1290 | n/a | self._assert_context_options(ctx) |
|---|
| 1291 | n/a | |
|---|
| 1292 | n/a | ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
|---|
| 1293 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) |
|---|
| 1294 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 1295 | n/a | self._assert_context_options(ctx) |
|---|
| 1296 | n/a | |
|---|
| 1297 | n/a | def test__create_stdlib_context(self): |
|---|
| 1298 | n/a | ctx = ssl._create_stdlib_context() |
|---|
| 1299 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) |
|---|
| 1300 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 1301 | n/a | self.assertFalse(ctx.check_hostname) |
|---|
| 1302 | n/a | self._assert_context_options(ctx) |
|---|
| 1303 | n/a | |
|---|
| 1304 | n/a | ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1) |
|---|
| 1305 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) |
|---|
| 1306 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 1307 | n/a | self._assert_context_options(ctx) |
|---|
| 1308 | n/a | |
|---|
| 1309 | n/a | ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1, |
|---|
| 1310 | n/a | cert_reqs=ssl.CERT_REQUIRED, |
|---|
| 1311 | n/a | check_hostname=True) |
|---|
| 1312 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) |
|---|
| 1313 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
|---|
| 1314 | n/a | self.assertTrue(ctx.check_hostname) |
|---|
| 1315 | n/a | self._assert_context_options(ctx) |
|---|
| 1316 | n/a | |
|---|
| 1317 | n/a | ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH) |
|---|
| 1318 | n/a | self.assertEqual(ctx.protocol, ssl.PROTOCOL_SSLv23) |
|---|
| 1319 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 1320 | n/a | self._assert_context_options(ctx) |
|---|
| 1321 | n/a | |
|---|
| 1322 | n/a | def test_check_hostname(self): |
|---|
| 1323 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1324 | n/a | self.assertFalse(ctx.check_hostname) |
|---|
| 1325 | n/a | |
|---|
| 1326 | n/a | # Requires CERT_REQUIRED or CERT_OPTIONAL |
|---|
| 1327 | n/a | with self.assertRaises(ValueError): |
|---|
| 1328 | n/a | ctx.check_hostname = True |
|---|
| 1329 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1330 | n/a | self.assertFalse(ctx.check_hostname) |
|---|
| 1331 | n/a | ctx.check_hostname = True |
|---|
| 1332 | n/a | self.assertTrue(ctx.check_hostname) |
|---|
| 1333 | n/a | |
|---|
| 1334 | n/a | ctx.verify_mode = ssl.CERT_OPTIONAL |
|---|
| 1335 | n/a | ctx.check_hostname = True |
|---|
| 1336 | n/a | self.assertTrue(ctx.check_hostname) |
|---|
| 1337 | n/a | |
|---|
| 1338 | n/a | # Cannot set CERT_NONE with check_hostname enabled |
|---|
| 1339 | n/a | with self.assertRaises(ValueError): |
|---|
| 1340 | n/a | ctx.verify_mode = ssl.CERT_NONE |
|---|
| 1341 | n/a | ctx.check_hostname = False |
|---|
| 1342 | n/a | self.assertFalse(ctx.check_hostname) |
|---|
| 1343 | n/a | |
|---|
| 1344 | n/a | def test_context_client_server(self): |
|---|
| 1345 | n/a | # PROTOCOL_TLS_CLIENT has sane defaults |
|---|
| 1346 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
|---|
| 1347 | n/a | self.assertTrue(ctx.check_hostname) |
|---|
| 1348 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
|---|
| 1349 | n/a | |
|---|
| 1350 | n/a | # PROTOCOL_TLS_SERVER has different but also sane defaults |
|---|
| 1351 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
|---|
| 1352 | n/a | self.assertFalse(ctx.check_hostname) |
|---|
| 1353 | n/a | self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
|---|
| 1354 | n/a | |
|---|
| 1355 | n/a | |
|---|
| 1356 | n/a | class SSLErrorTests(unittest.TestCase): |
|---|
| 1357 | n/a | |
|---|
| 1358 | n/a | def test_str(self): |
|---|
| 1359 | n/a | # The str() of a SSLError doesn't include the errno |
|---|
| 1360 | n/a | e = ssl.SSLError(1, "foo") |
|---|
| 1361 | n/a | self.assertEqual(str(e), "foo") |
|---|
| 1362 | n/a | self.assertEqual(e.errno, 1) |
|---|
| 1363 | n/a | # Same for a subclass |
|---|
| 1364 | n/a | e = ssl.SSLZeroReturnError(1, "foo") |
|---|
| 1365 | n/a | self.assertEqual(str(e), "foo") |
|---|
| 1366 | n/a | self.assertEqual(e.errno, 1) |
|---|
| 1367 | n/a | |
|---|
| 1368 | n/a | def test_lib_reason(self): |
|---|
| 1369 | n/a | # Test the library and reason attributes |
|---|
| 1370 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1371 | n/a | with self.assertRaises(ssl.SSLError) as cm: |
|---|
| 1372 | n/a | ctx.load_dh_params(CERTFILE) |
|---|
| 1373 | n/a | self.assertEqual(cm.exception.library, 'PEM') |
|---|
| 1374 | n/a | self.assertEqual(cm.exception.reason, 'NO_START_LINE') |
|---|
| 1375 | n/a | s = str(cm.exception) |
|---|
| 1376 | n/a | self.assertTrue(s.startswith("[PEM: NO_START_LINE] no start line"), s) |
|---|
| 1377 | n/a | |
|---|
| 1378 | n/a | def test_subclass(self): |
|---|
| 1379 | n/a | # Check that the appropriate SSLError subclass is raised |
|---|
| 1380 | n/a | # (this only tests one of them) |
|---|
| 1381 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1382 | n/a | with socket.socket() as s: |
|---|
| 1383 | n/a | s.bind(("127.0.0.1", 0)) |
|---|
| 1384 | n/a | s.listen() |
|---|
| 1385 | n/a | c = socket.socket() |
|---|
| 1386 | n/a | c.connect(s.getsockname()) |
|---|
| 1387 | n/a | c.setblocking(False) |
|---|
| 1388 | n/a | with ctx.wrap_socket(c, False, do_handshake_on_connect=False) as c: |
|---|
| 1389 | n/a | with self.assertRaises(ssl.SSLWantReadError) as cm: |
|---|
| 1390 | n/a | c.do_handshake() |
|---|
| 1391 | n/a | s = str(cm.exception) |
|---|
| 1392 | n/a | self.assertTrue(s.startswith("The operation did not complete (read)"), s) |
|---|
| 1393 | n/a | # For compatibility |
|---|
| 1394 | n/a | self.assertEqual(cm.exception.errno, ssl.SSL_ERROR_WANT_READ) |
|---|
| 1395 | n/a | |
|---|
| 1396 | n/a | |
|---|
| 1397 | n/a | class MemoryBIOTests(unittest.TestCase): |
|---|
| 1398 | n/a | |
|---|
| 1399 | n/a | def test_read_write(self): |
|---|
| 1400 | n/a | bio = ssl.MemoryBIO() |
|---|
| 1401 | n/a | bio.write(b'foo') |
|---|
| 1402 | n/a | self.assertEqual(bio.read(), b'foo') |
|---|
| 1403 | n/a | self.assertEqual(bio.read(), b'') |
|---|
| 1404 | n/a | bio.write(b'foo') |
|---|
| 1405 | n/a | bio.write(b'bar') |
|---|
| 1406 | n/a | self.assertEqual(bio.read(), b'foobar') |
|---|
| 1407 | n/a | self.assertEqual(bio.read(), b'') |
|---|
| 1408 | n/a | bio.write(b'baz') |
|---|
| 1409 | n/a | self.assertEqual(bio.read(2), b'ba') |
|---|
| 1410 | n/a | self.assertEqual(bio.read(1), b'z') |
|---|
| 1411 | n/a | self.assertEqual(bio.read(1), b'') |
|---|
| 1412 | n/a | |
|---|
| 1413 | n/a | def test_eof(self): |
|---|
| 1414 | n/a | bio = ssl.MemoryBIO() |
|---|
| 1415 | n/a | self.assertFalse(bio.eof) |
|---|
| 1416 | n/a | self.assertEqual(bio.read(), b'') |
|---|
| 1417 | n/a | self.assertFalse(bio.eof) |
|---|
| 1418 | n/a | bio.write(b'foo') |
|---|
| 1419 | n/a | self.assertFalse(bio.eof) |
|---|
| 1420 | n/a | bio.write_eof() |
|---|
| 1421 | n/a | self.assertFalse(bio.eof) |
|---|
| 1422 | n/a | self.assertEqual(bio.read(2), b'fo') |
|---|
| 1423 | n/a | self.assertFalse(bio.eof) |
|---|
| 1424 | n/a | self.assertEqual(bio.read(1), b'o') |
|---|
| 1425 | n/a | self.assertTrue(bio.eof) |
|---|
| 1426 | n/a | self.assertEqual(bio.read(), b'') |
|---|
| 1427 | n/a | self.assertTrue(bio.eof) |
|---|
| 1428 | n/a | |
|---|
| 1429 | n/a | def test_pending(self): |
|---|
| 1430 | n/a | bio = ssl.MemoryBIO() |
|---|
| 1431 | n/a | self.assertEqual(bio.pending, 0) |
|---|
| 1432 | n/a | bio.write(b'foo') |
|---|
| 1433 | n/a | self.assertEqual(bio.pending, 3) |
|---|
| 1434 | n/a | for i in range(3): |
|---|
| 1435 | n/a | bio.read(1) |
|---|
| 1436 | n/a | self.assertEqual(bio.pending, 3-i-1) |
|---|
| 1437 | n/a | for i in range(3): |
|---|
| 1438 | n/a | bio.write(b'x') |
|---|
| 1439 | n/a | self.assertEqual(bio.pending, i+1) |
|---|
| 1440 | n/a | bio.read() |
|---|
| 1441 | n/a | self.assertEqual(bio.pending, 0) |
|---|
| 1442 | n/a | |
|---|
| 1443 | n/a | def test_buffer_types(self): |
|---|
| 1444 | n/a | bio = ssl.MemoryBIO() |
|---|
| 1445 | n/a | bio.write(b'foo') |
|---|
| 1446 | n/a | self.assertEqual(bio.read(), b'foo') |
|---|
| 1447 | n/a | bio.write(bytearray(b'bar')) |
|---|
| 1448 | n/a | self.assertEqual(bio.read(), b'bar') |
|---|
| 1449 | n/a | bio.write(memoryview(b'baz')) |
|---|
| 1450 | n/a | self.assertEqual(bio.read(), b'baz') |
|---|
| 1451 | n/a | |
|---|
| 1452 | n/a | def test_error_types(self): |
|---|
| 1453 | n/a | bio = ssl.MemoryBIO() |
|---|
| 1454 | n/a | self.assertRaises(TypeError, bio.write, 'foo') |
|---|
| 1455 | n/a | self.assertRaises(TypeError, bio.write, None) |
|---|
| 1456 | n/a | self.assertRaises(TypeError, bio.write, True) |
|---|
| 1457 | n/a | self.assertRaises(TypeError, bio.write, 1) |
|---|
| 1458 | n/a | |
|---|
| 1459 | n/a | |
|---|
| 1460 | n/a | @unittest.skipUnless(_have_threads, "Needs threading module") |
|---|
| 1461 | n/a | class SimpleBackgroundTests(unittest.TestCase): |
|---|
| 1462 | n/a | |
|---|
| 1463 | n/a | """Tests that connect to a simple server running in the background""" |
|---|
| 1464 | n/a | |
|---|
| 1465 | n/a | def setUp(self): |
|---|
| 1466 | n/a | server = ThreadedEchoServer(SIGNED_CERTFILE) |
|---|
| 1467 | n/a | self.server_addr = (HOST, server.port) |
|---|
| 1468 | n/a | server.__enter__() |
|---|
| 1469 | n/a | self.addCleanup(server.__exit__, None, None, None) |
|---|
| 1470 | n/a | |
|---|
| 1471 | n/a | def test_connect(self): |
|---|
| 1472 | n/a | with test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1473 | n/a | cert_reqs=ssl.CERT_NONE) as s: |
|---|
| 1474 | n/a | s.connect(self.server_addr) |
|---|
| 1475 | n/a | self.assertEqual({}, s.getpeercert()) |
|---|
| 1476 | n/a | self.assertFalse(s.server_side) |
|---|
| 1477 | n/a | |
|---|
| 1478 | n/a | # this should succeed because we specify the root cert |
|---|
| 1479 | n/a | with test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1480 | n/a | cert_reqs=ssl.CERT_REQUIRED, |
|---|
| 1481 | n/a | ca_certs=SIGNING_CA) as s: |
|---|
| 1482 | n/a | s.connect(self.server_addr) |
|---|
| 1483 | n/a | self.assertTrue(s.getpeercert()) |
|---|
| 1484 | n/a | self.assertFalse(s.server_side) |
|---|
| 1485 | n/a | |
|---|
| 1486 | n/a | def test_connect_fail(self): |
|---|
| 1487 | n/a | # This should fail because we have no verification certs. Connection |
|---|
| 1488 | n/a | # failure crashes ThreadedEchoServer, so run this in an independent |
|---|
| 1489 | n/a | # test method. |
|---|
| 1490 | n/a | s = test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1491 | n/a | cert_reqs=ssl.CERT_REQUIRED) |
|---|
| 1492 | n/a | self.addCleanup(s.close) |
|---|
| 1493 | n/a | self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", |
|---|
| 1494 | n/a | s.connect, self.server_addr) |
|---|
| 1495 | n/a | |
|---|
| 1496 | n/a | def test_connect_ex(self): |
|---|
| 1497 | n/a | # Issue #11326: check connect_ex() implementation |
|---|
| 1498 | n/a | s = test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1499 | n/a | cert_reqs=ssl.CERT_REQUIRED, |
|---|
| 1500 | n/a | ca_certs=SIGNING_CA) |
|---|
| 1501 | n/a | self.addCleanup(s.close) |
|---|
| 1502 | n/a | self.assertEqual(0, s.connect_ex(self.server_addr)) |
|---|
| 1503 | n/a | self.assertTrue(s.getpeercert()) |
|---|
| 1504 | n/a | |
|---|
| 1505 | n/a | def test_non_blocking_connect_ex(self): |
|---|
| 1506 | n/a | # Issue #11326: non-blocking connect_ex() should allow handshake |
|---|
| 1507 | n/a | # to proceed after the socket gets ready. |
|---|
| 1508 | n/a | s = test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1509 | n/a | cert_reqs=ssl.CERT_REQUIRED, |
|---|
| 1510 | n/a | ca_certs=SIGNING_CA, |
|---|
| 1511 | n/a | do_handshake_on_connect=False) |
|---|
| 1512 | n/a | self.addCleanup(s.close) |
|---|
| 1513 | n/a | s.setblocking(False) |
|---|
| 1514 | n/a | rc = s.connect_ex(self.server_addr) |
|---|
| 1515 | n/a | # EWOULDBLOCK under Windows, EINPROGRESS elsewhere |
|---|
| 1516 | n/a | self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) |
|---|
| 1517 | n/a | # Wait for connect to finish |
|---|
| 1518 | n/a | select.select([], [s], [], 5.0) |
|---|
| 1519 | n/a | # Non-blocking handshake |
|---|
| 1520 | n/a | while True: |
|---|
| 1521 | n/a | try: |
|---|
| 1522 | n/a | s.do_handshake() |
|---|
| 1523 | n/a | break |
|---|
| 1524 | n/a | except ssl.SSLWantReadError: |
|---|
| 1525 | n/a | select.select([s], [], [], 5.0) |
|---|
| 1526 | n/a | except ssl.SSLWantWriteError: |
|---|
| 1527 | n/a | select.select([], [s], [], 5.0) |
|---|
| 1528 | n/a | # SSL established |
|---|
| 1529 | n/a | self.assertTrue(s.getpeercert()) |
|---|
| 1530 | n/a | |
|---|
| 1531 | n/a | def test_connect_with_context(self): |
|---|
| 1532 | n/a | # Same as test_connect, but with a separately created context |
|---|
| 1533 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1534 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1535 | n/a | s.connect(self.server_addr) |
|---|
| 1536 | n/a | self.assertEqual({}, s.getpeercert()) |
|---|
| 1537 | n/a | # Same with a server hostname |
|---|
| 1538 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1539 | n/a | server_hostname="dummy") as s: |
|---|
| 1540 | n/a | s.connect(self.server_addr) |
|---|
| 1541 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1542 | n/a | # This should succeed because we specify the root cert |
|---|
| 1543 | n/a | ctx.load_verify_locations(SIGNING_CA) |
|---|
| 1544 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1545 | n/a | s.connect(self.server_addr) |
|---|
| 1546 | n/a | cert = s.getpeercert() |
|---|
| 1547 | n/a | self.assertTrue(cert) |
|---|
| 1548 | n/a | |
|---|
| 1549 | n/a | def test_connect_with_context_fail(self): |
|---|
| 1550 | n/a | # This should fail because we have no verification certs. Connection |
|---|
| 1551 | n/a | # failure crashes ThreadedEchoServer, so run this in an independent |
|---|
| 1552 | n/a | # test method. |
|---|
| 1553 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1554 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1555 | n/a | s = ctx.wrap_socket(socket.socket(socket.AF_INET)) |
|---|
| 1556 | n/a | self.addCleanup(s.close) |
|---|
| 1557 | n/a | self.assertRaisesRegex(ssl.SSLError, "certificate verify failed", |
|---|
| 1558 | n/a | s.connect, self.server_addr) |
|---|
| 1559 | n/a | |
|---|
| 1560 | n/a | def test_connect_capath(self): |
|---|
| 1561 | n/a | # Verify server certificates using the `capath` argument |
|---|
| 1562 | n/a | # NOTE: the subject hashing algorithm has been changed between |
|---|
| 1563 | n/a | # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must |
|---|
| 1564 | n/a | # contain both versions of each certificate (same content, different |
|---|
| 1565 | n/a | # filename) for this test to be portable across OpenSSL releases. |
|---|
| 1566 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1567 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1568 | n/a | ctx.load_verify_locations(capath=CAPATH) |
|---|
| 1569 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1570 | n/a | s.connect(self.server_addr) |
|---|
| 1571 | n/a | cert = s.getpeercert() |
|---|
| 1572 | n/a | self.assertTrue(cert) |
|---|
| 1573 | n/a | # Same with a bytes `capath` argument |
|---|
| 1574 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1575 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1576 | n/a | ctx.load_verify_locations(capath=BYTES_CAPATH) |
|---|
| 1577 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1578 | n/a | s.connect(self.server_addr) |
|---|
| 1579 | n/a | cert = s.getpeercert() |
|---|
| 1580 | n/a | self.assertTrue(cert) |
|---|
| 1581 | n/a | |
|---|
| 1582 | n/a | def test_connect_cadata(self): |
|---|
| 1583 | n/a | with open(SIGNING_CA) as f: |
|---|
| 1584 | n/a | pem = f.read() |
|---|
| 1585 | n/a | der = ssl.PEM_cert_to_DER_cert(pem) |
|---|
| 1586 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1587 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1588 | n/a | ctx.load_verify_locations(cadata=pem) |
|---|
| 1589 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1590 | n/a | s.connect(self.server_addr) |
|---|
| 1591 | n/a | cert = s.getpeercert() |
|---|
| 1592 | n/a | self.assertTrue(cert) |
|---|
| 1593 | n/a | |
|---|
| 1594 | n/a | # same with DER |
|---|
| 1595 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1596 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1597 | n/a | ctx.load_verify_locations(cadata=der) |
|---|
| 1598 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1599 | n/a | s.connect(self.server_addr) |
|---|
| 1600 | n/a | cert = s.getpeercert() |
|---|
| 1601 | n/a | self.assertTrue(cert) |
|---|
| 1602 | n/a | |
|---|
| 1603 | n/a | @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") |
|---|
| 1604 | n/a | def test_makefile_close(self): |
|---|
| 1605 | n/a | # Issue #5238: creating a file-like object with makefile() shouldn't |
|---|
| 1606 | n/a | # delay closing the underlying "real socket" (here tested with its |
|---|
| 1607 | n/a | # file descriptor, hence skipping the test under Windows). |
|---|
| 1608 | n/a | ss = test_wrap_socket(socket.socket(socket.AF_INET)) |
|---|
| 1609 | n/a | ss.connect(self.server_addr) |
|---|
| 1610 | n/a | fd = ss.fileno() |
|---|
| 1611 | n/a | f = ss.makefile() |
|---|
| 1612 | n/a | f.close() |
|---|
| 1613 | n/a | # The fd is still open |
|---|
| 1614 | n/a | os.read(fd, 0) |
|---|
| 1615 | n/a | # Closing the SSL socket should close the fd too |
|---|
| 1616 | n/a | ss.close() |
|---|
| 1617 | n/a | gc.collect() |
|---|
| 1618 | n/a | with self.assertRaises(OSError) as e: |
|---|
| 1619 | n/a | os.read(fd, 0) |
|---|
| 1620 | n/a | self.assertEqual(e.exception.errno, errno.EBADF) |
|---|
| 1621 | n/a | |
|---|
| 1622 | n/a | def test_non_blocking_handshake(self): |
|---|
| 1623 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 1624 | n/a | s.connect(self.server_addr) |
|---|
| 1625 | n/a | s.setblocking(False) |
|---|
| 1626 | n/a | s = test_wrap_socket(s, |
|---|
| 1627 | n/a | cert_reqs=ssl.CERT_NONE, |
|---|
| 1628 | n/a | do_handshake_on_connect=False) |
|---|
| 1629 | n/a | self.addCleanup(s.close) |
|---|
| 1630 | n/a | count = 0 |
|---|
| 1631 | n/a | while True: |
|---|
| 1632 | n/a | try: |
|---|
| 1633 | n/a | count += 1 |
|---|
| 1634 | n/a | s.do_handshake() |
|---|
| 1635 | n/a | break |
|---|
| 1636 | n/a | except ssl.SSLWantReadError: |
|---|
| 1637 | n/a | select.select([s], [], []) |
|---|
| 1638 | n/a | except ssl.SSLWantWriteError: |
|---|
| 1639 | n/a | select.select([], [s], []) |
|---|
| 1640 | n/a | if support.verbose: |
|---|
| 1641 | n/a | sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) |
|---|
| 1642 | n/a | |
|---|
| 1643 | n/a | def test_get_server_certificate(self): |
|---|
| 1644 | n/a | _test_get_server_certificate(self, *self.server_addr, cert=SIGNING_CA) |
|---|
| 1645 | n/a | |
|---|
| 1646 | n/a | def test_get_server_certificate_fail(self): |
|---|
| 1647 | n/a | # Connection failure crashes ThreadedEchoServer, so run this in an |
|---|
| 1648 | n/a | # independent test method |
|---|
| 1649 | n/a | _test_get_server_certificate_fail(self, *self.server_addr) |
|---|
| 1650 | n/a | |
|---|
| 1651 | n/a | def test_ciphers(self): |
|---|
| 1652 | n/a | with test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1653 | n/a | cert_reqs=ssl.CERT_NONE, ciphers="ALL") as s: |
|---|
| 1654 | n/a | s.connect(self.server_addr) |
|---|
| 1655 | n/a | with test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1656 | n/a | cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") as s: |
|---|
| 1657 | n/a | s.connect(self.server_addr) |
|---|
| 1658 | n/a | # Error checking can happen at instantiation or when connecting |
|---|
| 1659 | n/a | with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
|---|
| 1660 | n/a | with socket.socket(socket.AF_INET) as sock: |
|---|
| 1661 | n/a | s = test_wrap_socket(sock, |
|---|
| 1662 | n/a | cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") |
|---|
| 1663 | n/a | s.connect(self.server_addr) |
|---|
| 1664 | n/a | |
|---|
| 1665 | n/a | def test_get_ca_certs_capath(self): |
|---|
| 1666 | n/a | # capath certs are loaded on request |
|---|
| 1667 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1668 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1669 | n/a | ctx.load_verify_locations(capath=CAPATH) |
|---|
| 1670 | n/a | self.assertEqual(ctx.get_ca_certs(), []) |
|---|
| 1671 | n/a | with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
|---|
| 1672 | n/a | s.connect(self.server_addr) |
|---|
| 1673 | n/a | cert = s.getpeercert() |
|---|
| 1674 | n/a | self.assertTrue(cert) |
|---|
| 1675 | n/a | self.assertEqual(len(ctx.get_ca_certs()), 1) |
|---|
| 1676 | n/a | |
|---|
| 1677 | n/a | @needs_sni |
|---|
| 1678 | n/a | def test_context_setget(self): |
|---|
| 1679 | n/a | # Check that the context of a connected socket can be replaced. |
|---|
| 1680 | n/a | ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1681 | n/a | ctx2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1682 | n/a | s = socket.socket(socket.AF_INET) |
|---|
| 1683 | n/a | with ctx1.wrap_socket(s) as ss: |
|---|
| 1684 | n/a | ss.connect(self.server_addr) |
|---|
| 1685 | n/a | self.assertIs(ss.context, ctx1) |
|---|
| 1686 | n/a | self.assertIs(ss._sslobj.context, ctx1) |
|---|
| 1687 | n/a | ss.context = ctx2 |
|---|
| 1688 | n/a | self.assertIs(ss.context, ctx2) |
|---|
| 1689 | n/a | self.assertIs(ss._sslobj.context, ctx2) |
|---|
| 1690 | n/a | |
|---|
| 1691 | n/a | def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs): |
|---|
| 1692 | n/a | # A simple IO loop. Call func(*args) depending on the error we get |
|---|
| 1693 | n/a | # (WANT_READ or WANT_WRITE) move data between the socket and the BIOs. |
|---|
| 1694 | n/a | timeout = kwargs.get('timeout', 10) |
|---|
| 1695 | n/a | count = 0 |
|---|
| 1696 | n/a | while True: |
|---|
| 1697 | n/a | errno = None |
|---|
| 1698 | n/a | count += 1 |
|---|
| 1699 | n/a | try: |
|---|
| 1700 | n/a | ret = func(*args) |
|---|
| 1701 | n/a | except ssl.SSLError as e: |
|---|
| 1702 | n/a | if e.errno not in (ssl.SSL_ERROR_WANT_READ, |
|---|
| 1703 | n/a | ssl.SSL_ERROR_WANT_WRITE): |
|---|
| 1704 | n/a | raise |
|---|
| 1705 | n/a | errno = e.errno |
|---|
| 1706 | n/a | # Get any data from the outgoing BIO irrespective of any error, and |
|---|
| 1707 | n/a | # send it to the socket. |
|---|
| 1708 | n/a | buf = outgoing.read() |
|---|
| 1709 | n/a | sock.sendall(buf) |
|---|
| 1710 | n/a | # If there's no error, we're done. For WANT_READ, we need to get |
|---|
| 1711 | n/a | # data from the socket and put it in the incoming BIO. |
|---|
| 1712 | n/a | if errno is None: |
|---|
| 1713 | n/a | break |
|---|
| 1714 | n/a | elif errno == ssl.SSL_ERROR_WANT_READ: |
|---|
| 1715 | n/a | buf = sock.recv(32768) |
|---|
| 1716 | n/a | if buf: |
|---|
| 1717 | n/a | incoming.write(buf) |
|---|
| 1718 | n/a | else: |
|---|
| 1719 | n/a | incoming.write_eof() |
|---|
| 1720 | n/a | if support.verbose: |
|---|
| 1721 | n/a | sys.stdout.write("Needed %d calls to complete %s().\n" |
|---|
| 1722 | n/a | % (count, func.__name__)) |
|---|
| 1723 | n/a | return ret |
|---|
| 1724 | n/a | |
|---|
| 1725 | n/a | def test_bio_handshake(self): |
|---|
| 1726 | n/a | sock = socket.socket(socket.AF_INET) |
|---|
| 1727 | n/a | self.addCleanup(sock.close) |
|---|
| 1728 | n/a | sock.connect(self.server_addr) |
|---|
| 1729 | n/a | incoming = ssl.MemoryBIO() |
|---|
| 1730 | n/a | outgoing = ssl.MemoryBIO() |
|---|
| 1731 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1732 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1733 | n/a | ctx.load_verify_locations(SIGNING_CA) |
|---|
| 1734 | n/a | ctx.check_hostname = True |
|---|
| 1735 | n/a | sslobj = ctx.wrap_bio(incoming, outgoing, False, 'localhost') |
|---|
| 1736 | n/a | self.assertIs(sslobj._sslobj.owner, sslobj) |
|---|
| 1737 | n/a | self.assertIsNone(sslobj.cipher()) |
|---|
| 1738 | n/a | self.assertIsNotNone(sslobj.shared_ciphers()) |
|---|
| 1739 | n/a | self.assertRaises(ValueError, sslobj.getpeercert) |
|---|
| 1740 | n/a | if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: |
|---|
| 1741 | n/a | self.assertIsNone(sslobj.get_channel_binding('tls-unique')) |
|---|
| 1742 | n/a | self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) |
|---|
| 1743 | n/a | self.assertTrue(sslobj.cipher()) |
|---|
| 1744 | n/a | self.assertIsNotNone(sslobj.shared_ciphers()) |
|---|
| 1745 | n/a | self.assertTrue(sslobj.getpeercert()) |
|---|
| 1746 | n/a | if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES: |
|---|
| 1747 | n/a | self.assertTrue(sslobj.get_channel_binding('tls-unique')) |
|---|
| 1748 | n/a | try: |
|---|
| 1749 | n/a | self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) |
|---|
| 1750 | n/a | except ssl.SSLSyscallError: |
|---|
| 1751 | n/a | # If the server shuts down the TCP connection without sending a |
|---|
| 1752 | n/a | # secure shutdown message, this is reported as SSL_ERROR_SYSCALL |
|---|
| 1753 | n/a | pass |
|---|
| 1754 | n/a | self.assertRaises(ssl.SSLError, sslobj.write, b'foo') |
|---|
| 1755 | n/a | |
|---|
| 1756 | n/a | def test_bio_read_write_data(self): |
|---|
| 1757 | n/a | sock = socket.socket(socket.AF_INET) |
|---|
| 1758 | n/a | self.addCleanup(sock.close) |
|---|
| 1759 | n/a | sock.connect(self.server_addr) |
|---|
| 1760 | n/a | incoming = ssl.MemoryBIO() |
|---|
| 1761 | n/a | outgoing = ssl.MemoryBIO() |
|---|
| 1762 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 1763 | n/a | ctx.verify_mode = ssl.CERT_NONE |
|---|
| 1764 | n/a | sslobj = ctx.wrap_bio(incoming, outgoing, False) |
|---|
| 1765 | n/a | self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) |
|---|
| 1766 | n/a | req = b'FOO\n' |
|---|
| 1767 | n/a | self.ssl_io_loop(sock, incoming, outgoing, sslobj.write, req) |
|---|
| 1768 | n/a | buf = self.ssl_io_loop(sock, incoming, outgoing, sslobj.read, 1024) |
|---|
| 1769 | n/a | self.assertEqual(buf, b'foo\n') |
|---|
| 1770 | n/a | self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) |
|---|
| 1771 | n/a | |
|---|
| 1772 | n/a | |
|---|
| 1773 | n/a | class NetworkedTests(unittest.TestCase): |
|---|
| 1774 | n/a | |
|---|
| 1775 | n/a | def test_timeout_connect_ex(self): |
|---|
| 1776 | n/a | # Issue #12065: on a timeout, connect_ex() should return the original |
|---|
| 1777 | n/a | # errno (mimicking the behaviour of non-SSL sockets). |
|---|
| 1778 | n/a | with support.transient_internet(REMOTE_HOST): |
|---|
| 1779 | n/a | s = test_wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1780 | n/a | cert_reqs=ssl.CERT_REQUIRED, |
|---|
| 1781 | n/a | do_handshake_on_connect=False) |
|---|
| 1782 | n/a | self.addCleanup(s.close) |
|---|
| 1783 | n/a | s.settimeout(0.0000001) |
|---|
| 1784 | n/a | rc = s.connect_ex((REMOTE_HOST, 443)) |
|---|
| 1785 | n/a | if rc == 0: |
|---|
| 1786 | n/a | self.skipTest("REMOTE_HOST responded too quickly") |
|---|
| 1787 | n/a | self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) |
|---|
| 1788 | n/a | |
|---|
| 1789 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'Needs IPv6') |
|---|
| 1790 | n/a | def test_get_server_certificate_ipv6(self): |
|---|
| 1791 | n/a | with support.transient_internet('ipv6.google.com'): |
|---|
| 1792 | n/a | _test_get_server_certificate(self, 'ipv6.google.com', 443) |
|---|
| 1793 | n/a | _test_get_server_certificate_fail(self, 'ipv6.google.com', 443) |
|---|
| 1794 | n/a | |
|---|
| 1795 | n/a | def test_algorithms(self): |
|---|
| 1796 | n/a | # Issue #8484: all algorithms should be available when verifying a |
|---|
| 1797 | n/a | # certificate. |
|---|
| 1798 | n/a | # SHA256 was added in OpenSSL 0.9.8 |
|---|
| 1799 | n/a | if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15): |
|---|
| 1800 | n/a | self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION) |
|---|
| 1801 | n/a | # sha256.tbs-internet.com needs SNI to use the correct certificate |
|---|
| 1802 | n/a | if not ssl.HAS_SNI: |
|---|
| 1803 | n/a | self.skipTest("SNI needed for this test") |
|---|
| 1804 | n/a | # https://sha2.hboeck.de/ was used until 2011-01-08 (no route to host) |
|---|
| 1805 | n/a | remote = ("sha256.tbs-internet.com", 443) |
|---|
| 1806 | n/a | sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem") |
|---|
| 1807 | n/a | with support.transient_internet("sha256.tbs-internet.com"): |
|---|
| 1808 | n/a | ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 1809 | n/a | ctx.verify_mode = ssl.CERT_REQUIRED |
|---|
| 1810 | n/a | ctx.load_verify_locations(sha256_cert) |
|---|
| 1811 | n/a | s = ctx.wrap_socket(socket.socket(socket.AF_INET), |
|---|
| 1812 | n/a | server_hostname="sha256.tbs-internet.com") |
|---|
| 1813 | n/a | try: |
|---|
| 1814 | n/a | s.connect(remote) |
|---|
| 1815 | n/a | if support.verbose: |
|---|
| 1816 | n/a | sys.stdout.write("\nCipher with %r is %r\n" % |
|---|
| 1817 | n/a | (remote, s.cipher())) |
|---|
| 1818 | n/a | sys.stdout.write("Certificate is:\n%s\n" % |
|---|
| 1819 | n/a | pprint.pformat(s.getpeercert())) |
|---|
| 1820 | n/a | finally: |
|---|
| 1821 | n/a | s.close() |
|---|
| 1822 | n/a | |
|---|
| 1823 | n/a | |
|---|
| 1824 | n/a | def _test_get_server_certificate(test, host, port, cert=None): |
|---|
| 1825 | n/a | pem = ssl.get_server_certificate((host, port)) |
|---|
| 1826 | n/a | if not pem: |
|---|
| 1827 | n/a | test.fail("No server certificate on %s:%s!" % (host, port)) |
|---|
| 1828 | n/a | |
|---|
| 1829 | n/a | pem = ssl.get_server_certificate((host, port), ca_certs=cert) |
|---|
| 1830 | n/a | if not pem: |
|---|
| 1831 | n/a | test.fail("No server certificate on %s:%s!" % (host, port)) |
|---|
| 1832 | n/a | if support.verbose: |
|---|
| 1833 | n/a | sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem)) |
|---|
| 1834 | n/a | |
|---|
| 1835 | n/a | def _test_get_server_certificate_fail(test, host, port): |
|---|
| 1836 | n/a | try: |
|---|
| 1837 | n/a | pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE) |
|---|
| 1838 | n/a | except ssl.SSLError as x: |
|---|
| 1839 | n/a | #should fail |
|---|
| 1840 | n/a | if support.verbose: |
|---|
| 1841 | n/a | sys.stdout.write("%s\n" % x) |
|---|
| 1842 | n/a | else: |
|---|
| 1843 | n/a | test.fail("Got server certificate %s for %s:%s!" % (pem, host, port)) |
|---|
| 1844 | n/a | |
|---|
| 1845 | n/a | |
|---|
| 1846 | n/a | if _have_threads: |
|---|
| 1847 | n/a | from test.ssl_servers import make_https_server |
|---|
| 1848 | n/a | |
|---|
| 1849 | n/a | class ThreadedEchoServer(threading.Thread): |
|---|
| 1850 | n/a | |
|---|
| 1851 | n/a | class ConnectionHandler(threading.Thread): |
|---|
| 1852 | n/a | |
|---|
| 1853 | n/a | """A mildly complicated class, because we want it to work both |
|---|
| 1854 | n/a | with and without the SSL wrapper around the socket connection, so |
|---|
| 1855 | n/a | that we can test the STARTTLS functionality.""" |
|---|
| 1856 | n/a | |
|---|
| 1857 | n/a | def __init__(self, server, connsock, addr): |
|---|
| 1858 | n/a | self.server = server |
|---|
| 1859 | n/a | self.running = False |
|---|
| 1860 | n/a | self.sock = connsock |
|---|
| 1861 | n/a | self.addr = addr |
|---|
| 1862 | n/a | self.sock.setblocking(1) |
|---|
| 1863 | n/a | self.sslconn = None |
|---|
| 1864 | n/a | threading.Thread.__init__(self) |
|---|
| 1865 | n/a | self.daemon = True |
|---|
| 1866 | n/a | |
|---|
| 1867 | n/a | def wrap_conn(self): |
|---|
| 1868 | n/a | try: |
|---|
| 1869 | n/a | self.sslconn = self.server.context.wrap_socket( |
|---|
| 1870 | n/a | self.sock, server_side=True) |
|---|
| 1871 | n/a | self.server.selected_npn_protocols.append(self.sslconn.selected_npn_protocol()) |
|---|
| 1872 | n/a | self.server.selected_alpn_protocols.append(self.sslconn.selected_alpn_protocol()) |
|---|
| 1873 | n/a | except (ssl.SSLError, ConnectionResetError) as e: |
|---|
| 1874 | n/a | # We treat ConnectionResetError as though it were an |
|---|
| 1875 | n/a | # SSLError - OpenSSL on Ubuntu abruptly closes the |
|---|
| 1876 | n/a | # connection when asked to use an unsupported protocol. |
|---|
| 1877 | n/a | # |
|---|
| 1878 | n/a | # XXX Various errors can have happened here, for example |
|---|
| 1879 | n/a | # a mismatching protocol version, an invalid certificate, |
|---|
| 1880 | n/a | # or a low-level bug. This should be made more discriminating. |
|---|
| 1881 | n/a | self.server.conn_errors.append(e) |
|---|
| 1882 | n/a | if self.server.chatty: |
|---|
| 1883 | n/a | handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") |
|---|
| 1884 | n/a | self.running = False |
|---|
| 1885 | n/a | self.server.stop() |
|---|
| 1886 | n/a | self.close() |
|---|
| 1887 | n/a | return False |
|---|
| 1888 | n/a | else: |
|---|
| 1889 | n/a | self.server.shared_ciphers.append(self.sslconn.shared_ciphers()) |
|---|
| 1890 | n/a | if self.server.context.verify_mode == ssl.CERT_REQUIRED: |
|---|
| 1891 | n/a | cert = self.sslconn.getpeercert() |
|---|
| 1892 | n/a | if support.verbose and self.server.chatty: |
|---|
| 1893 | n/a | sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") |
|---|
| 1894 | n/a | cert_binary = self.sslconn.getpeercert(True) |
|---|
| 1895 | n/a | if support.verbose and self.server.chatty: |
|---|
| 1896 | n/a | sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") |
|---|
| 1897 | n/a | cipher = self.sslconn.cipher() |
|---|
| 1898 | n/a | if support.verbose and self.server.chatty: |
|---|
| 1899 | n/a | sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") |
|---|
| 1900 | n/a | sys.stdout.write(" server: selected protocol is now " |
|---|
| 1901 | n/a | + str(self.sslconn.selected_npn_protocol()) + "\n") |
|---|
| 1902 | n/a | return True |
|---|
| 1903 | n/a | |
|---|
| 1904 | n/a | def read(self): |
|---|
| 1905 | n/a | if self.sslconn: |
|---|
| 1906 | n/a | return self.sslconn.read() |
|---|
| 1907 | n/a | else: |
|---|
| 1908 | n/a | return self.sock.recv(1024) |
|---|
| 1909 | n/a | |
|---|
| 1910 | n/a | def write(self, bytes): |
|---|
| 1911 | n/a | if self.sslconn: |
|---|
| 1912 | n/a | return self.sslconn.write(bytes) |
|---|
| 1913 | n/a | else: |
|---|
| 1914 | n/a | return self.sock.send(bytes) |
|---|
| 1915 | n/a | |
|---|
| 1916 | n/a | def close(self): |
|---|
| 1917 | n/a | if self.sslconn: |
|---|
| 1918 | n/a | self.sslconn.close() |
|---|
| 1919 | n/a | else: |
|---|
| 1920 | n/a | self.sock.close() |
|---|
| 1921 | n/a | |
|---|
| 1922 | n/a | def run(self): |
|---|
| 1923 | n/a | self.running = True |
|---|
| 1924 | n/a | if not self.server.starttls_server: |
|---|
| 1925 | n/a | if not self.wrap_conn(): |
|---|
| 1926 | n/a | return |
|---|
| 1927 | n/a | while self.running: |
|---|
| 1928 | n/a | try: |
|---|
| 1929 | n/a | msg = self.read() |
|---|
| 1930 | n/a | stripped = msg.strip() |
|---|
| 1931 | n/a | if not stripped: |
|---|
| 1932 | n/a | # eof, so quit this handler |
|---|
| 1933 | n/a | self.running = False |
|---|
| 1934 | n/a | try: |
|---|
| 1935 | n/a | self.sock = self.sslconn.unwrap() |
|---|
| 1936 | n/a | except OSError: |
|---|
| 1937 | n/a | # Many tests shut the TCP connection down |
|---|
| 1938 | n/a | # without an SSL shutdown. This causes |
|---|
| 1939 | n/a | # unwrap() to raise OSError with errno=0! |
|---|
| 1940 | n/a | pass |
|---|
| 1941 | n/a | else: |
|---|
| 1942 | n/a | self.sslconn = None |
|---|
| 1943 | n/a | self.close() |
|---|
| 1944 | n/a | elif stripped == b'over': |
|---|
| 1945 | n/a | if support.verbose and self.server.connectionchatty: |
|---|
| 1946 | n/a | sys.stdout.write(" server: client closed connection\n") |
|---|
| 1947 | n/a | self.close() |
|---|
| 1948 | n/a | return |
|---|
| 1949 | n/a | elif (self.server.starttls_server and |
|---|
| 1950 | n/a | stripped == b'STARTTLS'): |
|---|
| 1951 | n/a | if support.verbose and self.server.connectionchatty: |
|---|
| 1952 | n/a | sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") |
|---|
| 1953 | n/a | self.write(b"OK\n") |
|---|
| 1954 | n/a | if not self.wrap_conn(): |
|---|
| 1955 | n/a | return |
|---|
| 1956 | n/a | elif (self.server.starttls_server and self.sslconn |
|---|
| 1957 | n/a | and stripped == b'ENDTLS'): |
|---|
| 1958 | n/a | if support.verbose and self.server.connectionchatty: |
|---|
| 1959 | n/a | sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") |
|---|
| 1960 | n/a | self.write(b"OK\n") |
|---|
| 1961 | n/a | self.sock = self.sslconn.unwrap() |
|---|
| 1962 | n/a | self.sslconn = None |
|---|
| 1963 | n/a | if support.verbose and self.server.connectionchatty: |
|---|
| 1964 | n/a | sys.stdout.write(" server: connection is now unencrypted...\n") |
|---|
| 1965 | n/a | elif stripped == b'CB tls-unique': |
|---|
| 1966 | n/a | if support.verbose and self.server.connectionchatty: |
|---|
| 1967 | n/a | sys.stdout.write(" server: read CB tls-unique from client, sending our CB data...\n") |
|---|
| 1968 | n/a | data = self.sslconn.get_channel_binding("tls-unique") |
|---|
| 1969 | n/a | self.write(repr(data).encode("us-ascii") + b"\n") |
|---|
| 1970 | n/a | else: |
|---|
| 1971 | n/a | if (support.verbose and |
|---|
| 1972 | n/a | self.server.connectionchatty): |
|---|
| 1973 | n/a | ctype = (self.sslconn and "encrypted") or "unencrypted" |
|---|
| 1974 | n/a | sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" |
|---|
| 1975 | n/a | % (msg, ctype, msg.lower(), ctype)) |
|---|
| 1976 | n/a | self.write(msg.lower()) |
|---|
| 1977 | n/a | except OSError: |
|---|
| 1978 | n/a | if self.server.chatty: |
|---|
| 1979 | n/a | handle_error("Test server failure:\n") |
|---|
| 1980 | n/a | self.close() |
|---|
| 1981 | n/a | self.running = False |
|---|
| 1982 | n/a | # normally, we'd just stop here, but for the test |
|---|
| 1983 | n/a | # harness, we want to stop the server |
|---|
| 1984 | n/a | self.server.stop() |
|---|
| 1985 | n/a | |
|---|
| 1986 | n/a | def __init__(self, certificate=None, ssl_version=None, |
|---|
| 1987 | n/a | certreqs=None, cacerts=None, |
|---|
| 1988 | n/a | chatty=True, connectionchatty=False, starttls_server=False, |
|---|
| 1989 | n/a | npn_protocols=None, alpn_protocols=None, |
|---|
| 1990 | n/a | ciphers=None, context=None): |
|---|
| 1991 | n/a | if context: |
|---|
| 1992 | n/a | self.context = context |
|---|
| 1993 | n/a | else: |
|---|
| 1994 | n/a | self.context = ssl.SSLContext(ssl_version |
|---|
| 1995 | n/a | if ssl_version is not None |
|---|
| 1996 | n/a | else ssl.PROTOCOL_TLSv1) |
|---|
| 1997 | n/a | self.context.verify_mode = (certreqs if certreqs is not None |
|---|
| 1998 | n/a | else ssl.CERT_NONE) |
|---|
| 1999 | n/a | if cacerts: |
|---|
| 2000 | n/a | self.context.load_verify_locations(cacerts) |
|---|
| 2001 | n/a | if certificate: |
|---|
| 2002 | n/a | self.context.load_cert_chain(certificate) |
|---|
| 2003 | n/a | if npn_protocols: |
|---|
| 2004 | n/a | self.context.set_npn_protocols(npn_protocols) |
|---|
| 2005 | n/a | if alpn_protocols: |
|---|
| 2006 | n/a | self.context.set_alpn_protocols(alpn_protocols) |
|---|
| 2007 | n/a | if ciphers: |
|---|
| 2008 | n/a | self.context.set_ciphers(ciphers) |
|---|
| 2009 | n/a | self.chatty = chatty |
|---|
| 2010 | n/a | self.connectionchatty = connectionchatty |
|---|
| 2011 | n/a | self.starttls_server = starttls_server |
|---|
| 2012 | n/a | self.sock = socket.socket() |
|---|
| 2013 | n/a | self.port = support.bind_port(self.sock) |
|---|
| 2014 | n/a | self.flag = None |
|---|
| 2015 | n/a | self.active = False |
|---|
| 2016 | n/a | self.selected_npn_protocols = [] |
|---|
| 2017 | n/a | self.selected_alpn_protocols = [] |
|---|
| 2018 | n/a | self.shared_ciphers = [] |
|---|
| 2019 | n/a | self.conn_errors = [] |
|---|
| 2020 | n/a | threading.Thread.__init__(self) |
|---|
| 2021 | n/a | self.daemon = True |
|---|
| 2022 | n/a | |
|---|
| 2023 | n/a | def __enter__(self): |
|---|
| 2024 | n/a | self.start(threading.Event()) |
|---|
| 2025 | n/a | self.flag.wait() |
|---|
| 2026 | n/a | return self |
|---|
| 2027 | n/a | |
|---|
| 2028 | n/a | def __exit__(self, *args): |
|---|
| 2029 | n/a | self.stop() |
|---|
| 2030 | n/a | self.join() |
|---|
| 2031 | n/a | |
|---|
| 2032 | n/a | def start(self, flag=None): |
|---|
| 2033 | n/a | self.flag = flag |
|---|
| 2034 | n/a | threading.Thread.start(self) |
|---|
| 2035 | n/a | |
|---|
| 2036 | n/a | def run(self): |
|---|
| 2037 | n/a | self.sock.settimeout(0.05) |
|---|
| 2038 | n/a | self.sock.listen() |
|---|
| 2039 | n/a | self.active = True |
|---|
| 2040 | n/a | if self.flag: |
|---|
| 2041 | n/a | # signal an event |
|---|
| 2042 | n/a | self.flag.set() |
|---|
| 2043 | n/a | while self.active: |
|---|
| 2044 | n/a | try: |
|---|
| 2045 | n/a | newconn, connaddr = self.sock.accept() |
|---|
| 2046 | n/a | if support.verbose and self.chatty: |
|---|
| 2047 | n/a | sys.stdout.write(' server: new connection from ' |
|---|
| 2048 | n/a | + repr(connaddr) + '\n') |
|---|
| 2049 | n/a | handler = self.ConnectionHandler(self, newconn, connaddr) |
|---|
| 2050 | n/a | handler.start() |
|---|
| 2051 | n/a | handler.join() |
|---|
| 2052 | n/a | except socket.timeout: |
|---|
| 2053 | n/a | pass |
|---|
| 2054 | n/a | except KeyboardInterrupt: |
|---|
| 2055 | n/a | self.stop() |
|---|
| 2056 | n/a | self.sock.close() |
|---|
| 2057 | n/a | |
|---|
| 2058 | n/a | def stop(self): |
|---|
| 2059 | n/a | self.active = False |
|---|
| 2060 | n/a | |
|---|
| 2061 | n/a | class AsyncoreEchoServer(threading.Thread): |
|---|
| 2062 | n/a | |
|---|
| 2063 | n/a | # this one's based on asyncore.dispatcher |
|---|
| 2064 | n/a | |
|---|
| 2065 | n/a | class EchoServer (asyncore.dispatcher): |
|---|
| 2066 | n/a | |
|---|
| 2067 | n/a | class ConnectionHandler (asyncore.dispatcher_with_send): |
|---|
| 2068 | n/a | |
|---|
| 2069 | n/a | def __init__(self, conn, certfile): |
|---|
| 2070 | n/a | self.socket = test_wrap_socket(conn, server_side=True, |
|---|
| 2071 | n/a | certfile=certfile, |
|---|
| 2072 | n/a | do_handshake_on_connect=False) |
|---|
| 2073 | n/a | asyncore.dispatcher_with_send.__init__(self, self.socket) |
|---|
| 2074 | n/a | self._ssl_accepting = True |
|---|
| 2075 | n/a | self._do_ssl_handshake() |
|---|
| 2076 | n/a | |
|---|
| 2077 | n/a | def readable(self): |
|---|
| 2078 | n/a | if isinstance(self.socket, ssl.SSLSocket): |
|---|
| 2079 | n/a | while self.socket.pending() > 0: |
|---|
| 2080 | n/a | self.handle_read_event() |
|---|
| 2081 | n/a | return True |
|---|
| 2082 | n/a | |
|---|
| 2083 | n/a | def _do_ssl_handshake(self): |
|---|
| 2084 | n/a | try: |
|---|
| 2085 | n/a | self.socket.do_handshake() |
|---|
| 2086 | n/a | except (ssl.SSLWantReadError, ssl.SSLWantWriteError): |
|---|
| 2087 | n/a | return |
|---|
| 2088 | n/a | except ssl.SSLEOFError: |
|---|
| 2089 | n/a | return self.handle_close() |
|---|
| 2090 | n/a | except ssl.SSLError: |
|---|
| 2091 | n/a | raise |
|---|
| 2092 | n/a | except OSError as err: |
|---|
| 2093 | n/a | if err.args[0] == errno.ECONNABORTED: |
|---|
| 2094 | n/a | return self.handle_close() |
|---|
| 2095 | n/a | else: |
|---|
| 2096 | n/a | self._ssl_accepting = False |
|---|
| 2097 | n/a | |
|---|
| 2098 | n/a | def handle_read(self): |
|---|
| 2099 | n/a | if self._ssl_accepting: |
|---|
| 2100 | n/a | self._do_ssl_handshake() |
|---|
| 2101 | n/a | else: |
|---|
| 2102 | n/a | data = self.recv(1024) |
|---|
| 2103 | n/a | if support.verbose: |
|---|
| 2104 | n/a | sys.stdout.write(" server: read %s from client\n" % repr(data)) |
|---|
| 2105 | n/a | if not data: |
|---|
| 2106 | n/a | self.close() |
|---|
| 2107 | n/a | else: |
|---|
| 2108 | n/a | self.send(data.lower()) |
|---|
| 2109 | n/a | |
|---|
| 2110 | n/a | def handle_close(self): |
|---|
| 2111 | n/a | self.close() |
|---|
| 2112 | n/a | if support.verbose: |
|---|
| 2113 | n/a | sys.stdout.write(" server: closed connection %s\n" % self.socket) |
|---|
| 2114 | n/a | |
|---|
| 2115 | n/a | def handle_error(self): |
|---|
| 2116 | n/a | raise |
|---|
| 2117 | n/a | |
|---|
| 2118 | n/a | def __init__(self, certfile): |
|---|
| 2119 | n/a | self.certfile = certfile |
|---|
| 2120 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
|---|
| 2121 | n/a | self.port = support.bind_port(sock, '') |
|---|
| 2122 | n/a | asyncore.dispatcher.__init__(self, sock) |
|---|
| 2123 | n/a | self.listen(5) |
|---|
| 2124 | n/a | |
|---|
| 2125 | n/a | def handle_accepted(self, sock_obj, addr): |
|---|
| 2126 | n/a | if support.verbose: |
|---|
| 2127 | n/a | sys.stdout.write(" server: new connection from %s:%s\n" %addr) |
|---|
| 2128 | n/a | self.ConnectionHandler(sock_obj, self.certfile) |
|---|
| 2129 | n/a | |
|---|
| 2130 | n/a | def handle_error(self): |
|---|
| 2131 | n/a | raise |
|---|
| 2132 | n/a | |
|---|
| 2133 | n/a | def __init__(self, certfile): |
|---|
| 2134 | n/a | self.flag = None |
|---|
| 2135 | n/a | self.active = False |
|---|
| 2136 | n/a | self.server = self.EchoServer(certfile) |
|---|
| 2137 | n/a | self.port = self.server.port |
|---|
| 2138 | n/a | threading.Thread.__init__(self) |
|---|
| 2139 | n/a | self.daemon = True |
|---|
| 2140 | n/a | |
|---|
| 2141 | n/a | def __str__(self): |
|---|
| 2142 | n/a | return "<%s %s>" % (self.__class__.__name__, self.server) |
|---|
| 2143 | n/a | |
|---|
| 2144 | n/a | def __enter__(self): |
|---|
| 2145 | n/a | self.start(threading.Event()) |
|---|
| 2146 | n/a | self.flag.wait() |
|---|
| 2147 | n/a | return self |
|---|
| 2148 | n/a | |
|---|
| 2149 | n/a | def __exit__(self, *args): |
|---|
| 2150 | n/a | if support.verbose: |
|---|
| 2151 | n/a | sys.stdout.write(" cleanup: stopping server.\n") |
|---|
| 2152 | n/a | self.stop() |
|---|
| 2153 | n/a | if support.verbose: |
|---|
| 2154 | n/a | sys.stdout.write(" cleanup: joining server thread.\n") |
|---|
| 2155 | n/a | self.join() |
|---|
| 2156 | n/a | if support.verbose: |
|---|
| 2157 | n/a | sys.stdout.write(" cleanup: successfully joined.\n") |
|---|
| 2158 | n/a | |
|---|
| 2159 | n/a | def start (self, flag=None): |
|---|
| 2160 | n/a | self.flag = flag |
|---|
| 2161 | n/a | threading.Thread.start(self) |
|---|
| 2162 | n/a | |
|---|
| 2163 | n/a | def run(self): |
|---|
| 2164 | n/a | self.active = True |
|---|
| 2165 | n/a | if self.flag: |
|---|
| 2166 | n/a | self.flag.set() |
|---|
| 2167 | n/a | while self.active: |
|---|
| 2168 | n/a | try: |
|---|
| 2169 | n/a | asyncore.loop(1) |
|---|
| 2170 | n/a | except: |
|---|
| 2171 | n/a | pass |
|---|
| 2172 | n/a | |
|---|
| 2173 | n/a | def stop(self): |
|---|
| 2174 | n/a | self.active = False |
|---|
| 2175 | n/a | self.server.close() |
|---|
| 2176 | n/a | |
|---|
| 2177 | n/a | def server_params_test(client_context, server_context, indata=b"FOO\n", |
|---|
| 2178 | n/a | chatty=True, connectionchatty=False, sni_name=None, |
|---|
| 2179 | n/a | session=None): |
|---|
| 2180 | n/a | """ |
|---|
| 2181 | n/a | Launch a server, connect a client to it and try various reads |
|---|
| 2182 | n/a | and writes. |
|---|
| 2183 | n/a | """ |
|---|
| 2184 | n/a | stats = {} |
|---|
| 2185 | n/a | server = ThreadedEchoServer(context=server_context, |
|---|
| 2186 | n/a | chatty=chatty, |
|---|
| 2187 | n/a | connectionchatty=False) |
|---|
| 2188 | n/a | with server: |
|---|
| 2189 | n/a | with client_context.wrap_socket(socket.socket(), |
|---|
| 2190 | n/a | server_hostname=sni_name, session=session) as s: |
|---|
| 2191 | n/a | s.connect((HOST, server.port)) |
|---|
| 2192 | n/a | for arg in [indata, bytearray(indata), memoryview(indata)]: |
|---|
| 2193 | n/a | if connectionchatty: |
|---|
| 2194 | n/a | if support.verbose: |
|---|
| 2195 | n/a | sys.stdout.write( |
|---|
| 2196 | n/a | " client: sending %r...\n" % indata) |
|---|
| 2197 | n/a | s.write(arg) |
|---|
| 2198 | n/a | outdata = s.read() |
|---|
| 2199 | n/a | if connectionchatty: |
|---|
| 2200 | n/a | if support.verbose: |
|---|
| 2201 | n/a | sys.stdout.write(" client: read %r\n" % outdata) |
|---|
| 2202 | n/a | if outdata != indata.lower(): |
|---|
| 2203 | n/a | raise AssertionError( |
|---|
| 2204 | n/a | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
|---|
| 2205 | n/a | % (outdata[:20], len(outdata), |
|---|
| 2206 | n/a | indata[:20].lower(), len(indata))) |
|---|
| 2207 | n/a | s.write(b"over\n") |
|---|
| 2208 | n/a | if connectionchatty: |
|---|
| 2209 | n/a | if support.verbose: |
|---|
| 2210 | n/a | sys.stdout.write(" client: closing connection.\n") |
|---|
| 2211 | n/a | stats.update({ |
|---|
| 2212 | n/a | 'compression': s.compression(), |
|---|
| 2213 | n/a | 'cipher': s.cipher(), |
|---|
| 2214 | n/a | 'peercert': s.getpeercert(), |
|---|
| 2215 | n/a | 'client_alpn_protocol': s.selected_alpn_protocol(), |
|---|
| 2216 | n/a | 'client_npn_protocol': s.selected_npn_protocol(), |
|---|
| 2217 | n/a | 'version': s.version(), |
|---|
| 2218 | n/a | 'session_reused': s.session_reused, |
|---|
| 2219 | n/a | 'session': s.session, |
|---|
| 2220 | n/a | }) |
|---|
| 2221 | n/a | s.close() |
|---|
| 2222 | n/a | stats['server_alpn_protocols'] = server.selected_alpn_protocols |
|---|
| 2223 | n/a | stats['server_npn_protocols'] = server.selected_npn_protocols |
|---|
| 2224 | n/a | stats['server_shared_ciphers'] = server.shared_ciphers |
|---|
| 2225 | n/a | return stats |
|---|
| 2226 | n/a | |
|---|
| 2227 | n/a | def try_protocol_combo(server_protocol, client_protocol, expect_success, |
|---|
| 2228 | n/a | certsreqs=None, server_options=0, client_options=0): |
|---|
| 2229 | n/a | """ |
|---|
| 2230 | n/a | Try to SSL-connect using *client_protocol* to *server_protocol*. |
|---|
| 2231 | n/a | If *expect_success* is true, assert that the connection succeeds, |
|---|
| 2232 | n/a | if it's false, assert that the connection fails. |
|---|
| 2233 | n/a | Also, if *expect_success* is a string, assert that it is the protocol |
|---|
| 2234 | n/a | version actually used by the connection. |
|---|
| 2235 | n/a | """ |
|---|
| 2236 | n/a | if certsreqs is None: |
|---|
| 2237 | n/a | certsreqs = ssl.CERT_NONE |
|---|
| 2238 | n/a | certtype = { |
|---|
| 2239 | n/a | ssl.CERT_NONE: "CERT_NONE", |
|---|
| 2240 | n/a | ssl.CERT_OPTIONAL: "CERT_OPTIONAL", |
|---|
| 2241 | n/a | ssl.CERT_REQUIRED: "CERT_REQUIRED", |
|---|
| 2242 | n/a | }[certsreqs] |
|---|
| 2243 | n/a | if support.verbose: |
|---|
| 2244 | n/a | formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n" |
|---|
| 2245 | n/a | sys.stdout.write(formatstr % |
|---|
| 2246 | n/a | (ssl.get_protocol_name(client_protocol), |
|---|
| 2247 | n/a | ssl.get_protocol_name(server_protocol), |
|---|
| 2248 | n/a | certtype)) |
|---|
| 2249 | n/a | client_context = ssl.SSLContext(client_protocol) |
|---|
| 2250 | n/a | client_context.options |= client_options |
|---|
| 2251 | n/a | server_context = ssl.SSLContext(server_protocol) |
|---|
| 2252 | n/a | server_context.options |= server_options |
|---|
| 2253 | n/a | |
|---|
| 2254 | n/a | # NOTE: we must enable "ALL" ciphers on the client, otherwise an |
|---|
| 2255 | n/a | # SSLv23 client will send an SSLv3 hello (rather than SSLv2) |
|---|
| 2256 | n/a | # starting from OpenSSL 1.0.0 (see issue #8322). |
|---|
| 2257 | n/a | if client_context.protocol == ssl.PROTOCOL_SSLv23: |
|---|
| 2258 | n/a | client_context.set_ciphers("ALL") |
|---|
| 2259 | n/a | |
|---|
| 2260 | n/a | for ctx in (client_context, server_context): |
|---|
| 2261 | n/a | ctx.verify_mode = certsreqs |
|---|
| 2262 | n/a | ctx.load_cert_chain(CERTFILE) |
|---|
| 2263 | n/a | ctx.load_verify_locations(CERTFILE) |
|---|
| 2264 | n/a | try: |
|---|
| 2265 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 2266 | n/a | chatty=False, connectionchatty=False) |
|---|
| 2267 | n/a | # Protocol mismatch can result in either an SSLError, or a |
|---|
| 2268 | n/a | # "Connection reset by peer" error. |
|---|
| 2269 | n/a | except ssl.SSLError: |
|---|
| 2270 | n/a | if expect_success: |
|---|
| 2271 | n/a | raise |
|---|
| 2272 | n/a | except OSError as e: |
|---|
| 2273 | n/a | if expect_success or e.errno != errno.ECONNRESET: |
|---|
| 2274 | n/a | raise |
|---|
| 2275 | n/a | else: |
|---|
| 2276 | n/a | if not expect_success: |
|---|
| 2277 | n/a | raise AssertionError( |
|---|
| 2278 | n/a | "Client protocol %s succeeded with server protocol %s!" |
|---|
| 2279 | n/a | % (ssl.get_protocol_name(client_protocol), |
|---|
| 2280 | n/a | ssl.get_protocol_name(server_protocol))) |
|---|
| 2281 | n/a | elif (expect_success is not True |
|---|
| 2282 | n/a | and expect_success != stats['version']): |
|---|
| 2283 | n/a | raise AssertionError("version mismatch: expected %r, got %r" |
|---|
| 2284 | n/a | % (expect_success, stats['version'])) |
|---|
| 2285 | n/a | |
|---|
| 2286 | n/a | |
|---|
| 2287 | n/a | class ThreadedTests(unittest.TestCase): |
|---|
| 2288 | n/a | |
|---|
| 2289 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2290 | n/a | def test_echo(self): |
|---|
| 2291 | n/a | """Basic test of an SSL client connecting to a server""" |
|---|
| 2292 | n/a | if support.verbose: |
|---|
| 2293 | n/a | sys.stdout.write("\n") |
|---|
| 2294 | n/a | for protocol in PROTOCOLS: |
|---|
| 2295 | n/a | if protocol in {ssl.PROTOCOL_TLS_CLIENT, ssl.PROTOCOL_TLS_SERVER}: |
|---|
| 2296 | n/a | continue |
|---|
| 2297 | n/a | with self.subTest(protocol=ssl._PROTOCOL_NAMES[protocol]): |
|---|
| 2298 | n/a | context = ssl.SSLContext(protocol) |
|---|
| 2299 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 2300 | n/a | server_params_test(context, context, |
|---|
| 2301 | n/a | chatty=True, connectionchatty=True) |
|---|
| 2302 | n/a | |
|---|
| 2303 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
|---|
| 2304 | n/a | client_context.load_verify_locations(SIGNING_CA) |
|---|
| 2305 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
|---|
| 2306 | n/a | # server_context.load_verify_locations(SIGNING_CA) |
|---|
| 2307 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE2) |
|---|
| 2308 | n/a | |
|---|
| 2309 | n/a | with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_SERVER): |
|---|
| 2310 | n/a | server_params_test(client_context=client_context, |
|---|
| 2311 | n/a | server_context=server_context, |
|---|
| 2312 | n/a | chatty=True, connectionchatty=True, |
|---|
| 2313 | n/a | sni_name='fakehostname') |
|---|
| 2314 | n/a | |
|---|
| 2315 | n/a | client_context.check_hostname = False |
|---|
| 2316 | n/a | with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_CLIENT): |
|---|
| 2317 | n/a | with self.assertRaises(ssl.SSLError) as e: |
|---|
| 2318 | n/a | server_params_test(client_context=server_context, |
|---|
| 2319 | n/a | server_context=client_context, |
|---|
| 2320 | n/a | chatty=True, connectionchatty=True, |
|---|
| 2321 | n/a | sni_name='fakehostname') |
|---|
| 2322 | n/a | self.assertIn('called a function you should not call', |
|---|
| 2323 | n/a | str(e.exception)) |
|---|
| 2324 | n/a | |
|---|
| 2325 | n/a | with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_SERVER): |
|---|
| 2326 | n/a | with self.assertRaises(ssl.SSLError) as e: |
|---|
| 2327 | n/a | server_params_test(client_context=server_context, |
|---|
| 2328 | n/a | server_context=server_context, |
|---|
| 2329 | n/a | chatty=True, connectionchatty=True) |
|---|
| 2330 | n/a | self.assertIn('called a function you should not call', |
|---|
| 2331 | n/a | str(e.exception)) |
|---|
| 2332 | n/a | |
|---|
| 2333 | n/a | with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_CLIENT): |
|---|
| 2334 | n/a | with self.assertRaises(ssl.SSLError) as e: |
|---|
| 2335 | n/a | server_params_test(client_context=server_context, |
|---|
| 2336 | n/a | server_context=client_context, |
|---|
| 2337 | n/a | chatty=True, connectionchatty=True) |
|---|
| 2338 | n/a | self.assertIn('called a function you should not call', |
|---|
| 2339 | n/a | str(e.exception)) |
|---|
| 2340 | n/a | |
|---|
| 2341 | n/a | |
|---|
| 2342 | n/a | def test_getpeercert(self): |
|---|
| 2343 | n/a | if support.verbose: |
|---|
| 2344 | n/a | sys.stdout.write("\n") |
|---|
| 2345 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 2346 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 2347 | n/a | context.load_verify_locations(CERTFILE) |
|---|
| 2348 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 2349 | n/a | server = ThreadedEchoServer(context=context, chatty=False) |
|---|
| 2350 | n/a | with server: |
|---|
| 2351 | n/a | s = context.wrap_socket(socket.socket(), |
|---|
| 2352 | n/a | do_handshake_on_connect=False) |
|---|
| 2353 | n/a | s.connect((HOST, server.port)) |
|---|
| 2354 | n/a | # getpeercert() raise ValueError while the handshake isn't |
|---|
| 2355 | n/a | # done. |
|---|
| 2356 | n/a | with self.assertRaises(ValueError): |
|---|
| 2357 | n/a | s.getpeercert() |
|---|
| 2358 | n/a | s.do_handshake() |
|---|
| 2359 | n/a | cert = s.getpeercert() |
|---|
| 2360 | n/a | self.assertTrue(cert, "Can't get peer certificate.") |
|---|
| 2361 | n/a | cipher = s.cipher() |
|---|
| 2362 | n/a | if support.verbose: |
|---|
| 2363 | n/a | sys.stdout.write(pprint.pformat(cert) + '\n') |
|---|
| 2364 | n/a | sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') |
|---|
| 2365 | n/a | if 'subject' not in cert: |
|---|
| 2366 | n/a | self.fail("No subject field in certificate: %s." % |
|---|
| 2367 | n/a | pprint.pformat(cert)) |
|---|
| 2368 | n/a | if ((('organizationName', 'Python Software Foundation'),) |
|---|
| 2369 | n/a | not in cert['subject']): |
|---|
| 2370 | n/a | self.fail( |
|---|
| 2371 | n/a | "Missing or invalid 'organizationName' field in certificate subject; " |
|---|
| 2372 | n/a | "should be 'Python Software Foundation'.") |
|---|
| 2373 | n/a | self.assertIn('notBefore', cert) |
|---|
| 2374 | n/a | self.assertIn('notAfter', cert) |
|---|
| 2375 | n/a | before = ssl.cert_time_to_seconds(cert['notBefore']) |
|---|
| 2376 | n/a | after = ssl.cert_time_to_seconds(cert['notAfter']) |
|---|
| 2377 | n/a | self.assertLess(before, after) |
|---|
| 2378 | n/a | s.close() |
|---|
| 2379 | n/a | |
|---|
| 2380 | n/a | @unittest.skipUnless(have_verify_flags(), |
|---|
| 2381 | n/a | "verify_flags need OpenSSL > 0.9.8") |
|---|
| 2382 | n/a | def test_crl_check(self): |
|---|
| 2383 | n/a | if support.verbose: |
|---|
| 2384 | n/a | sys.stdout.write("\n") |
|---|
| 2385 | n/a | |
|---|
| 2386 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 2387 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE) |
|---|
| 2388 | n/a | |
|---|
| 2389 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 2390 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 2391 | n/a | context.load_verify_locations(SIGNING_CA) |
|---|
| 2392 | n/a | tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) |
|---|
| 2393 | n/a | self.assertEqual(context.verify_flags, ssl.VERIFY_DEFAULT | tf) |
|---|
| 2394 | n/a | |
|---|
| 2395 | n/a | # VERIFY_DEFAULT should pass |
|---|
| 2396 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2397 | n/a | with server: |
|---|
| 2398 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 2399 | n/a | s.connect((HOST, server.port)) |
|---|
| 2400 | n/a | cert = s.getpeercert() |
|---|
| 2401 | n/a | self.assertTrue(cert, "Can't get peer certificate.") |
|---|
| 2402 | n/a | |
|---|
| 2403 | n/a | # VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails |
|---|
| 2404 | n/a | context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF |
|---|
| 2405 | n/a | |
|---|
| 2406 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2407 | n/a | with server: |
|---|
| 2408 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 2409 | n/a | with self.assertRaisesRegex(ssl.SSLError, |
|---|
| 2410 | n/a | "certificate verify failed"): |
|---|
| 2411 | n/a | s.connect((HOST, server.port)) |
|---|
| 2412 | n/a | |
|---|
| 2413 | n/a | # now load a CRL file. The CRL file is signed by the CA. |
|---|
| 2414 | n/a | context.load_verify_locations(CRLFILE) |
|---|
| 2415 | n/a | |
|---|
| 2416 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2417 | n/a | with server: |
|---|
| 2418 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 2419 | n/a | s.connect((HOST, server.port)) |
|---|
| 2420 | n/a | cert = s.getpeercert() |
|---|
| 2421 | n/a | self.assertTrue(cert, "Can't get peer certificate.") |
|---|
| 2422 | n/a | |
|---|
| 2423 | n/a | def test_check_hostname(self): |
|---|
| 2424 | n/a | if support.verbose: |
|---|
| 2425 | n/a | sys.stdout.write("\n") |
|---|
| 2426 | n/a | |
|---|
| 2427 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 2428 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE) |
|---|
| 2429 | n/a | |
|---|
| 2430 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 2431 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 2432 | n/a | context.check_hostname = True |
|---|
| 2433 | n/a | context.load_verify_locations(SIGNING_CA) |
|---|
| 2434 | n/a | |
|---|
| 2435 | n/a | # correct hostname should verify |
|---|
| 2436 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2437 | n/a | with server: |
|---|
| 2438 | n/a | with context.wrap_socket(socket.socket(), |
|---|
| 2439 | n/a | server_hostname="localhost") as s: |
|---|
| 2440 | n/a | s.connect((HOST, server.port)) |
|---|
| 2441 | n/a | cert = s.getpeercert() |
|---|
| 2442 | n/a | self.assertTrue(cert, "Can't get peer certificate.") |
|---|
| 2443 | n/a | |
|---|
| 2444 | n/a | # incorrect hostname should raise an exception |
|---|
| 2445 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2446 | n/a | with server: |
|---|
| 2447 | n/a | with context.wrap_socket(socket.socket(), |
|---|
| 2448 | n/a | server_hostname="invalid") as s: |
|---|
| 2449 | n/a | with self.assertRaisesRegex(ssl.CertificateError, |
|---|
| 2450 | n/a | "hostname 'invalid' doesn't match 'localhost'"): |
|---|
| 2451 | n/a | s.connect((HOST, server.port)) |
|---|
| 2452 | n/a | |
|---|
| 2453 | n/a | # missing server_hostname arg should cause an exception, too |
|---|
| 2454 | n/a | server = ThreadedEchoServer(context=server_context, chatty=True) |
|---|
| 2455 | n/a | with server: |
|---|
| 2456 | n/a | with socket.socket() as s: |
|---|
| 2457 | n/a | with self.assertRaisesRegex(ValueError, |
|---|
| 2458 | n/a | "check_hostname requires server_hostname"): |
|---|
| 2459 | n/a | context.wrap_socket(s) |
|---|
| 2460 | n/a | |
|---|
| 2461 | n/a | def test_wrong_cert(self): |
|---|
| 2462 | n/a | """Connecting when the server rejects the client's certificate |
|---|
| 2463 | n/a | |
|---|
| 2464 | n/a | Launch a server with CERT_REQUIRED, and check that trying to |
|---|
| 2465 | n/a | connect to it with a wrong client certificate fails. |
|---|
| 2466 | n/a | """ |
|---|
| 2467 | n/a | certfile = os.path.join(os.path.dirname(__file__) or os.curdir, |
|---|
| 2468 | n/a | "wrongcert.pem") |
|---|
| 2469 | n/a | server = ThreadedEchoServer(CERTFILE, |
|---|
| 2470 | n/a | certreqs=ssl.CERT_REQUIRED, |
|---|
| 2471 | n/a | cacerts=CERTFILE, chatty=False, |
|---|
| 2472 | n/a | connectionchatty=False) |
|---|
| 2473 | n/a | with server, \ |
|---|
| 2474 | n/a | socket.socket() as sock, \ |
|---|
| 2475 | n/a | test_wrap_socket(sock, |
|---|
| 2476 | n/a | certfile=certfile, |
|---|
| 2477 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) as s: |
|---|
| 2478 | n/a | try: |
|---|
| 2479 | n/a | # Expect either an SSL error about the server rejecting |
|---|
| 2480 | n/a | # the connection, or a low-level connection reset (which |
|---|
| 2481 | n/a | # sometimes happens on Windows) |
|---|
| 2482 | n/a | s.connect((HOST, server.port)) |
|---|
| 2483 | n/a | except ssl.SSLError as e: |
|---|
| 2484 | n/a | if support.verbose: |
|---|
| 2485 | n/a | sys.stdout.write("\nSSLError is %r\n" % e) |
|---|
| 2486 | n/a | except OSError as e: |
|---|
| 2487 | n/a | if e.errno != errno.ECONNRESET: |
|---|
| 2488 | n/a | raise |
|---|
| 2489 | n/a | if support.verbose: |
|---|
| 2490 | n/a | sys.stdout.write("\nsocket.error is %r\n" % e) |
|---|
| 2491 | n/a | else: |
|---|
| 2492 | n/a | self.fail("Use of invalid cert should have failed!") |
|---|
| 2493 | n/a | |
|---|
| 2494 | n/a | def test_rude_shutdown(self): |
|---|
| 2495 | n/a | """A brutal shutdown of an SSL server should raise an OSError |
|---|
| 2496 | n/a | in the client when attempting handshake. |
|---|
| 2497 | n/a | """ |
|---|
| 2498 | n/a | listener_ready = threading.Event() |
|---|
| 2499 | n/a | listener_gone = threading.Event() |
|---|
| 2500 | n/a | |
|---|
| 2501 | n/a | s = socket.socket() |
|---|
| 2502 | n/a | port = support.bind_port(s, HOST) |
|---|
| 2503 | n/a | |
|---|
| 2504 | n/a | # `listener` runs in a thread. It sits in an accept() until |
|---|
| 2505 | n/a | # the main thread connects. Then it rudely closes the socket, |
|---|
| 2506 | n/a | # and sets Event `listener_gone` to let the main thread know |
|---|
| 2507 | n/a | # the socket is gone. |
|---|
| 2508 | n/a | def listener(): |
|---|
| 2509 | n/a | s.listen() |
|---|
| 2510 | n/a | listener_ready.set() |
|---|
| 2511 | n/a | newsock, addr = s.accept() |
|---|
| 2512 | n/a | newsock.close() |
|---|
| 2513 | n/a | s.close() |
|---|
| 2514 | n/a | listener_gone.set() |
|---|
| 2515 | n/a | |
|---|
| 2516 | n/a | def connector(): |
|---|
| 2517 | n/a | listener_ready.wait() |
|---|
| 2518 | n/a | with socket.socket() as c: |
|---|
| 2519 | n/a | c.connect((HOST, port)) |
|---|
| 2520 | n/a | listener_gone.wait() |
|---|
| 2521 | n/a | try: |
|---|
| 2522 | n/a | ssl_sock = test_wrap_socket(c) |
|---|
| 2523 | n/a | except OSError: |
|---|
| 2524 | n/a | pass |
|---|
| 2525 | n/a | else: |
|---|
| 2526 | n/a | self.fail('connecting to closed SSL socket should have failed') |
|---|
| 2527 | n/a | |
|---|
| 2528 | n/a | t = threading.Thread(target=listener) |
|---|
| 2529 | n/a | t.start() |
|---|
| 2530 | n/a | try: |
|---|
| 2531 | n/a | connector() |
|---|
| 2532 | n/a | finally: |
|---|
| 2533 | n/a | t.join() |
|---|
| 2534 | n/a | |
|---|
| 2535 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2536 | n/a | @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv2'), |
|---|
| 2537 | n/a | "OpenSSL is compiled without SSLv2 support") |
|---|
| 2538 | n/a | def test_protocol_sslv2(self): |
|---|
| 2539 | n/a | """Connecting to an SSLv2 server with various client options""" |
|---|
| 2540 | n/a | if support.verbose: |
|---|
| 2541 | n/a | sys.stdout.write("\n") |
|---|
| 2542 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) |
|---|
| 2543 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) |
|---|
| 2544 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) |
|---|
| 2545 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False) |
|---|
| 2546 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2547 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) |
|---|
| 2548 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) |
|---|
| 2549 | n/a | # SSLv23 client with specific SSL options |
|---|
| 2550 | n/a | if no_sslv2_implies_sslv3_hello(): |
|---|
| 2551 | n/a | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
|---|
| 2552 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2553 | n/a | client_options=ssl.OP_NO_SSLv2) |
|---|
| 2554 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2555 | n/a | client_options=ssl.OP_NO_SSLv3) |
|---|
| 2556 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2557 | n/a | client_options=ssl.OP_NO_TLSv1) |
|---|
| 2558 | n/a | |
|---|
| 2559 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2560 | n/a | def test_protocol_sslv23(self): |
|---|
| 2561 | n/a | """Connecting to an SSLv23 server with various client options""" |
|---|
| 2562 | n/a | if support.verbose: |
|---|
| 2563 | n/a | sys.stdout.write("\n") |
|---|
| 2564 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 2565 | n/a | try: |
|---|
| 2566 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) |
|---|
| 2567 | n/a | except OSError as x: |
|---|
| 2568 | n/a | # this fails on some older versions of OpenSSL (0.9.7l, for instance) |
|---|
| 2569 | n/a | if support.verbose: |
|---|
| 2570 | n/a | sys.stdout.write( |
|---|
| 2571 | n/a | " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" |
|---|
| 2572 | n/a | % str(x)) |
|---|
| 2573 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2574 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False) |
|---|
| 2575 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) |
|---|
| 2576 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1') |
|---|
| 2577 | n/a | |
|---|
| 2578 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2579 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL) |
|---|
| 2580 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) |
|---|
| 2581 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) |
|---|
| 2582 | n/a | |
|---|
| 2583 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2584 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED) |
|---|
| 2585 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) |
|---|
| 2586 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) |
|---|
| 2587 | n/a | |
|---|
| 2588 | n/a | # Server with specific SSL options |
|---|
| 2589 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2590 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, False, |
|---|
| 2591 | n/a | server_options=ssl.OP_NO_SSLv3) |
|---|
| 2592 | n/a | # Will choose TLSv1 |
|---|
| 2593 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, |
|---|
| 2594 | n/a | server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
|---|
| 2595 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, False, |
|---|
| 2596 | n/a | server_options=ssl.OP_NO_TLSv1) |
|---|
| 2597 | n/a | |
|---|
| 2598 | n/a | |
|---|
| 2599 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2600 | n/a | @unittest.skipUnless(hasattr(ssl, 'PROTOCOL_SSLv3'), |
|---|
| 2601 | n/a | "OpenSSL is compiled without SSLv3 support") |
|---|
| 2602 | n/a | def test_protocol_sslv3(self): |
|---|
| 2603 | n/a | """Connecting to an SSLv3 server with various client options""" |
|---|
| 2604 | n/a | if support.verbose: |
|---|
| 2605 | n/a | sys.stdout.write("\n") |
|---|
| 2606 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3') |
|---|
| 2607 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL) |
|---|
| 2608 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED) |
|---|
| 2609 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 2610 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) |
|---|
| 2611 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2612 | n/a | client_options=ssl.OP_NO_SSLv3) |
|---|
| 2613 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) |
|---|
| 2614 | n/a | if no_sslv2_implies_sslv3_hello(): |
|---|
| 2615 | n/a | # No SSLv2 => client will use an SSLv3 hello on recent OpenSSLs |
|---|
| 2616 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, |
|---|
| 2617 | n/a | False, client_options=ssl.OP_NO_SSLv2) |
|---|
| 2618 | n/a | |
|---|
| 2619 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2620 | n/a | def test_protocol_tlsv1(self): |
|---|
| 2621 | n/a | """Connecting to a TLSv1 server with various client options""" |
|---|
| 2622 | n/a | if support.verbose: |
|---|
| 2623 | n/a | sys.stdout.write("\n") |
|---|
| 2624 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1') |
|---|
| 2625 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) |
|---|
| 2626 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) |
|---|
| 2627 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 2628 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) |
|---|
| 2629 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2630 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) |
|---|
| 2631 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2632 | n/a | client_options=ssl.OP_NO_TLSv1) |
|---|
| 2633 | n/a | |
|---|
| 2634 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2635 | n/a | @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_1"), |
|---|
| 2636 | n/a | "TLS version 1.1 not supported.") |
|---|
| 2637 | n/a | def test_protocol_tlsv1_1(self): |
|---|
| 2638 | n/a | """Connecting to a TLSv1.1 server with various client options. |
|---|
| 2639 | n/a | Testing against older TLS versions.""" |
|---|
| 2640 | n/a | if support.verbose: |
|---|
| 2641 | n/a | sys.stdout.write("\n") |
|---|
| 2642 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') |
|---|
| 2643 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 2644 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv2, False) |
|---|
| 2645 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2646 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False) |
|---|
| 2647 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2648 | n/a | client_options=ssl.OP_NO_TLSv1_1) |
|---|
| 2649 | n/a | |
|---|
| 2650 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') |
|---|
| 2651 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1, False) |
|---|
| 2652 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_1, False) |
|---|
| 2653 | n/a | |
|---|
| 2654 | n/a | |
|---|
| 2655 | n/a | @skip_if_broken_ubuntu_ssl |
|---|
| 2656 | n/a | @unittest.skipUnless(hasattr(ssl, "PROTOCOL_TLSv1_2"), |
|---|
| 2657 | n/a | "TLS version 1.2 not supported.") |
|---|
| 2658 | n/a | def test_protocol_tlsv1_2(self): |
|---|
| 2659 | n/a | """Connecting to a TLSv1.2 server with various client options. |
|---|
| 2660 | n/a | Testing against older TLS versions.""" |
|---|
| 2661 | n/a | if support.verbose: |
|---|
| 2662 | n/a | sys.stdout.write("\n") |
|---|
| 2663 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2', |
|---|
| 2664 | n/a | server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2, |
|---|
| 2665 | n/a | client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,) |
|---|
| 2666 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv2'): |
|---|
| 2667 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv2, False) |
|---|
| 2668 | n/a | if hasattr(ssl, 'PROTOCOL_SSLv3'): |
|---|
| 2669 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False) |
|---|
| 2670 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv23, False, |
|---|
| 2671 | n/a | client_options=ssl.OP_NO_TLSv1_2) |
|---|
| 2672 | n/a | |
|---|
| 2673 | n/a | try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2') |
|---|
| 2674 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False) |
|---|
| 2675 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False) |
|---|
| 2676 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False) |
|---|
| 2677 | n/a | try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) |
|---|
| 2678 | n/a | |
|---|
| 2679 | n/a | def test_starttls(self): |
|---|
| 2680 | n/a | """Switching from clear text to encrypted and back again.""" |
|---|
| 2681 | n/a | msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6") |
|---|
| 2682 | n/a | |
|---|
| 2683 | n/a | server = ThreadedEchoServer(CERTFILE, |
|---|
| 2684 | n/a | ssl_version=ssl.PROTOCOL_TLSv1, |
|---|
| 2685 | n/a | starttls_server=True, |
|---|
| 2686 | n/a | chatty=True, |
|---|
| 2687 | n/a | connectionchatty=True) |
|---|
| 2688 | n/a | wrapped = False |
|---|
| 2689 | n/a | with server: |
|---|
| 2690 | n/a | s = socket.socket() |
|---|
| 2691 | n/a | s.setblocking(1) |
|---|
| 2692 | n/a | s.connect((HOST, server.port)) |
|---|
| 2693 | n/a | if support.verbose: |
|---|
| 2694 | n/a | sys.stdout.write("\n") |
|---|
| 2695 | n/a | for indata in msgs: |
|---|
| 2696 | n/a | if support.verbose: |
|---|
| 2697 | n/a | sys.stdout.write( |
|---|
| 2698 | n/a | " client: sending %r...\n" % indata) |
|---|
| 2699 | n/a | if wrapped: |
|---|
| 2700 | n/a | conn.write(indata) |
|---|
| 2701 | n/a | outdata = conn.read() |
|---|
| 2702 | n/a | else: |
|---|
| 2703 | n/a | s.send(indata) |
|---|
| 2704 | n/a | outdata = s.recv(1024) |
|---|
| 2705 | n/a | msg = outdata.strip().lower() |
|---|
| 2706 | n/a | if indata == b"STARTTLS" and msg.startswith(b"ok"): |
|---|
| 2707 | n/a | # STARTTLS ok, switch to secure mode |
|---|
| 2708 | n/a | if support.verbose: |
|---|
| 2709 | n/a | sys.stdout.write( |
|---|
| 2710 | n/a | " client: read %r from server, starting TLS...\n" |
|---|
| 2711 | n/a | % msg) |
|---|
| 2712 | n/a | conn = test_wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 2713 | n/a | wrapped = True |
|---|
| 2714 | n/a | elif indata == b"ENDTLS" and msg.startswith(b"ok"): |
|---|
| 2715 | n/a | # ENDTLS ok, switch back to clear text |
|---|
| 2716 | n/a | if support.verbose: |
|---|
| 2717 | n/a | sys.stdout.write( |
|---|
| 2718 | n/a | " client: read %r from server, ending TLS...\n" |
|---|
| 2719 | n/a | % msg) |
|---|
| 2720 | n/a | s = conn.unwrap() |
|---|
| 2721 | n/a | wrapped = False |
|---|
| 2722 | n/a | else: |
|---|
| 2723 | n/a | if support.verbose: |
|---|
| 2724 | n/a | sys.stdout.write( |
|---|
| 2725 | n/a | " client: read %r from server\n" % msg) |
|---|
| 2726 | n/a | if support.verbose: |
|---|
| 2727 | n/a | sys.stdout.write(" client: closing connection.\n") |
|---|
| 2728 | n/a | if wrapped: |
|---|
| 2729 | n/a | conn.write(b"over\n") |
|---|
| 2730 | n/a | else: |
|---|
| 2731 | n/a | s.send(b"over\n") |
|---|
| 2732 | n/a | if wrapped: |
|---|
| 2733 | n/a | conn.close() |
|---|
| 2734 | n/a | else: |
|---|
| 2735 | n/a | s.close() |
|---|
| 2736 | n/a | |
|---|
| 2737 | n/a | def test_socketserver(self): |
|---|
| 2738 | n/a | """Using socketserver to create and manage SSL connections.""" |
|---|
| 2739 | n/a | server = make_https_server(self, certfile=CERTFILE) |
|---|
| 2740 | n/a | # try to connect |
|---|
| 2741 | n/a | if support.verbose: |
|---|
| 2742 | n/a | sys.stdout.write('\n') |
|---|
| 2743 | n/a | with open(CERTFILE, 'rb') as f: |
|---|
| 2744 | n/a | d1 = f.read() |
|---|
| 2745 | n/a | d2 = '' |
|---|
| 2746 | n/a | # now fetch the same data from the HTTPS server |
|---|
| 2747 | n/a | url = 'https://localhost:%d/%s' % ( |
|---|
| 2748 | n/a | server.port, os.path.split(CERTFILE)[1]) |
|---|
| 2749 | n/a | context = ssl.create_default_context(cafile=CERTFILE) |
|---|
| 2750 | n/a | f = urllib.request.urlopen(url, context=context) |
|---|
| 2751 | n/a | try: |
|---|
| 2752 | n/a | dlen = f.info().get("content-length") |
|---|
| 2753 | n/a | if dlen and (int(dlen) > 0): |
|---|
| 2754 | n/a | d2 = f.read(int(dlen)) |
|---|
| 2755 | n/a | if support.verbose: |
|---|
| 2756 | n/a | sys.stdout.write( |
|---|
| 2757 | n/a | " client: read %d bytes from remote server '%s'\n" |
|---|
| 2758 | n/a | % (len(d2), server)) |
|---|
| 2759 | n/a | finally: |
|---|
| 2760 | n/a | f.close() |
|---|
| 2761 | n/a | self.assertEqual(d1, d2) |
|---|
| 2762 | n/a | |
|---|
| 2763 | n/a | def test_asyncore_server(self): |
|---|
| 2764 | n/a | """Check the example asyncore integration.""" |
|---|
| 2765 | n/a | if support.verbose: |
|---|
| 2766 | n/a | sys.stdout.write("\n") |
|---|
| 2767 | n/a | |
|---|
| 2768 | n/a | indata = b"FOO\n" |
|---|
| 2769 | n/a | server = AsyncoreEchoServer(CERTFILE) |
|---|
| 2770 | n/a | with server: |
|---|
| 2771 | n/a | s = test_wrap_socket(socket.socket()) |
|---|
| 2772 | n/a | s.connect(('127.0.0.1', server.port)) |
|---|
| 2773 | n/a | if support.verbose: |
|---|
| 2774 | n/a | sys.stdout.write( |
|---|
| 2775 | n/a | " client: sending %r...\n" % indata) |
|---|
| 2776 | n/a | s.write(indata) |
|---|
| 2777 | n/a | outdata = s.read() |
|---|
| 2778 | n/a | if support.verbose: |
|---|
| 2779 | n/a | sys.stdout.write(" client: read %r\n" % outdata) |
|---|
| 2780 | n/a | if outdata != indata.lower(): |
|---|
| 2781 | n/a | self.fail( |
|---|
| 2782 | n/a | "bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
|---|
| 2783 | n/a | % (outdata[:20], len(outdata), |
|---|
| 2784 | n/a | indata[:20].lower(), len(indata))) |
|---|
| 2785 | n/a | s.write(b"over\n") |
|---|
| 2786 | n/a | if support.verbose: |
|---|
| 2787 | n/a | sys.stdout.write(" client: closing connection.\n") |
|---|
| 2788 | n/a | s.close() |
|---|
| 2789 | n/a | if support.verbose: |
|---|
| 2790 | n/a | sys.stdout.write(" client: connection closed.\n") |
|---|
| 2791 | n/a | |
|---|
| 2792 | n/a | def test_recv_send(self): |
|---|
| 2793 | n/a | """Test recv(), send() and friends.""" |
|---|
| 2794 | n/a | if support.verbose: |
|---|
| 2795 | n/a | sys.stdout.write("\n") |
|---|
| 2796 | n/a | |
|---|
| 2797 | n/a | server = ThreadedEchoServer(CERTFILE, |
|---|
| 2798 | n/a | certreqs=ssl.CERT_NONE, |
|---|
| 2799 | n/a | ssl_version=ssl.PROTOCOL_TLSv1, |
|---|
| 2800 | n/a | cacerts=CERTFILE, |
|---|
| 2801 | n/a | chatty=True, |
|---|
| 2802 | n/a | connectionchatty=False) |
|---|
| 2803 | n/a | with server: |
|---|
| 2804 | n/a | s = test_wrap_socket(socket.socket(), |
|---|
| 2805 | n/a | server_side=False, |
|---|
| 2806 | n/a | certfile=CERTFILE, |
|---|
| 2807 | n/a | ca_certs=CERTFILE, |
|---|
| 2808 | n/a | cert_reqs=ssl.CERT_NONE, |
|---|
| 2809 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 2810 | n/a | s.connect((HOST, server.port)) |
|---|
| 2811 | n/a | # helper methods for standardising recv* method signatures |
|---|
| 2812 | n/a | def _recv_into(): |
|---|
| 2813 | n/a | b = bytearray(b"\0"*100) |
|---|
| 2814 | n/a | count = s.recv_into(b) |
|---|
| 2815 | n/a | return b[:count] |
|---|
| 2816 | n/a | |
|---|
| 2817 | n/a | def _recvfrom_into(): |
|---|
| 2818 | n/a | b = bytearray(b"\0"*100) |
|---|
| 2819 | n/a | count, addr = s.recvfrom_into(b) |
|---|
| 2820 | n/a | return b[:count] |
|---|
| 2821 | n/a | |
|---|
| 2822 | n/a | # (name, method, expect success?, *args, return value func) |
|---|
| 2823 | n/a | send_methods = [ |
|---|
| 2824 | n/a | ('send', s.send, True, [], len), |
|---|
| 2825 | n/a | ('sendto', s.sendto, False, ["some.address"], len), |
|---|
| 2826 | n/a | ('sendall', s.sendall, True, [], lambda x: None), |
|---|
| 2827 | n/a | ] |
|---|
| 2828 | n/a | # (name, method, whether to expect success, *args) |
|---|
| 2829 | n/a | recv_methods = [ |
|---|
| 2830 | n/a | ('recv', s.recv, True, []), |
|---|
| 2831 | n/a | ('recvfrom', s.recvfrom, False, ["some.address"]), |
|---|
| 2832 | n/a | ('recv_into', _recv_into, True, []), |
|---|
| 2833 | n/a | ('recvfrom_into', _recvfrom_into, False, []), |
|---|
| 2834 | n/a | ] |
|---|
| 2835 | n/a | data_prefix = "PREFIX_" |
|---|
| 2836 | n/a | |
|---|
| 2837 | n/a | for (meth_name, send_meth, expect_success, args, |
|---|
| 2838 | n/a | ret_val_meth) in send_methods: |
|---|
| 2839 | n/a | indata = (data_prefix + meth_name).encode('ascii') |
|---|
| 2840 | n/a | try: |
|---|
| 2841 | n/a | ret = send_meth(indata, *args) |
|---|
| 2842 | n/a | msg = "sending with {}".format(meth_name) |
|---|
| 2843 | n/a | self.assertEqual(ret, ret_val_meth(indata), msg=msg) |
|---|
| 2844 | n/a | outdata = s.read() |
|---|
| 2845 | n/a | if outdata != indata.lower(): |
|---|
| 2846 | n/a | self.fail( |
|---|
| 2847 | n/a | "While sending with <<{name:s}>> bad data " |
|---|
| 2848 | n/a | "<<{outdata:r}>> ({nout:d}) received; " |
|---|
| 2849 | n/a | "expected <<{indata:r}>> ({nin:d})\n".format( |
|---|
| 2850 | n/a | name=meth_name, outdata=outdata[:20], |
|---|
| 2851 | n/a | nout=len(outdata), |
|---|
| 2852 | n/a | indata=indata[:20], nin=len(indata) |
|---|
| 2853 | n/a | ) |
|---|
| 2854 | n/a | ) |
|---|
| 2855 | n/a | except ValueError as e: |
|---|
| 2856 | n/a | if expect_success: |
|---|
| 2857 | n/a | self.fail( |
|---|
| 2858 | n/a | "Failed to send with method <<{name:s}>>; " |
|---|
| 2859 | n/a | "expected to succeed.\n".format(name=meth_name) |
|---|
| 2860 | n/a | ) |
|---|
| 2861 | n/a | if not str(e).startswith(meth_name): |
|---|
| 2862 | n/a | self.fail( |
|---|
| 2863 | n/a | "Method <<{name:s}>> failed with unexpected " |
|---|
| 2864 | n/a | "exception message: {exp:s}\n".format( |
|---|
| 2865 | n/a | name=meth_name, exp=e |
|---|
| 2866 | n/a | ) |
|---|
| 2867 | n/a | ) |
|---|
| 2868 | n/a | |
|---|
| 2869 | n/a | for meth_name, recv_meth, expect_success, args in recv_methods: |
|---|
| 2870 | n/a | indata = (data_prefix + meth_name).encode('ascii') |
|---|
| 2871 | n/a | try: |
|---|
| 2872 | n/a | s.send(indata) |
|---|
| 2873 | n/a | outdata = recv_meth(*args) |
|---|
| 2874 | n/a | if outdata != indata.lower(): |
|---|
| 2875 | n/a | self.fail( |
|---|
| 2876 | n/a | "While receiving with <<{name:s}>> bad data " |
|---|
| 2877 | n/a | "<<{outdata:r}>> ({nout:d}) received; " |
|---|
| 2878 | n/a | "expected <<{indata:r}>> ({nin:d})\n".format( |
|---|
| 2879 | n/a | name=meth_name, outdata=outdata[:20], |
|---|
| 2880 | n/a | nout=len(outdata), |
|---|
| 2881 | n/a | indata=indata[:20], nin=len(indata) |
|---|
| 2882 | n/a | ) |
|---|
| 2883 | n/a | ) |
|---|
| 2884 | n/a | except ValueError as e: |
|---|
| 2885 | n/a | if expect_success: |
|---|
| 2886 | n/a | self.fail( |
|---|
| 2887 | n/a | "Failed to receive with method <<{name:s}>>; " |
|---|
| 2888 | n/a | "expected to succeed.\n".format(name=meth_name) |
|---|
| 2889 | n/a | ) |
|---|
| 2890 | n/a | if not str(e).startswith(meth_name): |
|---|
| 2891 | n/a | self.fail( |
|---|
| 2892 | n/a | "Method <<{name:s}>> failed with unexpected " |
|---|
| 2893 | n/a | "exception message: {exp:s}\n".format( |
|---|
| 2894 | n/a | name=meth_name, exp=e |
|---|
| 2895 | n/a | ) |
|---|
| 2896 | n/a | ) |
|---|
| 2897 | n/a | # consume data |
|---|
| 2898 | n/a | s.read() |
|---|
| 2899 | n/a | |
|---|
| 2900 | n/a | # read(-1, buffer) is supported, even though read(-1) is not |
|---|
| 2901 | n/a | data = b"data" |
|---|
| 2902 | n/a | s.send(data) |
|---|
| 2903 | n/a | buffer = bytearray(len(data)) |
|---|
| 2904 | n/a | self.assertEqual(s.read(-1, buffer), len(data)) |
|---|
| 2905 | n/a | self.assertEqual(buffer, data) |
|---|
| 2906 | n/a | |
|---|
| 2907 | n/a | # Make sure sendmsg et al are disallowed to avoid |
|---|
| 2908 | n/a | # inadvertent disclosure of data and/or corruption |
|---|
| 2909 | n/a | # of the encrypted data stream |
|---|
| 2910 | n/a | self.assertRaises(NotImplementedError, s.sendmsg, [b"data"]) |
|---|
| 2911 | n/a | self.assertRaises(NotImplementedError, s.recvmsg, 100) |
|---|
| 2912 | n/a | self.assertRaises(NotImplementedError, |
|---|
| 2913 | n/a | s.recvmsg_into, bytearray(100)) |
|---|
| 2914 | n/a | |
|---|
| 2915 | n/a | s.write(b"over\n") |
|---|
| 2916 | n/a | |
|---|
| 2917 | n/a | self.assertRaises(ValueError, s.recv, -1) |
|---|
| 2918 | n/a | self.assertRaises(ValueError, s.read, -1) |
|---|
| 2919 | n/a | |
|---|
| 2920 | n/a | s.close() |
|---|
| 2921 | n/a | |
|---|
| 2922 | n/a | def test_recv_zero(self): |
|---|
| 2923 | n/a | server = ThreadedEchoServer(CERTFILE) |
|---|
| 2924 | n/a | server.__enter__() |
|---|
| 2925 | n/a | self.addCleanup(server.__exit__, None, None) |
|---|
| 2926 | n/a | s = socket.create_connection((HOST, server.port)) |
|---|
| 2927 | n/a | self.addCleanup(s.close) |
|---|
| 2928 | n/a | s = test_wrap_socket(s, suppress_ragged_eofs=False) |
|---|
| 2929 | n/a | self.addCleanup(s.close) |
|---|
| 2930 | n/a | |
|---|
| 2931 | n/a | # recv/read(0) should return no data |
|---|
| 2932 | n/a | s.send(b"data") |
|---|
| 2933 | n/a | self.assertEqual(s.recv(0), b"") |
|---|
| 2934 | n/a | self.assertEqual(s.read(0), b"") |
|---|
| 2935 | n/a | self.assertEqual(s.read(), b"data") |
|---|
| 2936 | n/a | |
|---|
| 2937 | n/a | # Should not block if the other end sends no data |
|---|
| 2938 | n/a | s.setblocking(False) |
|---|
| 2939 | n/a | self.assertEqual(s.recv(0), b"") |
|---|
| 2940 | n/a | self.assertEqual(s.recv_into(bytearray()), 0) |
|---|
| 2941 | n/a | |
|---|
| 2942 | n/a | def test_nonblocking_send(self): |
|---|
| 2943 | n/a | server = ThreadedEchoServer(CERTFILE, |
|---|
| 2944 | n/a | certreqs=ssl.CERT_NONE, |
|---|
| 2945 | n/a | ssl_version=ssl.PROTOCOL_TLSv1, |
|---|
| 2946 | n/a | cacerts=CERTFILE, |
|---|
| 2947 | n/a | chatty=True, |
|---|
| 2948 | n/a | connectionchatty=False) |
|---|
| 2949 | n/a | with server: |
|---|
| 2950 | n/a | s = test_wrap_socket(socket.socket(), |
|---|
| 2951 | n/a | server_side=False, |
|---|
| 2952 | n/a | certfile=CERTFILE, |
|---|
| 2953 | n/a | ca_certs=CERTFILE, |
|---|
| 2954 | n/a | cert_reqs=ssl.CERT_NONE, |
|---|
| 2955 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 2956 | n/a | s.connect((HOST, server.port)) |
|---|
| 2957 | n/a | s.setblocking(False) |
|---|
| 2958 | n/a | |
|---|
| 2959 | n/a | # If we keep sending data, at some point the buffers |
|---|
| 2960 | n/a | # will be full and the call will block |
|---|
| 2961 | n/a | buf = bytearray(8192) |
|---|
| 2962 | n/a | def fill_buffer(): |
|---|
| 2963 | n/a | while True: |
|---|
| 2964 | n/a | s.send(buf) |
|---|
| 2965 | n/a | self.assertRaises((ssl.SSLWantWriteError, |
|---|
| 2966 | n/a | ssl.SSLWantReadError), fill_buffer) |
|---|
| 2967 | n/a | |
|---|
| 2968 | n/a | # Now read all the output and discard it |
|---|
| 2969 | n/a | s.setblocking(True) |
|---|
| 2970 | n/a | s.close() |
|---|
| 2971 | n/a | |
|---|
| 2972 | n/a | def test_handshake_timeout(self): |
|---|
| 2973 | n/a | # Issue #5103: SSL handshake must respect the socket timeout |
|---|
| 2974 | n/a | server = socket.socket(socket.AF_INET) |
|---|
| 2975 | n/a | host = "127.0.0.1" |
|---|
| 2976 | n/a | port = support.bind_port(server) |
|---|
| 2977 | n/a | started = threading.Event() |
|---|
| 2978 | n/a | finish = False |
|---|
| 2979 | n/a | |
|---|
| 2980 | n/a | def serve(): |
|---|
| 2981 | n/a | server.listen() |
|---|
| 2982 | n/a | started.set() |
|---|
| 2983 | n/a | conns = [] |
|---|
| 2984 | n/a | while not finish: |
|---|
| 2985 | n/a | r, w, e = select.select([server], [], [], 0.1) |
|---|
| 2986 | n/a | if server in r: |
|---|
| 2987 | n/a | # Let the socket hang around rather than having |
|---|
| 2988 | n/a | # it closed by garbage collection. |
|---|
| 2989 | n/a | conns.append(server.accept()[0]) |
|---|
| 2990 | n/a | for sock in conns: |
|---|
| 2991 | n/a | sock.close() |
|---|
| 2992 | n/a | |
|---|
| 2993 | n/a | t = threading.Thread(target=serve) |
|---|
| 2994 | n/a | t.start() |
|---|
| 2995 | n/a | started.wait() |
|---|
| 2996 | n/a | |
|---|
| 2997 | n/a | try: |
|---|
| 2998 | n/a | try: |
|---|
| 2999 | n/a | c = socket.socket(socket.AF_INET) |
|---|
| 3000 | n/a | c.settimeout(0.2) |
|---|
| 3001 | n/a | c.connect((host, port)) |
|---|
| 3002 | n/a | # Will attempt handshake and time out |
|---|
| 3003 | n/a | self.assertRaisesRegex(socket.timeout, "timed out", |
|---|
| 3004 | n/a | test_wrap_socket, c) |
|---|
| 3005 | n/a | finally: |
|---|
| 3006 | n/a | c.close() |
|---|
| 3007 | n/a | try: |
|---|
| 3008 | n/a | c = socket.socket(socket.AF_INET) |
|---|
| 3009 | n/a | c = test_wrap_socket(c) |
|---|
| 3010 | n/a | c.settimeout(0.2) |
|---|
| 3011 | n/a | # Will attempt handshake and time out |
|---|
| 3012 | n/a | self.assertRaisesRegex(socket.timeout, "timed out", |
|---|
| 3013 | n/a | c.connect, (host, port)) |
|---|
| 3014 | n/a | finally: |
|---|
| 3015 | n/a | c.close() |
|---|
| 3016 | n/a | finally: |
|---|
| 3017 | n/a | finish = True |
|---|
| 3018 | n/a | t.join() |
|---|
| 3019 | n/a | server.close() |
|---|
| 3020 | n/a | |
|---|
| 3021 | n/a | def test_server_accept(self): |
|---|
| 3022 | n/a | # Issue #16357: accept() on a SSLSocket created through |
|---|
| 3023 | n/a | # SSLContext.wrap_socket(). |
|---|
| 3024 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3025 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3026 | n/a | context.load_verify_locations(CERTFILE) |
|---|
| 3027 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3028 | n/a | server = socket.socket(socket.AF_INET) |
|---|
| 3029 | n/a | host = "127.0.0.1" |
|---|
| 3030 | n/a | port = support.bind_port(server) |
|---|
| 3031 | n/a | server = context.wrap_socket(server, server_side=True) |
|---|
| 3032 | n/a | self.assertTrue(server.server_side) |
|---|
| 3033 | n/a | |
|---|
| 3034 | n/a | evt = threading.Event() |
|---|
| 3035 | n/a | remote = None |
|---|
| 3036 | n/a | peer = None |
|---|
| 3037 | n/a | def serve(): |
|---|
| 3038 | n/a | nonlocal remote, peer |
|---|
| 3039 | n/a | server.listen() |
|---|
| 3040 | n/a | # Block on the accept and wait on the connection to close. |
|---|
| 3041 | n/a | evt.set() |
|---|
| 3042 | n/a | remote, peer = server.accept() |
|---|
| 3043 | n/a | remote.recv(1) |
|---|
| 3044 | n/a | |
|---|
| 3045 | n/a | t = threading.Thread(target=serve) |
|---|
| 3046 | n/a | t.start() |
|---|
| 3047 | n/a | # Client wait until server setup and perform a connect. |
|---|
| 3048 | n/a | evt.wait() |
|---|
| 3049 | n/a | client = context.wrap_socket(socket.socket()) |
|---|
| 3050 | n/a | client.connect((host, port)) |
|---|
| 3051 | n/a | client_addr = client.getsockname() |
|---|
| 3052 | n/a | client.close() |
|---|
| 3053 | n/a | t.join() |
|---|
| 3054 | n/a | remote.close() |
|---|
| 3055 | n/a | server.close() |
|---|
| 3056 | n/a | # Sanity checks. |
|---|
| 3057 | n/a | self.assertIsInstance(remote, ssl.SSLSocket) |
|---|
| 3058 | n/a | self.assertEqual(peer, client_addr) |
|---|
| 3059 | n/a | |
|---|
| 3060 | n/a | def test_getpeercert_enotconn(self): |
|---|
| 3061 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3062 | n/a | with context.wrap_socket(socket.socket()) as sock: |
|---|
| 3063 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 3064 | n/a | sock.getpeercert() |
|---|
| 3065 | n/a | self.assertEqual(cm.exception.errno, errno.ENOTCONN) |
|---|
| 3066 | n/a | |
|---|
| 3067 | n/a | def test_do_handshake_enotconn(self): |
|---|
| 3068 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3069 | n/a | with context.wrap_socket(socket.socket()) as sock: |
|---|
| 3070 | n/a | with self.assertRaises(OSError) as cm: |
|---|
| 3071 | n/a | sock.do_handshake() |
|---|
| 3072 | n/a | self.assertEqual(cm.exception.errno, errno.ENOTCONN) |
|---|
| 3073 | n/a | |
|---|
| 3074 | n/a | def test_default_ciphers(self): |
|---|
| 3075 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3076 | n/a | try: |
|---|
| 3077 | n/a | # Force a set of weak ciphers on our client context |
|---|
| 3078 | n/a | context.set_ciphers("DES") |
|---|
| 3079 | n/a | except ssl.SSLError: |
|---|
| 3080 | n/a | self.skipTest("no DES cipher available") |
|---|
| 3081 | n/a | with ThreadedEchoServer(CERTFILE, |
|---|
| 3082 | n/a | ssl_version=ssl.PROTOCOL_SSLv23, |
|---|
| 3083 | n/a | chatty=False) as server: |
|---|
| 3084 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3085 | n/a | with self.assertRaises(OSError): |
|---|
| 3086 | n/a | s.connect((HOST, server.port)) |
|---|
| 3087 | n/a | self.assertIn("no shared cipher", str(server.conn_errors[0])) |
|---|
| 3088 | n/a | |
|---|
| 3089 | n/a | def test_version_basic(self): |
|---|
| 3090 | n/a | """ |
|---|
| 3091 | n/a | Basic tests for SSLSocket.version(). |
|---|
| 3092 | n/a | More tests are done in the test_protocol_*() methods. |
|---|
| 3093 | n/a | """ |
|---|
| 3094 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3095 | n/a | with ThreadedEchoServer(CERTFILE, |
|---|
| 3096 | n/a | ssl_version=ssl.PROTOCOL_TLSv1, |
|---|
| 3097 | n/a | chatty=False) as server: |
|---|
| 3098 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3099 | n/a | self.assertIs(s.version(), None) |
|---|
| 3100 | n/a | s.connect((HOST, server.port)) |
|---|
| 3101 | n/a | self.assertEqual(s.version(), 'TLSv1') |
|---|
| 3102 | n/a | self.assertIs(s.version(), None) |
|---|
| 3103 | n/a | |
|---|
| 3104 | n/a | @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL") |
|---|
| 3105 | n/a | def test_default_ecdh_curve(self): |
|---|
| 3106 | n/a | # Issue #21015: elliptic curve-based Diffie Hellman key exchange |
|---|
| 3107 | n/a | # should be enabled by default on SSL contexts. |
|---|
| 3108 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3109 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3110 | n/a | # Prior to OpenSSL 1.0.0, ECDH ciphers have to be enabled |
|---|
| 3111 | n/a | # explicitly using the 'ECCdraft' cipher alias. Otherwise, |
|---|
| 3112 | n/a | # our default cipher list should prefer ECDH-based ciphers |
|---|
| 3113 | n/a | # automatically. |
|---|
| 3114 | n/a | if ssl.OPENSSL_VERSION_INFO < (1, 0, 0): |
|---|
| 3115 | n/a | context.set_ciphers("ECCdraft:ECDH") |
|---|
| 3116 | n/a | with ThreadedEchoServer(context=context) as server: |
|---|
| 3117 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3118 | n/a | s.connect((HOST, server.port)) |
|---|
| 3119 | n/a | self.assertIn("ECDH", s.cipher()[0]) |
|---|
| 3120 | n/a | |
|---|
| 3121 | n/a | @unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, |
|---|
| 3122 | n/a | "'tls-unique' channel binding not available") |
|---|
| 3123 | n/a | def test_tls_unique_channel_binding(self): |
|---|
| 3124 | n/a | """Test tls-unique channel binding.""" |
|---|
| 3125 | n/a | if support.verbose: |
|---|
| 3126 | n/a | sys.stdout.write("\n") |
|---|
| 3127 | n/a | |
|---|
| 3128 | n/a | server = ThreadedEchoServer(CERTFILE, |
|---|
| 3129 | n/a | certreqs=ssl.CERT_NONE, |
|---|
| 3130 | n/a | ssl_version=ssl.PROTOCOL_TLSv1, |
|---|
| 3131 | n/a | cacerts=CERTFILE, |
|---|
| 3132 | n/a | chatty=True, |
|---|
| 3133 | n/a | connectionchatty=False) |
|---|
| 3134 | n/a | with server: |
|---|
| 3135 | n/a | s = test_wrap_socket(socket.socket(), |
|---|
| 3136 | n/a | server_side=False, |
|---|
| 3137 | n/a | certfile=CERTFILE, |
|---|
| 3138 | n/a | ca_certs=CERTFILE, |
|---|
| 3139 | n/a | cert_reqs=ssl.CERT_NONE, |
|---|
| 3140 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 3141 | n/a | s.connect((HOST, server.port)) |
|---|
| 3142 | n/a | # get the data |
|---|
| 3143 | n/a | cb_data = s.get_channel_binding("tls-unique") |
|---|
| 3144 | n/a | if support.verbose: |
|---|
| 3145 | n/a | sys.stdout.write(" got channel binding data: {0!r}\n" |
|---|
| 3146 | n/a | .format(cb_data)) |
|---|
| 3147 | n/a | |
|---|
| 3148 | n/a | # check if it is sane |
|---|
| 3149 | n/a | self.assertIsNotNone(cb_data) |
|---|
| 3150 | n/a | self.assertEqual(len(cb_data), 12) # True for TLSv1 |
|---|
| 3151 | n/a | |
|---|
| 3152 | n/a | # and compare with the peers version |
|---|
| 3153 | n/a | s.write(b"CB tls-unique\n") |
|---|
| 3154 | n/a | peer_data_repr = s.read().strip() |
|---|
| 3155 | n/a | self.assertEqual(peer_data_repr, |
|---|
| 3156 | n/a | repr(cb_data).encode("us-ascii")) |
|---|
| 3157 | n/a | s.close() |
|---|
| 3158 | n/a | |
|---|
| 3159 | n/a | # now, again |
|---|
| 3160 | n/a | s = test_wrap_socket(socket.socket(), |
|---|
| 3161 | n/a | server_side=False, |
|---|
| 3162 | n/a | certfile=CERTFILE, |
|---|
| 3163 | n/a | ca_certs=CERTFILE, |
|---|
| 3164 | n/a | cert_reqs=ssl.CERT_NONE, |
|---|
| 3165 | n/a | ssl_version=ssl.PROTOCOL_TLSv1) |
|---|
| 3166 | n/a | s.connect((HOST, server.port)) |
|---|
| 3167 | n/a | new_cb_data = s.get_channel_binding("tls-unique") |
|---|
| 3168 | n/a | if support.verbose: |
|---|
| 3169 | n/a | sys.stdout.write(" got another channel binding data: {0!r}\n" |
|---|
| 3170 | n/a | .format(new_cb_data)) |
|---|
| 3171 | n/a | # is it really unique |
|---|
| 3172 | n/a | self.assertNotEqual(cb_data, new_cb_data) |
|---|
| 3173 | n/a | self.assertIsNotNone(cb_data) |
|---|
| 3174 | n/a | self.assertEqual(len(cb_data), 12) # True for TLSv1 |
|---|
| 3175 | n/a | s.write(b"CB tls-unique\n") |
|---|
| 3176 | n/a | peer_data_repr = s.read().strip() |
|---|
| 3177 | n/a | self.assertEqual(peer_data_repr, |
|---|
| 3178 | n/a | repr(new_cb_data).encode("us-ascii")) |
|---|
| 3179 | n/a | s.close() |
|---|
| 3180 | n/a | |
|---|
| 3181 | n/a | def test_compression(self): |
|---|
| 3182 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3183 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3184 | n/a | stats = server_params_test(context, context, |
|---|
| 3185 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3186 | n/a | if support.verbose: |
|---|
| 3187 | n/a | sys.stdout.write(" got compression: {!r}\n".format(stats['compression'])) |
|---|
| 3188 | n/a | self.assertIn(stats['compression'], { None, 'ZLIB', 'RLE' }) |
|---|
| 3189 | n/a | |
|---|
| 3190 | n/a | @unittest.skipUnless(hasattr(ssl, 'OP_NO_COMPRESSION'), |
|---|
| 3191 | n/a | "ssl.OP_NO_COMPRESSION needed for this test") |
|---|
| 3192 | n/a | def test_compression_disabled(self): |
|---|
| 3193 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3194 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3195 | n/a | context.options |= ssl.OP_NO_COMPRESSION |
|---|
| 3196 | n/a | stats = server_params_test(context, context, |
|---|
| 3197 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3198 | n/a | self.assertIs(stats['compression'], None) |
|---|
| 3199 | n/a | |
|---|
| 3200 | n/a | def test_dh_params(self): |
|---|
| 3201 | n/a | # Check we can get a connection with ephemeral Diffie-Hellman |
|---|
| 3202 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3203 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3204 | n/a | context.load_dh_params(DHFILE) |
|---|
| 3205 | n/a | context.set_ciphers("kEDH") |
|---|
| 3206 | n/a | stats = server_params_test(context, context, |
|---|
| 3207 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3208 | n/a | cipher = stats["cipher"][0] |
|---|
| 3209 | n/a | parts = cipher.split("-") |
|---|
| 3210 | n/a | if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts: |
|---|
| 3211 | n/a | self.fail("Non-DH cipher: " + cipher[0]) |
|---|
| 3212 | n/a | |
|---|
| 3213 | n/a | def test_selected_alpn_protocol(self): |
|---|
| 3214 | n/a | # selected_alpn_protocol() is None unless ALPN is used. |
|---|
| 3215 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3216 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3217 | n/a | stats = server_params_test(context, context, |
|---|
| 3218 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3219 | n/a | self.assertIs(stats['client_alpn_protocol'], None) |
|---|
| 3220 | n/a | |
|---|
| 3221 | n/a | @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required") |
|---|
| 3222 | n/a | def test_selected_alpn_protocol_if_server_uses_alpn(self): |
|---|
| 3223 | n/a | # selected_alpn_protocol() is None unless ALPN is used by the client. |
|---|
| 3224 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3225 | n/a | client_context.load_verify_locations(CERTFILE) |
|---|
| 3226 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3227 | n/a | server_context.load_cert_chain(CERTFILE) |
|---|
| 3228 | n/a | server_context.set_alpn_protocols(['foo', 'bar']) |
|---|
| 3229 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3230 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3231 | n/a | self.assertIs(stats['client_alpn_protocol'], None) |
|---|
| 3232 | n/a | |
|---|
| 3233 | n/a | @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test") |
|---|
| 3234 | n/a | def test_alpn_protocols(self): |
|---|
| 3235 | n/a | server_protocols = ['foo', 'bar', 'milkshake'] |
|---|
| 3236 | n/a | protocol_tests = [ |
|---|
| 3237 | n/a | (['foo', 'bar'], 'foo'), |
|---|
| 3238 | n/a | (['bar', 'foo'], 'foo'), |
|---|
| 3239 | n/a | (['milkshake'], 'milkshake'), |
|---|
| 3240 | n/a | (['http/3.0', 'http/4.0'], None) |
|---|
| 3241 | n/a | ] |
|---|
| 3242 | n/a | for client_protocols, expected in protocol_tests: |
|---|
| 3243 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) |
|---|
| 3244 | n/a | server_context.load_cert_chain(CERTFILE) |
|---|
| 3245 | n/a | server_context.set_alpn_protocols(server_protocols) |
|---|
| 3246 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) |
|---|
| 3247 | n/a | client_context.load_cert_chain(CERTFILE) |
|---|
| 3248 | n/a | client_context.set_alpn_protocols(client_protocols) |
|---|
| 3249 | n/a | |
|---|
| 3250 | n/a | try: |
|---|
| 3251 | n/a | stats = server_params_test(client_context, |
|---|
| 3252 | n/a | server_context, |
|---|
| 3253 | n/a | chatty=True, |
|---|
| 3254 | n/a | connectionchatty=True) |
|---|
| 3255 | n/a | except ssl.SSLError as e: |
|---|
| 3256 | n/a | stats = e |
|---|
| 3257 | n/a | |
|---|
| 3258 | n/a | if expected is None and IS_OPENSSL_1_1: |
|---|
| 3259 | n/a | # OpenSSL 1.1.0 raises handshake error |
|---|
| 3260 | n/a | self.assertIsInstance(stats, ssl.SSLError) |
|---|
| 3261 | n/a | else: |
|---|
| 3262 | n/a | msg = "failed trying %s (s) and %s (c).\n" \ |
|---|
| 3263 | n/a | "was expecting %s, but got %%s from the %%s" \ |
|---|
| 3264 | n/a | % (str(server_protocols), str(client_protocols), |
|---|
| 3265 | n/a | str(expected)) |
|---|
| 3266 | n/a | client_result = stats['client_alpn_protocol'] |
|---|
| 3267 | n/a | self.assertEqual(client_result, expected, |
|---|
| 3268 | n/a | msg % (client_result, "client")) |
|---|
| 3269 | n/a | server_result = stats['server_alpn_protocols'][-1] \ |
|---|
| 3270 | n/a | if len(stats['server_alpn_protocols']) else 'nothing' |
|---|
| 3271 | n/a | self.assertEqual(server_result, expected, |
|---|
| 3272 | n/a | msg % (server_result, "server")) |
|---|
| 3273 | n/a | |
|---|
| 3274 | n/a | def test_selected_npn_protocol(self): |
|---|
| 3275 | n/a | # selected_npn_protocol() is None unless NPN is used |
|---|
| 3276 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3277 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3278 | n/a | stats = server_params_test(context, context, |
|---|
| 3279 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3280 | n/a | self.assertIs(stats['client_npn_protocol'], None) |
|---|
| 3281 | n/a | |
|---|
| 3282 | n/a | @unittest.skipUnless(ssl.HAS_NPN, "NPN support needed for this test") |
|---|
| 3283 | n/a | def test_npn_protocols(self): |
|---|
| 3284 | n/a | server_protocols = ['http/1.1', 'spdy/2'] |
|---|
| 3285 | n/a | protocol_tests = [ |
|---|
| 3286 | n/a | (['http/1.1', 'spdy/2'], 'http/1.1'), |
|---|
| 3287 | n/a | (['spdy/2', 'http/1.1'], 'http/1.1'), |
|---|
| 3288 | n/a | (['spdy/2', 'test'], 'spdy/2'), |
|---|
| 3289 | n/a | (['abc', 'def'], 'abc') |
|---|
| 3290 | n/a | ] |
|---|
| 3291 | n/a | for client_protocols, expected in protocol_tests: |
|---|
| 3292 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3293 | n/a | server_context.load_cert_chain(CERTFILE) |
|---|
| 3294 | n/a | server_context.set_npn_protocols(server_protocols) |
|---|
| 3295 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3296 | n/a | client_context.load_cert_chain(CERTFILE) |
|---|
| 3297 | n/a | client_context.set_npn_protocols(client_protocols) |
|---|
| 3298 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3299 | n/a | chatty=True, connectionchatty=True) |
|---|
| 3300 | n/a | |
|---|
| 3301 | n/a | msg = "failed trying %s (s) and %s (c).\n" \ |
|---|
| 3302 | n/a | "was expecting %s, but got %%s from the %%s" \ |
|---|
| 3303 | n/a | % (str(server_protocols), str(client_protocols), |
|---|
| 3304 | n/a | str(expected)) |
|---|
| 3305 | n/a | client_result = stats['client_npn_protocol'] |
|---|
| 3306 | n/a | self.assertEqual(client_result, expected, msg % (client_result, "client")) |
|---|
| 3307 | n/a | server_result = stats['server_npn_protocols'][-1] \ |
|---|
| 3308 | n/a | if len(stats['server_npn_protocols']) else 'nothing' |
|---|
| 3309 | n/a | self.assertEqual(server_result, expected, msg % (server_result, "server")) |
|---|
| 3310 | n/a | |
|---|
| 3311 | n/a | def sni_contexts(self): |
|---|
| 3312 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3313 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE) |
|---|
| 3314 | n/a | other_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3315 | n/a | other_context.load_cert_chain(SIGNED_CERTFILE2) |
|---|
| 3316 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3317 | n/a | client_context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3318 | n/a | client_context.load_verify_locations(SIGNING_CA) |
|---|
| 3319 | n/a | return server_context, other_context, client_context |
|---|
| 3320 | n/a | |
|---|
| 3321 | n/a | def check_common_name(self, stats, name): |
|---|
| 3322 | n/a | cert = stats['peercert'] |
|---|
| 3323 | n/a | self.assertIn((('commonName', name),), cert['subject']) |
|---|
| 3324 | n/a | |
|---|
| 3325 | n/a | @needs_sni |
|---|
| 3326 | n/a | def test_sni_callback(self): |
|---|
| 3327 | n/a | calls = [] |
|---|
| 3328 | n/a | server_context, other_context, client_context = self.sni_contexts() |
|---|
| 3329 | n/a | |
|---|
| 3330 | n/a | def servername_cb(ssl_sock, server_name, initial_context): |
|---|
| 3331 | n/a | calls.append((server_name, initial_context)) |
|---|
| 3332 | n/a | if server_name is not None: |
|---|
| 3333 | n/a | ssl_sock.context = other_context |
|---|
| 3334 | n/a | server_context.set_servername_callback(servername_cb) |
|---|
| 3335 | n/a | |
|---|
| 3336 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3337 | n/a | chatty=True, |
|---|
| 3338 | n/a | sni_name='supermessage') |
|---|
| 3339 | n/a | # The hostname was fetched properly, and the certificate was |
|---|
| 3340 | n/a | # changed for the connection. |
|---|
| 3341 | n/a | self.assertEqual(calls, [("supermessage", server_context)]) |
|---|
| 3342 | n/a | # CERTFILE4 was selected |
|---|
| 3343 | n/a | self.check_common_name(stats, 'fakehostname') |
|---|
| 3344 | n/a | |
|---|
| 3345 | n/a | calls = [] |
|---|
| 3346 | n/a | # The callback is called with server_name=None |
|---|
| 3347 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3348 | n/a | chatty=True, |
|---|
| 3349 | n/a | sni_name=None) |
|---|
| 3350 | n/a | self.assertEqual(calls, [(None, server_context)]) |
|---|
| 3351 | n/a | self.check_common_name(stats, 'localhost') |
|---|
| 3352 | n/a | |
|---|
| 3353 | n/a | # Check disabling the callback |
|---|
| 3354 | n/a | calls = [] |
|---|
| 3355 | n/a | server_context.set_servername_callback(None) |
|---|
| 3356 | n/a | |
|---|
| 3357 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3358 | n/a | chatty=True, |
|---|
| 3359 | n/a | sni_name='notfunny') |
|---|
| 3360 | n/a | # Certificate didn't change |
|---|
| 3361 | n/a | self.check_common_name(stats, 'localhost') |
|---|
| 3362 | n/a | self.assertEqual(calls, []) |
|---|
| 3363 | n/a | |
|---|
| 3364 | n/a | @needs_sni |
|---|
| 3365 | n/a | def test_sni_callback_alert(self): |
|---|
| 3366 | n/a | # Returning a TLS alert is reflected to the connecting client |
|---|
| 3367 | n/a | server_context, other_context, client_context = self.sni_contexts() |
|---|
| 3368 | n/a | |
|---|
| 3369 | n/a | def cb_returning_alert(ssl_sock, server_name, initial_context): |
|---|
| 3370 | n/a | return ssl.ALERT_DESCRIPTION_ACCESS_DENIED |
|---|
| 3371 | n/a | server_context.set_servername_callback(cb_returning_alert) |
|---|
| 3372 | n/a | |
|---|
| 3373 | n/a | with self.assertRaises(ssl.SSLError) as cm: |
|---|
| 3374 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3375 | n/a | chatty=False, |
|---|
| 3376 | n/a | sni_name='supermessage') |
|---|
| 3377 | n/a | self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_ACCESS_DENIED') |
|---|
| 3378 | n/a | |
|---|
| 3379 | n/a | @needs_sni |
|---|
| 3380 | n/a | def test_sni_callback_raising(self): |
|---|
| 3381 | n/a | # Raising fails the connection with a TLS handshake failure alert. |
|---|
| 3382 | n/a | server_context, other_context, client_context = self.sni_contexts() |
|---|
| 3383 | n/a | |
|---|
| 3384 | n/a | def cb_raising(ssl_sock, server_name, initial_context): |
|---|
| 3385 | n/a | 1/0 |
|---|
| 3386 | n/a | server_context.set_servername_callback(cb_raising) |
|---|
| 3387 | n/a | |
|---|
| 3388 | n/a | with self.assertRaises(ssl.SSLError) as cm, \ |
|---|
| 3389 | n/a | support.captured_stderr() as stderr: |
|---|
| 3390 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3391 | n/a | chatty=False, |
|---|
| 3392 | n/a | sni_name='supermessage') |
|---|
| 3393 | n/a | self.assertEqual(cm.exception.reason, 'SSLV3_ALERT_HANDSHAKE_FAILURE') |
|---|
| 3394 | n/a | self.assertIn("ZeroDivisionError", stderr.getvalue()) |
|---|
| 3395 | n/a | |
|---|
| 3396 | n/a | @needs_sni |
|---|
| 3397 | n/a | def test_sni_callback_wrong_return_type(self): |
|---|
| 3398 | n/a | # Returning the wrong return type terminates the TLS connection |
|---|
| 3399 | n/a | # with an internal error alert. |
|---|
| 3400 | n/a | server_context, other_context, client_context = self.sni_contexts() |
|---|
| 3401 | n/a | |
|---|
| 3402 | n/a | def cb_wrong_return_type(ssl_sock, server_name, initial_context): |
|---|
| 3403 | n/a | return "foo" |
|---|
| 3404 | n/a | server_context.set_servername_callback(cb_wrong_return_type) |
|---|
| 3405 | n/a | |
|---|
| 3406 | n/a | with self.assertRaises(ssl.SSLError) as cm, \ |
|---|
| 3407 | n/a | support.captured_stderr() as stderr: |
|---|
| 3408 | n/a | stats = server_params_test(client_context, server_context, |
|---|
| 3409 | n/a | chatty=False, |
|---|
| 3410 | n/a | sni_name='supermessage') |
|---|
| 3411 | n/a | self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR') |
|---|
| 3412 | n/a | self.assertIn("TypeError", stderr.getvalue()) |
|---|
| 3413 | n/a | |
|---|
| 3414 | n/a | def test_shared_ciphers(self): |
|---|
| 3415 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3416 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE) |
|---|
| 3417 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3418 | n/a | client_context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3419 | n/a | client_context.load_verify_locations(SIGNING_CA) |
|---|
| 3420 | n/a | if ssl.OPENSSL_VERSION_INFO >= (1, 0, 2): |
|---|
| 3421 | n/a | client_context.set_ciphers("AES128:AES256") |
|---|
| 3422 | n/a | server_context.set_ciphers("AES256") |
|---|
| 3423 | n/a | alg1 = "AES256" |
|---|
| 3424 | n/a | alg2 = "AES-256" |
|---|
| 3425 | n/a | else: |
|---|
| 3426 | n/a | client_context.set_ciphers("AES:3DES") |
|---|
| 3427 | n/a | server_context.set_ciphers("3DES") |
|---|
| 3428 | n/a | alg1 = "3DES" |
|---|
| 3429 | n/a | alg2 = "DES-CBC3" |
|---|
| 3430 | n/a | |
|---|
| 3431 | n/a | stats = server_params_test(client_context, server_context) |
|---|
| 3432 | n/a | ciphers = stats['server_shared_ciphers'][0] |
|---|
| 3433 | n/a | self.assertGreater(len(ciphers), 0) |
|---|
| 3434 | n/a | for name, tls_version, bits in ciphers: |
|---|
| 3435 | n/a | if not alg1 in name.split("-") and alg2 not in name: |
|---|
| 3436 | n/a | self.fail(name) |
|---|
| 3437 | n/a | |
|---|
| 3438 | n/a | def test_read_write_after_close_raises_valuerror(self): |
|---|
| 3439 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3440 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3441 | n/a | context.load_verify_locations(CERTFILE) |
|---|
| 3442 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3443 | n/a | server = ThreadedEchoServer(context=context, chatty=False) |
|---|
| 3444 | n/a | |
|---|
| 3445 | n/a | with server: |
|---|
| 3446 | n/a | s = context.wrap_socket(socket.socket()) |
|---|
| 3447 | n/a | s.connect((HOST, server.port)) |
|---|
| 3448 | n/a | s.close() |
|---|
| 3449 | n/a | |
|---|
| 3450 | n/a | self.assertRaises(ValueError, s.read, 1024) |
|---|
| 3451 | n/a | self.assertRaises(ValueError, s.write, b'hello') |
|---|
| 3452 | n/a | |
|---|
| 3453 | n/a | def test_sendfile(self): |
|---|
| 3454 | n/a | TEST_DATA = b"x" * 512 |
|---|
| 3455 | n/a | with open(support.TESTFN, 'wb') as f: |
|---|
| 3456 | n/a | f.write(TEST_DATA) |
|---|
| 3457 | n/a | self.addCleanup(support.unlink, support.TESTFN) |
|---|
| 3458 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3459 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3460 | n/a | context.load_verify_locations(CERTFILE) |
|---|
| 3461 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3462 | n/a | server = ThreadedEchoServer(context=context, chatty=False) |
|---|
| 3463 | n/a | with server: |
|---|
| 3464 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3465 | n/a | s.connect((HOST, server.port)) |
|---|
| 3466 | n/a | with open(support.TESTFN, 'rb') as file: |
|---|
| 3467 | n/a | s.sendfile(file) |
|---|
| 3468 | n/a | self.assertEqual(s.recv(1024), TEST_DATA) |
|---|
| 3469 | n/a | |
|---|
| 3470 | n/a | def test_session(self): |
|---|
| 3471 | n/a | server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3472 | n/a | server_context.load_cert_chain(SIGNED_CERTFILE) |
|---|
| 3473 | n/a | client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
|---|
| 3474 | n/a | client_context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3475 | n/a | client_context.load_verify_locations(SIGNING_CA) |
|---|
| 3476 | n/a | |
|---|
| 3477 | n/a | # first connection without session |
|---|
| 3478 | n/a | stats = server_params_test(client_context, server_context) |
|---|
| 3479 | n/a | session = stats['session'] |
|---|
| 3480 | n/a | self.assertTrue(session.id) |
|---|
| 3481 | n/a | self.assertGreater(session.time, 0) |
|---|
| 3482 | n/a | self.assertGreater(session.timeout, 0) |
|---|
| 3483 | n/a | self.assertTrue(session.has_ticket) |
|---|
| 3484 | n/a | if ssl.OPENSSL_VERSION_INFO > (1, 0, 1): |
|---|
| 3485 | n/a | self.assertGreater(session.ticket_lifetime_hint, 0) |
|---|
| 3486 | n/a | self.assertFalse(stats['session_reused']) |
|---|
| 3487 | n/a | sess_stat = server_context.session_stats() |
|---|
| 3488 | n/a | self.assertEqual(sess_stat['accept'], 1) |
|---|
| 3489 | n/a | self.assertEqual(sess_stat['hits'], 0) |
|---|
| 3490 | n/a | |
|---|
| 3491 | n/a | # reuse session |
|---|
| 3492 | n/a | stats = server_params_test(client_context, server_context, session=session) |
|---|
| 3493 | n/a | sess_stat = server_context.session_stats() |
|---|
| 3494 | n/a | self.assertEqual(sess_stat['accept'], 2) |
|---|
| 3495 | n/a | self.assertEqual(sess_stat['hits'], 1) |
|---|
| 3496 | n/a | self.assertTrue(stats['session_reused']) |
|---|
| 3497 | n/a | session2 = stats['session'] |
|---|
| 3498 | n/a | self.assertEqual(session2.id, session.id) |
|---|
| 3499 | n/a | self.assertEqual(session2, session) |
|---|
| 3500 | n/a | self.assertIsNot(session2, session) |
|---|
| 3501 | n/a | self.assertGreaterEqual(session2.time, session.time) |
|---|
| 3502 | n/a | self.assertGreaterEqual(session2.timeout, session.timeout) |
|---|
| 3503 | n/a | |
|---|
| 3504 | n/a | # another one without session |
|---|
| 3505 | n/a | stats = server_params_test(client_context, server_context) |
|---|
| 3506 | n/a | self.assertFalse(stats['session_reused']) |
|---|
| 3507 | n/a | session3 = stats['session'] |
|---|
| 3508 | n/a | self.assertNotEqual(session3.id, session.id) |
|---|
| 3509 | n/a | self.assertNotEqual(session3, session) |
|---|
| 3510 | n/a | sess_stat = server_context.session_stats() |
|---|
| 3511 | n/a | self.assertEqual(sess_stat['accept'], 3) |
|---|
| 3512 | n/a | self.assertEqual(sess_stat['hits'], 1) |
|---|
| 3513 | n/a | |
|---|
| 3514 | n/a | # reuse session again |
|---|
| 3515 | n/a | stats = server_params_test(client_context, server_context, session=session) |
|---|
| 3516 | n/a | self.assertTrue(stats['session_reused']) |
|---|
| 3517 | n/a | session4 = stats['session'] |
|---|
| 3518 | n/a | self.assertEqual(session4.id, session.id) |
|---|
| 3519 | n/a | self.assertEqual(session4, session) |
|---|
| 3520 | n/a | self.assertGreaterEqual(session4.time, session.time) |
|---|
| 3521 | n/a | self.assertGreaterEqual(session4.timeout, session.timeout) |
|---|
| 3522 | n/a | sess_stat = server_context.session_stats() |
|---|
| 3523 | n/a | self.assertEqual(sess_stat['accept'], 4) |
|---|
| 3524 | n/a | self.assertEqual(sess_stat['hits'], 2) |
|---|
| 3525 | n/a | |
|---|
| 3526 | n/a | def test_session_handling(self): |
|---|
| 3527 | n/a | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3528 | n/a | context.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3529 | n/a | context.load_verify_locations(CERTFILE) |
|---|
| 3530 | n/a | context.load_cert_chain(CERTFILE) |
|---|
| 3531 | n/a | |
|---|
| 3532 | n/a | context2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
|---|
| 3533 | n/a | context2.verify_mode = ssl.CERT_REQUIRED |
|---|
| 3534 | n/a | context2.load_verify_locations(CERTFILE) |
|---|
| 3535 | n/a | context2.load_cert_chain(CERTFILE) |
|---|
| 3536 | n/a | |
|---|
| 3537 | n/a | server = ThreadedEchoServer(context=context, chatty=False) |
|---|
| 3538 | n/a | with server: |
|---|
| 3539 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3540 | n/a | # session is None before handshake |
|---|
| 3541 | n/a | self.assertEqual(s.session, None) |
|---|
| 3542 | n/a | self.assertEqual(s.session_reused, None) |
|---|
| 3543 | n/a | s.connect((HOST, server.port)) |
|---|
| 3544 | n/a | session = s.session |
|---|
| 3545 | n/a | self.assertTrue(session) |
|---|
| 3546 | n/a | with self.assertRaises(TypeError) as e: |
|---|
| 3547 | n/a | s.session = object |
|---|
| 3548 | n/a | self.assertEqual(str(e.exception), 'Value is not a SSLSession.') |
|---|
| 3549 | n/a | |
|---|
| 3550 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3551 | n/a | s.connect((HOST, server.port)) |
|---|
| 3552 | n/a | # cannot set session after handshake |
|---|
| 3553 | n/a | with self.assertRaises(ValueError) as e: |
|---|
| 3554 | n/a | s.session = session |
|---|
| 3555 | n/a | self.assertEqual(str(e.exception), |
|---|
| 3556 | n/a | 'Cannot set session after handshake.') |
|---|
| 3557 | n/a | |
|---|
| 3558 | n/a | with context.wrap_socket(socket.socket()) as s: |
|---|
| 3559 | n/a | # can set session before handshake and before the |
|---|
| 3560 | n/a | # connection was established |
|---|
| 3561 | n/a | s.session = session |
|---|
| 3562 | n/a | s.connect((HOST, server.port)) |
|---|
| 3563 | n/a | self.assertEqual(s.session.id, session.id) |
|---|
| 3564 | n/a | self.assertEqual(s.session, session) |
|---|
| 3565 | n/a | self.assertEqual(s.session_reused, True) |
|---|
| 3566 | n/a | |
|---|
| 3567 | n/a | with context2.wrap_socket(socket.socket()) as s: |
|---|
| 3568 | n/a | # cannot re-use session with a different SSLContext |
|---|
| 3569 | n/a | with self.assertRaises(ValueError) as e: |
|---|
| 3570 | n/a | s.session = session |
|---|
| 3571 | n/a | s.connect((HOST, server.port)) |
|---|
| 3572 | n/a | self.assertEqual(str(e.exception), |
|---|
| 3573 | n/a | 'Session refers to a different SSLContext.') |
|---|
| 3574 | n/a | |
|---|
| 3575 | n/a | |
|---|
| 3576 | n/a | def test_main(verbose=False): |
|---|
| 3577 | n/a | if support.verbose: |
|---|
| 3578 | n/a | import warnings |
|---|
| 3579 | n/a | plats = { |
|---|
| 3580 | n/a | 'Linux': platform.linux_distribution, |
|---|
| 3581 | n/a | 'Mac': platform.mac_ver, |
|---|
| 3582 | n/a | 'Windows': platform.win32_ver, |
|---|
| 3583 | n/a | } |
|---|
| 3584 | n/a | with warnings.catch_warnings(): |
|---|
| 3585 | n/a | warnings.filterwarnings( |
|---|
| 3586 | n/a | 'ignore', |
|---|
| 3587 | n/a | r'dist\(\) and linux_distribution\(\) ' |
|---|
| 3588 | n/a | 'functions are deprecated .*', |
|---|
| 3589 | n/a | PendingDeprecationWarning, |
|---|
| 3590 | n/a | ) |
|---|
| 3591 | n/a | for name, func in plats.items(): |
|---|
| 3592 | n/a | plat = func() |
|---|
| 3593 | n/a | if plat and plat[0]: |
|---|
| 3594 | n/a | plat = '%s %r' % (name, plat) |
|---|
| 3595 | n/a | break |
|---|
| 3596 | n/a | else: |
|---|
| 3597 | n/a | plat = repr(platform.platform()) |
|---|
| 3598 | n/a | print("test_ssl: testing with %r %r" % |
|---|
| 3599 | n/a | (ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO)) |
|---|
| 3600 | n/a | print(" under %s" % plat) |
|---|
| 3601 | n/a | print(" HAS_SNI = %r" % ssl.HAS_SNI) |
|---|
| 3602 | n/a | print(" OP_ALL = 0x%8x" % ssl.OP_ALL) |
|---|
| 3603 | n/a | try: |
|---|
| 3604 | n/a | print(" OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1) |
|---|
| 3605 | n/a | except AttributeError: |
|---|
| 3606 | n/a | pass |
|---|
| 3607 | n/a | |
|---|
| 3608 | n/a | for filename in [ |
|---|
| 3609 | n/a | CERTFILE, BYTES_CERTFILE, |
|---|
| 3610 | n/a | ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, |
|---|
| 3611 | n/a | SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA, |
|---|
| 3612 | n/a | BADCERT, BADKEY, EMPTYCERT]: |
|---|
| 3613 | n/a | if not os.path.exists(filename): |
|---|
| 3614 | n/a | raise support.TestFailed("Can't read certificate file %r" % filename) |
|---|
| 3615 | n/a | |
|---|
| 3616 | n/a | tests = [ |
|---|
| 3617 | n/a | ContextTests, BasicSocketTests, SSLErrorTests, MemoryBIOTests, |
|---|
| 3618 | n/a | SimpleBackgroundTests, |
|---|
| 3619 | n/a | ] |
|---|
| 3620 | n/a | |
|---|
| 3621 | n/a | if support.is_resource_enabled('network'): |
|---|
| 3622 | n/a | tests.append(NetworkedTests) |
|---|
| 3623 | n/a | |
|---|
| 3624 | n/a | if _have_threads: |
|---|
| 3625 | n/a | thread_info = support.threading_setup() |
|---|
| 3626 | n/a | if thread_info: |
|---|
| 3627 | n/a | tests.append(ThreadedTests) |
|---|
| 3628 | n/a | |
|---|
| 3629 | n/a | try: |
|---|
| 3630 | n/a | support.run_unittest(*tests) |
|---|
| 3631 | n/a | finally: |
|---|
| 3632 | n/a | if _have_threads: |
|---|
| 3633 | n/a | support.threading_cleanup(*thread_info) |
|---|
| 3634 | n/a | |
|---|
| 3635 | n/a | if __name__ == "__main__": |
|---|
| 3636 | n/a | test_main() |
|---|