| 1 |
# Test the support for SSL and sockets |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import sys |
| 5 |
import unittest |
| 6 |
import unittest.mock |
| 7 |
from ast import literal_eval |
| 8 |
from threading import Thread |
| 9 |
from test import support |
| 10 |
from test.support import import_helper |
| 11 |
from test.support import os_helper |
| 12 |
from test.support import socket_helper |
| 13 |
from test.support import threading_helper |
| 14 |
from test.support import warnings_helper |
| 15 |
from test.support import asyncore |
| 16 |
import array |
| 17 |
import re |
| 18 |
import socket |
| 19 |
import select |
| 20 |
import struct |
| 21 |
import time |
| 22 |
import enum |
| 23 |
import gc |
| 24 |
import http.client |
| 25 |
import os |
| 26 |
import errno |
| 27 |
import pprint |
| 28 |
import urllib.request |
| 29 |
import threading |
| 30 |
import traceback |
| 31 |
import weakref |
| 32 |
import platform |
| 33 |
import sysconfig |
| 34 |
import functools |
| 35 |
from contextlib import nullcontext |
| 36 |
try: |
| 37 |
import ctypes |
| 38 |
except ImportError: |
| 39 |
ctypes = None |
| 40 |
|
| 41 |
|
| 42 |
ssl = import_helper.import_module("ssl") |
| 43 |
import _ssl |
| 44 |
|
| 45 |
from ssl import Purpose, TLSVersion, _TLSContentType, _TLSMessageType, _TLSAlertType |
| 46 |
|
| 47 |
Py_DEBUG_WIN32 = support.Py_DEBUG and sys.platform == 'win32' |
| 48 |
|
| 49 |
PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) |
| 50 |
HOST = socket_helper.HOST |
| 51 |
IS_AWS_LC = "AWS-LC" in ssl.OPENSSL_VERSION |
| 52 |
IS_OPENSSL_3_0_0 = ssl.OPENSSL_VERSION_INFO >= (3, 0, 0) |
| 53 |
PY_SSL_DEFAULT_CIPHERS = sysconfig.get_config_var('PY_SSL_DEFAULT_CIPHERS') |
| 54 |
|
| 55 |
HAS_KEYLOG = hasattr(ssl.SSLContext, 'keylog_filename') |
| 56 |
requires_keylog = unittest.skipUnless( |
| 57 |
HAS_KEYLOG, 'test requires OpenSSL 1.1.1 with keylog callback') |
| 58 |
CAN_SET_KEYLOG = HAS_KEYLOG and os.name != "nt" |
| 59 |
requires_keylog_setter = unittest.skipUnless( |
| 60 |
CAN_SET_KEYLOG, |
| 61 |
"cannot set 'keylog_filename' on Windows" |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
PROTOCOL_TO_TLS_VERSION = {} |
| 66 |
for proto, ver in ( |
| 67 |
("PROTOCOL_SSLv3", "SSLv3"), |
| 68 |
("PROTOCOL_TLSv1", "TLSv1"), |
| 69 |
("PROTOCOL_TLSv1_1", "TLSv1_1"), |
| 70 |
): |
| 71 |
try: |
| 72 |
proto = getattr(ssl, proto) |
| 73 |
ver = getattr(ssl.TLSVersion, ver) |
| 74 |
except AttributeError: |
| 75 |
continue |
| 76 |
PROTOCOL_TO_TLS_VERSION[proto] = ver |
| 77 |
|
| 78 |
def data_file(*name): |
| 79 |
return os.path.join(os.path.dirname(__file__), "certdata", *name) |
| 80 |
|
| 81 |
# The custom key and certificate files used in test_ssl are generated |
| 82 |
# using Lib/test/certdata/make_ssl_certs.py. |
| 83 |
# Other certificates are simply fetched from the internet servers they |
| 84 |
# are meant to authenticate. |
| 85 |
|
| 86 |
CERTFILE = data_file("keycert.pem") |
| 87 |
BYTES_CERTFILE = os.fsencode(CERTFILE) |
| 88 |
ONLYCERT = data_file("ssl_cert.pem") |
| 89 |
ONLYKEY = data_file("ssl_key.pem") |
| 90 |
BYTES_ONLYCERT = os.fsencode(ONLYCERT) |
| 91 |
BYTES_ONLYKEY = os.fsencode(ONLYKEY) |
| 92 |
CERTFILE_PROTECTED = data_file("keycert.passwd.pem") |
| 93 |
ONLYKEY_PROTECTED = data_file("ssl_key.passwd.pem") |
| 94 |
KEY_PASSWORD = "somepass" |
| 95 |
CAPATH = data_file("capath") |
| 96 |
BYTES_CAPATH = os.fsencode(CAPATH) |
| 97 |
CAFILE_NEURONIO = data_file("capath", "4e1295a3.0") |
| 98 |
CAFILE_CACERT = data_file("capath", "5ed36f99.0") |
| 99 |
|
| 100 |
with open(data_file('keycert.pem.reference')) as file: |
| 101 |
CERTFILE_INFO = literal_eval(file.read()) |
| 102 |
|
| 103 |
# empty CRL |
| 104 |
CRLFILE = data_file("revocation.crl") |
| 105 |
|
| 106 |
# Two keys and certs signed by the same CA (for SNI tests) |
| 107 |
SIGNED_CERTFILE = data_file("keycert3.pem") |
| 108 |
SINGED_CERTFILE_ONLY = data_file("cert3.pem") |
| 109 |
SIGNED_CERTFILE_HOSTNAME = 'localhost' |
| 110 |
|
| 111 |
with open(data_file('keycert3.pem.reference')) as file: |
| 112 |
SIGNED_CERTFILE_INFO = literal_eval(file.read()) |
| 113 |
|
| 114 |
SIGNED_CERTFILE2 = data_file("keycert4.pem") |
| 115 |
SIGNED_CERTFILE2_HOSTNAME = 'fakehostname' |
| 116 |
SIGNED_CERTFILE_ECC = data_file("keycertecc.pem") |
| 117 |
SIGNED_CERTFILE_ECC_HOSTNAME = 'localhost-ecc' |
| 118 |
|
| 119 |
# A custom testcase, extracted from `rfc5280::aki::leaf-missing-aki` in x509-limbo: |
| 120 |
# The leaf (server) certificate has no AKI, which is forbidden under RFC 5280. |
| 121 |
# See: https://x509-limbo.com/testcases/rfc5280/#rfc5280akileaf-missing-aki |
| 122 |
LEAF_MISSING_AKI_CERTFILE = data_file("leaf-missing-aki.keycert.pem") |
| 123 |
LEAF_MISSING_AKI_CERTFILE_HOSTNAME = "example.com" |
| 124 |
LEAF_MISSING_AKI_CA = data_file("leaf-missing-aki.ca.pem") |
| 125 |
|
| 126 |
# Same certificate as pycacert.pem, but without extra text in file |
| 127 |
SIGNING_CA = data_file("capath", "ceff1710.0") |
| 128 |
# cert with all kinds of subject alt names |
| 129 |
ALLSANFILE = data_file("allsans.pem") |
| 130 |
IDNSANSFILE = data_file("idnsans.pem") |
| 131 |
NOSANFILE = data_file("nosan.pem") |
| 132 |
NOSAN_HOSTNAME = 'localhost' |
| 133 |
|
| 134 |
REMOTE_HOST = "self-signed.pythontest.net" |
| 135 |
|
| 136 |
EMPTYCERT = data_file("nullcert.pem") |
| 137 |
BADCERT = data_file("badcert.pem") |
| 138 |
NONEXISTINGCERT = data_file("XXXnonexisting.pem") |
| 139 |
BADKEY = data_file("badkey.pem") |
| 140 |
NOKIACERT = data_file("nokia.pem") |
| 141 |
NULLBYTECERT = data_file("nullbytecert.pem") |
| 142 |
TALOS_INVALID_CRLDP = data_file("talos-2019-0758.pem") |
| 143 |
|
| 144 |
DHFILE = data_file("ffdh3072.pem") |
| 145 |
BYTES_DHFILE = os.fsencode(DHFILE) |
| 146 |
|
| 147 |
# Not defined in all versions of OpenSSL |
| 148 |
OP_NO_COMPRESSION = getattr(ssl, "OP_NO_COMPRESSION", 0) |
| 149 |
OP_SINGLE_DH_USE = getattr(ssl, "OP_SINGLE_DH_USE", 0) |
| 150 |
OP_SINGLE_ECDH_USE = getattr(ssl, "OP_SINGLE_ECDH_USE", 0) |
| 151 |
OP_CIPHER_SERVER_PREFERENCE = getattr(ssl, "OP_CIPHER_SERVER_PREFERENCE", 0) |
| 152 |
OP_ENABLE_MIDDLEBOX_COMPAT = getattr(ssl, "OP_ENABLE_MIDDLEBOX_COMPAT", 0) |
| 153 |
|
| 154 |
# Ubuntu has patched OpenSSL and changed behavior of security level 2 |
| 155 |
# see https://bugs.python.org/issue41561#msg389003 |
| 156 |
def is_ubuntu(): |
| 157 |
try: |
| 158 |
# Assume that any references of "ubuntu" implies Ubuntu-like distro |
| 159 |
# The workaround is not required for 18.04, but doesn't hurt either. |
| 160 |
with open("/etc/os-release", encoding="utf-8") as f: |
| 161 |
return "ubuntu" in f.read() |
| 162 |
except FileNotFoundError: |
| 163 |
return False |
| 164 |
|
| 165 |
if is_ubuntu(): |
| 166 |
def seclevel_workaround(*ctxs): |
| 167 |
"""Lower security level to '1' and allow all ciphers for TLS 1.0/1""" |
| 168 |
for ctx in ctxs: |
| 169 |
if ( |
| 170 |
hasattr(ctx, "minimum_version") and |
| 171 |
ctx.minimum_version <= ssl.TLSVersion.TLSv1_1 and |
| 172 |
ctx.security_level > 1 |
| 173 |
): |
| 174 |
ctx.set_ciphers("@SECLEVEL=1:ALL") |
| 175 |
else: |
| 176 |
def seclevel_workaround(*ctxs): |
| 177 |
pass |
| 178 |
|
| 179 |
|
| 180 |
def has_tls_protocol(protocol): |
| 181 |
"""Check if a TLS protocol is available and enabled |
| 182 |
|
| 183 |
:param protocol: enum ssl._SSLMethod member or name |
| 184 |
:return: bool |
| 185 |
""" |
| 186 |
if isinstance(protocol, str): |
| 187 |
assert protocol.startswith('PROTOCOL_') |
| 188 |
protocol = getattr(ssl, protocol, None) |
| 189 |
if protocol is None: |
| 190 |
return False |
| 191 |
if protocol in { |
| 192 |
ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS_SERVER, |
| 193 |
ssl.PROTOCOL_TLS_CLIENT |
| 194 |
}: |
| 195 |
# auto-negotiate protocols are always available |
| 196 |
return True |
| 197 |
name = protocol.name |
| 198 |
return has_tls_version(name[len('PROTOCOL_'):]) |
| 199 |
|
| 200 |
|
| 201 |
@functools.lru_cache |
| 202 |
def has_tls_version(version): |
| 203 |
"""Check if a TLS/SSL version is enabled |
| 204 |
|
| 205 |
:param version: TLS version name or ssl.TLSVersion member |
| 206 |
:return: bool |
| 207 |
""" |
| 208 |
if isinstance(version, str): |
| 209 |
version = ssl.TLSVersion.__members__[version] |
| 210 |
|
| 211 |
# check compile time flags like ssl.HAS_TLSv1_2 |
| 212 |
if not getattr(ssl, f'HAS_{version.name}'): |
| 213 |
return False |
| 214 |
|
| 215 |
if IS_OPENSSL_3_0_0 and version < ssl.TLSVersion.TLSv1_2: |
| 216 |
# bpo43791: 3.0.0-alpha14 fails with TLSV1_ALERT_INTERNAL_ERROR |
| 217 |
return False |
| 218 |
|
| 219 |
# check runtime and dynamic crypto policy settings. A TLS version may |
| 220 |
# be compiled in but disabled by a policy or config option. |
| 221 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 222 |
if ( |
| 223 |
hasattr(ctx, 'minimum_version') and |
| 224 |
ctx.minimum_version != ssl.TLSVersion.MINIMUM_SUPPORTED and |
| 225 |
version < ctx.minimum_version |
| 226 |
): |
| 227 |
return False |
| 228 |
if ( |
| 229 |
hasattr(ctx, 'maximum_version') and |
| 230 |
ctx.maximum_version != ssl.TLSVersion.MAXIMUM_SUPPORTED and |
| 231 |
version > ctx.maximum_version |
| 232 |
): |
| 233 |
return False |
| 234 |
|
| 235 |
return True |
| 236 |
|
| 237 |
|
| 238 |
def requires_tls_version(version): |
| 239 |
"""Decorator to skip tests when a required TLS version is not available |
| 240 |
|
| 241 |
:param version: TLS version name or ssl.TLSVersion member |
| 242 |
:return: |
| 243 |
""" |
| 244 |
def decorator(func): |
| 245 |
@functools.wraps(func) |
| 246 |
def wrapper(*args, **kw): |
| 247 |
if not has_tls_version(version): |
| 248 |
raise unittest.SkipTest(f"{version} is not available.") |
| 249 |
else: |
| 250 |
return func(*args, **kw) |
| 251 |
return wrapper |
| 252 |
return decorator |
| 253 |
|
| 254 |
|
| 255 |
def handle_error(prefix): |
| 256 |
exc_format = ' '.join(traceback.format_exception(sys.exception())) |
| 257 |
if support.verbose: |
| 258 |
sys.stdout.write(prefix + exc_format) |
| 259 |
|
| 260 |
|
| 261 |
def utc_offset(): #NOTE: ignore issues like #1647654 |
| 262 |
# local time = utc time + utc offset |
| 263 |
if time.daylight and time.localtime().tm_isdst > 0: |
| 264 |
return -time.altzone # seconds |
| 265 |
return -time.timezone |
| 266 |
|
| 267 |
|
| 268 |
ignore_deprecation = warnings_helper.ignore_warnings( |
| 269 |
category=DeprecationWarning |
| 270 |
) |
| 271 |
|
| 272 |
|
| 273 |
def make_test_context( |
| 274 |
*, |
| 275 |
server_side=False, |
| 276 |
check_hostname=None, |
| 277 |
cert_reqs=ssl.CERT_NONE, |
| 278 |
ca_certs=None, certfile=None, keyfile=None, |
| 279 |
ciphers=None, |
| 280 |
min_version=None, max_version=None, |
| 281 |
): |
| 282 |
if server_side: |
| 283 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 284 |
else: |
| 285 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 286 |
|
| 287 |
if check_hostname is None: |
| 288 |
if cert_reqs == ssl.CERT_NONE: |
| 289 |
context.check_hostname = False |
| 290 |
else: |
| 291 |
context.check_hostname = check_hostname |
| 292 |
|
| 293 |
if cert_reqs is not None: |
| 294 |
context.verify_mode = cert_reqs |
| 295 |
|
| 296 |
if ca_certs is not None: |
| 297 |
context.load_verify_locations(ca_certs) |
| 298 |
if certfile is not None or keyfile is not None: |
| 299 |
context.load_cert_chain(certfile, keyfile) |
| 300 |
|
| 301 |
if ciphers is not None: |
| 302 |
context.set_ciphers(ciphers) |
| 303 |
|
| 304 |
if min_version is not None: |
| 305 |
context.minimum_version = min_version |
| 306 |
if max_version is not None: |
| 307 |
context.maximum_version = max_version |
| 308 |
|
| 309 |
return context |
| 310 |
|
| 311 |
|
| 312 |
def test_wrap_socket( |
| 313 |
sock, |
| 314 |
*, |
| 315 |
server_side=False, |
| 316 |
check_hostname=None, |
| 317 |
cert_reqs=ssl.CERT_NONE, |
| 318 |
ca_certs=None, certfile=None, keyfile=None, |
| 319 |
ciphers=None, |
| 320 |
min_version=None, max_version=None, |
| 321 |
**kwargs, |
| 322 |
): |
| 323 |
context = make_test_context( |
| 324 |
server_side=server_side, |
| 325 |
check_hostname=check_hostname, |
| 326 |
cert_reqs=cert_reqs, |
| 327 |
ca_certs=ca_certs, certfile=certfile, keyfile=keyfile, |
| 328 |
ciphers=ciphers, |
| 329 |
min_version=min_version, max_version=max_version, |
| 330 |
) |
| 331 |
if not server_side: |
| 332 |
kwargs.setdefault("server_hostname", SIGNED_CERTFILE_HOSTNAME) |
| 333 |
return context.wrap_socket(sock, server_side=server_side, **kwargs) |
| 334 |
|
| 335 |
|
| 336 |
USE_SAME_TEST_CONTEXT = False |
| 337 |
_TEST_CONTEXT = None |
| 338 |
|
| 339 |
def testing_context(server_cert=SIGNED_CERTFILE, *, server_chain=True): |
| 340 |
"""Create context |
| 341 |
|
| 342 |
client_context, server_context, hostname = testing_context() |
| 343 |
""" |
| 344 |
global _TEST_CONTEXT |
| 345 |
if USE_SAME_TEST_CONTEXT: |
| 346 |
if _TEST_CONTEXT is not None: |
| 347 |
return _TEST_CONTEXT |
| 348 |
|
| 349 |
if server_cert == SIGNED_CERTFILE: |
| 350 |
hostname = SIGNED_CERTFILE_HOSTNAME |
| 351 |
elif server_cert == SIGNED_CERTFILE2: |
| 352 |
hostname = SIGNED_CERTFILE2_HOSTNAME |
| 353 |
elif server_cert == NOSANFILE: |
| 354 |
hostname = NOSAN_HOSTNAME |
| 355 |
else: |
| 356 |
raise ValueError(server_cert) |
| 357 |
|
| 358 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 359 |
client_context.load_verify_locations(SIGNING_CA) |
| 360 |
|
| 361 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 362 |
server_context.load_cert_chain(server_cert) |
| 363 |
if server_chain: |
| 364 |
server_context.load_verify_locations(SIGNING_CA) |
| 365 |
|
| 366 |
if USE_SAME_TEST_CONTEXT: |
| 367 |
if _TEST_CONTEXT is not None: |
| 368 |
_TEST_CONTEXT = client_context, server_context, hostname |
| 369 |
|
| 370 |
return client_context, server_context, hostname |
| 371 |
|
| 372 |
|
| 373 |
def do_ssl_object_handshake(sslobject, outgoing, max_retry=25): |
| 374 |
"""Call do_handshake() on the sslobject and return the sent data. |
| 375 |
|
| 376 |
If do_handshake() fails more than *max_retry* times, return None. |
| 377 |
""" |
| 378 |
data, attempt = None, 0 |
| 379 |
while not data and attempt < max_retry: |
| 380 |
with contextlib.suppress(ssl.SSLWantReadError): |
| 381 |
sslobject.do_handshake() |
| 382 |
data = outgoing.read() |
| 383 |
attempt += 1 |
| 384 |
return data |
| 385 |
|
| 386 |
|
| 387 |
class BasicSocketTests(unittest.TestCase): |
| 388 |
|
| 389 |
def test_constants(self): |
| 390 |
ssl.CERT_NONE |
| 391 |
ssl.CERT_OPTIONAL |
| 392 |
ssl.CERT_REQUIRED |
| 393 |
ssl.OP_CIPHER_SERVER_PREFERENCE |
| 394 |
ssl.OP_SINGLE_DH_USE |
| 395 |
ssl.OP_SINGLE_ECDH_USE |
| 396 |
ssl.OP_NO_COMPRESSION |
| 397 |
self.assertEqual(ssl.HAS_SNI, True) |
| 398 |
self.assertEqual(ssl.HAS_ECDH, True) |
| 399 |
self.assertEqual(ssl.HAS_TLSv1_2, True) |
| 400 |
self.assertEqual(ssl.HAS_TLSv1_3, True) |
| 401 |
ssl.OP_NO_SSLv2 |
| 402 |
ssl.OP_NO_SSLv3 |
| 403 |
ssl.OP_NO_TLSv1 |
| 404 |
ssl.OP_NO_TLSv1_3 |
| 405 |
ssl.OP_NO_TLSv1_1 |
| 406 |
ssl.OP_NO_TLSv1_2 |
| 407 |
self.assertEqual(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv23) |
| 408 |
|
| 409 |
def test_options(self): |
| 410 |
# gh-106687: SSL options values are unsigned integer (uint64_t) |
| 411 |
for name in dir(ssl): |
| 412 |
if not name.startswith('OP_'): |
| 413 |
continue |
| 414 |
with self.subTest(option=name): |
| 415 |
value = getattr(ssl, name) |
| 416 |
self.assertGreaterEqual(value, 0, f"ssl.{name}") |
| 417 |
|
| 418 |
def test_ssl_types(self): |
| 419 |
ssl_types = [ |
| 420 |
_ssl._SSLContext, |
| 421 |
_ssl._SSLSocket, |
| 422 |
_ssl.MemoryBIO, |
| 423 |
_ssl.Certificate, |
| 424 |
_ssl.SSLSession, |
| 425 |
_ssl.SSLError, |
| 426 |
] |
| 427 |
for ssl_type in ssl_types: |
| 428 |
with self.subTest(ssl_type=ssl_type): |
| 429 |
with self.assertRaisesRegex(TypeError, "immutable type"): |
| 430 |
ssl_type.value = None |
| 431 |
support.check_disallow_instantiation(self, _ssl.Certificate) |
| 432 |
|
| 433 |
def test_private_init(self): |
| 434 |
with self.assertRaisesRegex(TypeError, "public constructor"): |
| 435 |
with socket.socket() as s: |
| 436 |
ssl.SSLSocket(s) |
| 437 |
|
| 438 |
def test_str_for_enums(self): |
| 439 |
# Make sure that the PROTOCOL_* constants have enum-like string |
| 440 |
# reprs. |
| 441 |
proto = ssl.PROTOCOL_TLS_CLIENT |
| 442 |
self.assertEqual(repr(proto), '<_SSLMethod.PROTOCOL_TLS_CLIENT: %r>' % proto.value) |
| 443 |
self.assertEqual(str(proto), str(proto.value)) |
| 444 |
ctx = ssl.SSLContext(proto) |
| 445 |
self.assertIs(ctx.protocol, proto) |
| 446 |
|
| 447 |
def test_random(self): |
| 448 |
v = ssl.RAND_status() |
| 449 |
if support.verbose: |
| 450 |
sys.stdout.write("\n RAND_status is %d (%s)\n" |
| 451 |
% (v, (v and "sufficient randomness") or |
| 452 |
"insufficient randomness")) |
| 453 |
|
| 454 |
if v: |
| 455 |
data = ssl.RAND_bytes(16) |
| 456 |
self.assertEqual(len(data), 16) |
| 457 |
else: |
| 458 |
self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16) |
| 459 |
|
| 460 |
# negative num is invalid |
| 461 |
self.assertRaises(ValueError, ssl.RAND_bytes, -5) |
| 462 |
|
| 463 |
ssl.RAND_add("this is a random string", 75.0) |
| 464 |
ssl.RAND_add(b"this is a random bytes object", 75.0) |
| 465 |
ssl.RAND_add(bytearray(b"this is a random bytearray object"), 75.0) |
| 466 |
|
| 467 |
def test_parse_cert(self): |
| 468 |
self.maxDiff = None |
| 469 |
# note that this uses an 'unofficial' function in _ssl.c, |
| 470 |
# provided solely for this test, to exercise the certificate |
| 471 |
# parsing code |
| 472 |
self.assertEqual( |
| 473 |
ssl._ssl._test_decode_cert(CERTFILE), |
| 474 |
CERTFILE_INFO |
| 475 |
) |
| 476 |
self.assertEqual( |
| 477 |
ssl._ssl._test_decode_cert(SIGNED_CERTFILE), |
| 478 |
SIGNED_CERTFILE_INFO |
| 479 |
) |
| 480 |
|
| 481 |
# Issue #13034: the subjectAltName in some certificates |
| 482 |
# (notably projects.developer.nokia.com:443) wasn't parsed |
| 483 |
p = ssl._ssl._test_decode_cert(NOKIACERT) |
| 484 |
if support.verbose: |
| 485 |
sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
| 486 |
self.assertEqual(p['subjectAltName'], |
| 487 |
(('DNS', 'projects.developer.nokia.com'), |
| 488 |
('DNS', 'projects.forum.nokia.com')) |
| 489 |
) |
| 490 |
# extra OCSP and AIA fields |
| 491 |
self.assertEqual(p['OCSP'], ('http://ocsp.verisign.com',)) |
| 492 |
self.assertEqual(p['caIssuers'], |
| 493 |
('http://SVRIntl-G3-aia.verisign.com/SVRIntlG3.cer',)) |
| 494 |
self.assertEqual(p['crlDistributionPoints'], |
| 495 |
('http://SVRIntl-G3-crl.verisign.com/SVRIntlG3.crl',)) |
| 496 |
|
| 497 |
def test_parse_cert_CVE_2019_5010(self): |
| 498 |
p = ssl._ssl._test_decode_cert(TALOS_INVALID_CRLDP) |
| 499 |
if support.verbose: |
| 500 |
sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
| 501 |
self.assertEqual( |
| 502 |
p, |
| 503 |
{ |
| 504 |
'issuer': ( |
| 505 |
(('countryName', 'UK'),), (('commonName', 'cody-ca'),)), |
| 506 |
'notAfter': 'Jun 14 18:00:58 2028 GMT', |
| 507 |
'notBefore': 'Jun 18 18:00:58 2018 GMT', |
| 508 |
'serialNumber': '02', |
| 509 |
'subject': ((('countryName', 'UK'),), |
| 510 |
(('commonName', |
| 511 |
'codenomicon-vm-2.test.lal.cisco.com'),)), |
| 512 |
'subjectAltName': ( |
| 513 |
('DNS', 'codenomicon-vm-2.test.lal.cisco.com'),), |
| 514 |
'version': 3 |
| 515 |
} |
| 516 |
) |
| 517 |
|
| 518 |
def test_parse_cert_CVE_2013_4238(self): |
| 519 |
p = ssl._ssl._test_decode_cert(NULLBYTECERT) |
| 520 |
if support.verbose: |
| 521 |
sys.stdout.write("\n" + pprint.pformat(p) + "\n") |
| 522 |
subject = ((('countryName', 'US'),), |
| 523 |
(('stateOrProvinceName', 'Oregon'),), |
| 524 |
(('localityName', 'Beaverton'),), |
| 525 |
(('organizationName', 'Python Software Foundation'),), |
| 526 |
(('organizationalUnitName', 'Python Core Development'),), |
| 527 |
(('commonName', 'null.python.org\x00example.org'),), |
| 528 |
(('emailAddress', '[email protected]'),)) |
| 529 |
self.assertEqual(p['subject'], subject) |
| 530 |
self.assertEqual(p['issuer'], subject) |
| 531 |
if ssl._OPENSSL_API_VERSION >= (0, 9, 8): |
| 532 |
san = (('DNS', 'altnull.python.org\x00example.com'), |
| 533 |
('email', '[email protected]\[email protected]'), |
| 534 |
('URI', 'http://null.python.org\x00http://example.org'), |
| 535 |
('IP Address', '192.0.2.1'), |
| 536 |
('IP Address', '2001:DB8:0:0:0:0:0:1')) |
| 537 |
else: |
| 538 |
# OpenSSL 0.9.7 doesn't support IPv6 addresses in subjectAltName |
| 539 |
san = (('DNS', 'altnull.python.org\x00example.com'), |
| 540 |
('email', '[email protected]\[email protected]'), |
| 541 |
('URI', 'http://null.python.org\x00http://example.org'), |
| 542 |
('IP Address', '192.0.2.1'), |
| 543 |
('IP Address', '<invalid>')) |
| 544 |
|
| 545 |
self.assertEqual(p['subjectAltName'], san) |
| 546 |
|
| 547 |
def test_parse_all_sans(self): |
| 548 |
p = ssl._ssl._test_decode_cert(ALLSANFILE) |
| 549 |
self.assertEqual(p['subjectAltName'], |
| 550 |
( |
| 551 |
('DNS', 'allsans'), |
| 552 |
('othername', '<unsupported>'), |
| 553 |
('othername', '<unsupported>'), |
| 554 |
('email', '[email protected]'), |
| 555 |
('DNS', 'www.example.org'), |
| 556 |
('DirName', |
| 557 |
((('countryName', 'XY'),), |
| 558 |
(('localityName', 'Castle Anthrax'),), |
| 559 |
(('organizationName', 'Python Software Foundation'),), |
| 560 |
(('commonName', 'dirname example'),))), |
| 561 |
('URI', 'https://www.python.org/'), |
| 562 |
('IP Address', '127.0.0.1'), |
| 563 |
('IP Address', '0:0:0:0:0:0:0:1'), |
| 564 |
('Registered ID', '1.2.3.4.5') |
| 565 |
) |
| 566 |
) |
| 567 |
|
| 568 |
def test_DER_to_PEM(self): |
| 569 |
with open(CAFILE_CACERT, 'r') as f: |
| 570 |
pem = f.read() |
| 571 |
d1 = ssl.PEM_cert_to_DER_cert(pem) |
| 572 |
p2 = ssl.DER_cert_to_PEM_cert(d1) |
| 573 |
d2 = ssl.PEM_cert_to_DER_cert(p2) |
| 574 |
self.assertEqual(d1, d2) |
| 575 |
if not p2.startswith(ssl.PEM_HEADER + '\n'): |
| 576 |
self.fail("DER-to-PEM didn't include correct header:\n%r\n" % p2) |
| 577 |
if not p2.endswith('\n' + ssl.PEM_FOOTER + '\n'): |
| 578 |
self.fail("DER-to-PEM didn't include correct footer:\n%r\n" % p2) |
| 579 |
|
| 580 |
def test_openssl_version(self): |
| 581 |
n = ssl.OPENSSL_VERSION_NUMBER |
| 582 |
t = ssl.OPENSSL_VERSION_INFO |
| 583 |
s = ssl.OPENSSL_VERSION |
| 584 |
self.assertIsInstance(n, int) |
| 585 |
self.assertIsInstance(t, tuple) |
| 586 |
self.assertIsInstance(s, str) |
| 587 |
# Some sanity checks follow |
| 588 |
# >= 1.1.1 |
| 589 |
self.assertGreaterEqual(n, 0x10101000) |
| 590 |
# < 4.0 |
| 591 |
self.assertLess(n, 0x40000000) |
| 592 |
major, minor, fix, patch, status = t |
| 593 |
self.assertGreaterEqual(major, 1) |
| 594 |
self.assertLess(major, 4) |
| 595 |
self.assertGreaterEqual(minor, 0) |
| 596 |
self.assertLess(minor, 256) |
| 597 |
self.assertGreaterEqual(fix, 0) |
| 598 |
self.assertLess(fix, 256) |
| 599 |
self.assertGreaterEqual(patch, 0) |
| 600 |
self.assertLessEqual(patch, 63) |
| 601 |
self.assertGreaterEqual(status, 0) |
| 602 |
self.assertLessEqual(status, 15) |
| 603 |
|
| 604 |
libressl_ver = f"LibreSSL {major:d}" |
| 605 |
if major >= 3: |
| 606 |
# 3.x uses 0xMNN00PP0L |
| 607 |
openssl_ver = f"OpenSSL {major:d}.{minor:d}.{patch:d}" |
| 608 |
else: |
| 609 |
openssl_ver = f"OpenSSL {major:d}.{minor:d}.{fix:d}" |
| 610 |
self.assertStartsWith( |
| 611 |
s, (openssl_ver, libressl_ver, "AWS-LC"), |
| 612 |
(t, hex(n)) |
| 613 |
) |
| 614 |
|
| 615 |
@support.cpython_only |
| 616 |
def test_refcycle(self): |
| 617 |
# Issue #7943: an SSL object doesn't create reference cycles with |
| 618 |
# itself. |
| 619 |
s = socket.socket(socket.AF_INET) |
| 620 |
ss = test_wrap_socket(s) |
| 621 |
wr = weakref.ref(ss) |
| 622 |
with warnings_helper.check_warnings(("", ResourceWarning)): |
| 623 |
del ss |
| 624 |
self.assertEqual(wr(), None) |
| 625 |
|
| 626 |
def test_wrapped_unconnected(self): |
| 627 |
# Methods on an unconnected SSLSocket propagate the original |
| 628 |
# OSError raise by the underlying socket object. |
| 629 |
s = socket.socket(socket.AF_INET) |
| 630 |
with test_wrap_socket(s) as ss: |
| 631 |
self.assertRaises(OSError, ss.recv, 1) |
| 632 |
self.assertRaises(OSError, ss.recv_into, bytearray(b'x')) |
| 633 |
self.assertRaises(OSError, ss.recvfrom, 1) |
| 634 |
self.assertRaises(OSError, ss.recvfrom_into, bytearray(b'x'), 1) |
| 635 |
self.assertRaises(OSError, ss.send, b'x') |
| 636 |
self.assertRaises(OSError, ss.sendto, b'x', ('0.0.0.0', 0)) |
| 637 |
self.assertRaises(NotImplementedError, ss.dup) |
| 638 |
self.assertRaises(NotImplementedError, ss.sendmsg, |
| 639 |
[b'x'], (), 0, ('0.0.0.0', 0)) |
| 640 |
self.assertRaises(NotImplementedError, ss.recvmsg, 100) |
| 641 |
self.assertRaises(NotImplementedError, ss.recvmsg_into, |
| 642 |
[bytearray(100)]) |
| 643 |
|
| 644 |
def test_timeout(self): |
| 645 |
# Issue #8524: when creating an SSL socket, the timeout of the |
| 646 |
# original socket should be retained. |
| 647 |
for timeout in (None, 0.0, 5.0): |
| 648 |
s = socket.socket(socket.AF_INET) |
| 649 |
s.settimeout(timeout) |
| 650 |
with test_wrap_socket(s) as ss: |
| 651 |
self.assertEqual(timeout, ss.gettimeout()) |
| 652 |
|
| 653 |
def test_openssl111_deprecations(self): |
| 654 |
options = [ |
| 655 |
ssl.OP_NO_TLSv1, |
| 656 |
ssl.OP_NO_TLSv1_1, |
| 657 |
ssl.OP_NO_TLSv1_2, |
| 658 |
ssl.OP_NO_TLSv1_3 |
| 659 |
] |
| 660 |
protocols = [ |
| 661 |
ssl.PROTOCOL_TLSv1, |
| 662 |
ssl.PROTOCOL_TLSv1_1, |
| 663 |
ssl.PROTOCOL_TLSv1_2, |
| 664 |
ssl.PROTOCOL_TLS |
| 665 |
] |
| 666 |
versions = [ |
| 667 |
ssl.TLSVersion.SSLv3, |
| 668 |
ssl.TLSVersion.TLSv1, |
| 669 |
ssl.TLSVersion.TLSv1_1, |
| 670 |
] |
| 671 |
|
| 672 |
for option in options: |
| 673 |
with self.subTest(option=option): |
| 674 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 675 |
with self.assertWarns(DeprecationWarning) as cm: |
| 676 |
ctx.options |= option |
| 677 |
self.assertEqual( |
| 678 |
'ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are deprecated', |
| 679 |
str(cm.warning) |
| 680 |
) |
| 681 |
|
| 682 |
for protocol in protocols: |
| 683 |
if not has_tls_protocol(protocol): |
| 684 |
continue |
| 685 |
with self.subTest(protocol=protocol): |
| 686 |
with self.assertWarns(DeprecationWarning) as cm: |
| 687 |
ssl.SSLContext(protocol) |
| 688 |
self.assertEqual( |
| 689 |
f'ssl.{protocol.name} is deprecated', |
| 690 |
str(cm.warning) |
| 691 |
) |
| 692 |
|
| 693 |
for version in versions: |
| 694 |
if not has_tls_version(version): |
| 695 |
continue |
| 696 |
with self.subTest(version=version): |
| 697 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 698 |
with self.assertWarns(DeprecationWarning) as cm: |
| 699 |
ctx.minimum_version = version |
| 700 |
version_text = '%s.%s' % (version.__class__.__name__, version.name) |
| 701 |
self.assertEqual( |
| 702 |
f'ssl.{version_text} is deprecated', |
| 703 |
str(cm.warning) |
| 704 |
) |
| 705 |
|
| 706 |
def bad_cert_test(self, certfile): |
| 707 |
"""Check that trying to use the given client certificate fails""" |
| 708 |
certfile = os.path.join(os.path.dirname(__file__) or os.curdir, |
| 709 |
"certdata", certfile) |
| 710 |
sock = socket.socket() |
| 711 |
self.addCleanup(sock.close) |
| 712 |
with self.assertRaises(ssl.SSLError): |
| 713 |
test_wrap_socket(sock, |
| 714 |
certfile=certfile) |
| 715 |
|
| 716 |
def test_empty_cert(self): |
| 717 |
"""Wrapping with an empty cert file""" |
| 718 |
self.bad_cert_test("nullcert.pem") |
| 719 |
|
| 720 |
def test_malformed_cert(self): |
| 721 |
"""Wrapping with a badly formatted certificate (syntax error)""" |
| 722 |
self.bad_cert_test("badcert.pem") |
| 723 |
|
| 724 |
def test_malformed_key(self): |
| 725 |
"""Wrapping with a badly formatted key (syntax error)""" |
| 726 |
self.bad_cert_test("badkey.pem") |
| 727 |
|
| 728 |
def test_server_side(self): |
| 729 |
# server_hostname doesn't work for server sockets |
| 730 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 731 |
with socket.socket() as sock: |
| 732 |
self.assertRaises(ValueError, ctx.wrap_socket, sock, True, |
| 733 |
server_hostname="some.hostname") |
| 734 |
|
| 735 |
def test_unknown_channel_binding(self): |
| 736 |
# should raise ValueError for unknown type |
| 737 |
s = socket.create_server(('127.0.0.1', 0)) |
| 738 |
c = socket.socket(socket.AF_INET) |
| 739 |
c.connect(s.getsockname()) |
| 740 |
with test_wrap_socket(c, do_handshake_on_connect=False) as ss: |
| 741 |
with self.assertRaises(ValueError): |
| 742 |
ss.get_channel_binding("unknown-type") |
| 743 |
s.close() |
| 744 |
|
| 745 |
@unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, |
| 746 |
"'tls-unique' channel binding not available") |
| 747 |
def test_tls_unique_channel_binding(self): |
| 748 |
# unconnected should return None for known type |
| 749 |
s = socket.socket(socket.AF_INET) |
| 750 |
with test_wrap_socket(s) as ss: |
| 751 |
self.assertIsNone(ss.get_channel_binding("tls-unique")) |
| 752 |
# the same for server-side |
| 753 |
s = socket.socket(socket.AF_INET) |
| 754 |
with test_wrap_socket(s, server_side=True, certfile=CERTFILE) as ss: |
| 755 |
self.assertIsNone(ss.get_channel_binding("tls-unique")) |
| 756 |
|
| 757 |
def test_dealloc_warn(self): |
| 758 |
ss = test_wrap_socket(socket.socket(socket.AF_INET)) |
| 759 |
r = repr(ss) |
| 760 |
with self.assertWarns(ResourceWarning) as cm: |
| 761 |
ss = None |
| 762 |
support.gc_collect() |
| 763 |
self.assertIn(r, str(cm.warning.args[0])) |
| 764 |
|
| 765 |
def test_get_default_verify_paths(self): |
| 766 |
paths = ssl.get_default_verify_paths() |
| 767 |
self.assertEqual(len(paths), 6) |
| 768 |
self.assertIsInstance(paths, ssl.DefaultVerifyPaths) |
| 769 |
|
| 770 |
with os_helper.EnvironmentVarGuard() as env: |
| 771 |
env["SSL_CERT_DIR"] = CAPATH |
| 772 |
env["SSL_CERT_FILE"] = CERTFILE |
| 773 |
paths = ssl.get_default_verify_paths() |
| 774 |
self.assertEqual(paths.cafile, CERTFILE) |
| 775 |
self.assertEqual(paths.capath, CAPATH) |
| 776 |
|
| 777 |
@unittest.skipUnless(sys.platform == "win32", "Windows specific") |
| 778 |
def test_enum_certificates(self): |
| 779 |
self.assertTrue(ssl.enum_certificates("CA")) |
| 780 |
self.assertTrue(ssl.enum_certificates("ROOT")) |
| 781 |
|
| 782 |
self.assertRaises(TypeError, ssl.enum_certificates) |
| 783 |
self.assertRaises(WindowsError, ssl.enum_certificates, "") |
| 784 |
|
| 785 |
trust_oids = set() |
| 786 |
for storename in ("CA", "ROOT"): |
| 787 |
store = ssl.enum_certificates(storename) |
| 788 |
self.assertIsInstance(store, list) |
| 789 |
for element in store: |
| 790 |
self.assertIsInstance(element, tuple) |
| 791 |
self.assertEqual(len(element), 3) |
| 792 |
cert, enc, trust = element |
| 793 |
self.assertIsInstance(cert, bytes) |
| 794 |
self.assertIn(enc, {"x509_asn", "pkcs_7_asn"}) |
| 795 |
self.assertIsInstance(trust, (frozenset, set, bool)) |
| 796 |
if isinstance(trust, (frozenset, set)): |
| 797 |
trust_oids.update(trust) |
| 798 |
|
| 799 |
serverAuth = "1.3.6.1.5.5.7.3.1" |
| 800 |
self.assertIn(serverAuth, trust_oids) |
| 801 |
|
| 802 |
@unittest.skipUnless(sys.platform == "win32", "Windows specific") |
| 803 |
def test_enum_crls(self): |
| 804 |
self.assertTrue(ssl.enum_crls("CA")) |
| 805 |
self.assertRaises(TypeError, ssl.enum_crls) |
| 806 |
self.assertRaises(WindowsError, ssl.enum_crls, "") |
| 807 |
|
| 808 |
crls = ssl.enum_crls("CA") |
| 809 |
self.assertIsInstance(crls, list) |
| 810 |
for element in crls: |
| 811 |
self.assertIsInstance(element, tuple) |
| 812 |
self.assertEqual(len(element), 2) |
| 813 |
self.assertIsInstance(element[0], bytes) |
| 814 |
self.assertIn(element[1], {"x509_asn", "pkcs_7_asn"}) |
| 815 |
|
| 816 |
|
| 817 |
def test_asn1object(self): |
| 818 |
expected = (129, 'serverAuth', 'TLS Web Server Authentication', |
| 819 |
'1.3.6.1.5.5.7.3.1') |
| 820 |
|
| 821 |
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') |
| 822 |
self.assertEqual(val, expected) |
| 823 |
self.assertEqual(val.nid, 129) |
| 824 |
self.assertEqual(val.shortname, 'serverAuth') |
| 825 |
self.assertEqual(val.longname, 'TLS Web Server Authentication') |
| 826 |
self.assertEqual(val.oid, '1.3.6.1.5.5.7.3.1') |
| 827 |
self.assertIsInstance(val, ssl._ASN1Object) |
| 828 |
self.assertRaises(ValueError, ssl._ASN1Object, 'serverAuth') |
| 829 |
|
| 830 |
val = ssl._ASN1Object.fromnid(129) |
| 831 |
self.assertEqual(val, expected) |
| 832 |
self.assertIsInstance(val, ssl._ASN1Object) |
| 833 |
self.assertRaises(ValueError, ssl._ASN1Object.fromnid, -1) |
| 834 |
with self.assertRaisesRegex(ValueError, "unknown NID 100000"): |
| 835 |
ssl._ASN1Object.fromnid(100000) |
| 836 |
for i in range(1000): |
| 837 |
try: |
| 838 |
obj = ssl._ASN1Object.fromnid(i) |
| 839 |
except ValueError: |
| 840 |
pass |
| 841 |
else: |
| 842 |
self.assertIsInstance(obj.nid, int) |
| 843 |
self.assertIsInstance(obj.shortname, str) |
| 844 |
self.assertIsInstance(obj.longname, str) |
| 845 |
self.assertIsInstance(obj.oid, (str, type(None))) |
| 846 |
|
| 847 |
val = ssl._ASN1Object.fromname('TLS Web Server Authentication') |
| 848 |
self.assertEqual(val, expected) |
| 849 |
self.assertIsInstance(val, ssl._ASN1Object) |
| 850 |
self.assertEqual(ssl._ASN1Object.fromname('serverAuth'), expected) |
| 851 |
self.assertEqual(ssl._ASN1Object.fromname('1.3.6.1.5.5.7.3.1'), |
| 852 |
expected) |
| 853 |
with self.assertRaisesRegex(ValueError, "unknown object 'serverauth'"): |
| 854 |
ssl._ASN1Object.fromname('serverauth') |
| 855 |
|
| 856 |
def test_purpose_enum(self): |
| 857 |
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.1') |
| 858 |
self.assertIsInstance(ssl.Purpose.SERVER_AUTH, ssl._ASN1Object) |
| 859 |
self.assertEqual(ssl.Purpose.SERVER_AUTH, val) |
| 860 |
self.assertEqual(ssl.Purpose.SERVER_AUTH.nid, 129) |
| 861 |
self.assertEqual(ssl.Purpose.SERVER_AUTH.shortname, 'serverAuth') |
| 862 |
self.assertEqual(ssl.Purpose.SERVER_AUTH.oid, |
| 863 |
'1.3.6.1.5.5.7.3.1') |
| 864 |
|
| 865 |
val = ssl._ASN1Object('1.3.6.1.5.5.7.3.2') |
| 866 |
self.assertIsInstance(ssl.Purpose.CLIENT_AUTH, ssl._ASN1Object) |
| 867 |
self.assertEqual(ssl.Purpose.CLIENT_AUTH, val) |
| 868 |
self.assertEqual(ssl.Purpose.CLIENT_AUTH.nid, 130) |
| 869 |
self.assertEqual(ssl.Purpose.CLIENT_AUTH.shortname, 'clientAuth') |
| 870 |
self.assertEqual(ssl.Purpose.CLIENT_AUTH.oid, |
| 871 |
'1.3.6.1.5.5.7.3.2') |
| 872 |
|
| 873 |
def test_unsupported_dtls(self): |
| 874 |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 875 |
self.addCleanup(s.close) |
| 876 |
with self.assertRaises(NotImplementedError) as cx: |
| 877 |
test_wrap_socket(s, cert_reqs=ssl.CERT_NONE) |
| 878 |
self.assertEqual(str(cx.exception), "only stream sockets are supported") |
| 879 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 880 |
with self.assertRaises(NotImplementedError) as cx: |
| 881 |
ctx.wrap_socket(s) |
| 882 |
self.assertEqual(str(cx.exception), "only stream sockets are supported") |
| 883 |
|
| 884 |
def cert_time_ok(self, timestring, timestamp): |
| 885 |
self.assertEqual(ssl.cert_time_to_seconds(timestring), timestamp) |
| 886 |
|
| 887 |
def cert_time_fail(self, timestring): |
| 888 |
with self.assertRaises(ValueError): |
| 889 |
ssl.cert_time_to_seconds(timestring) |
| 890 |
|
| 891 |
@unittest.skipUnless(utc_offset(), |
| 892 |
'local time needs to be different from UTC') |
| 893 |
def test_cert_time_to_seconds_timezone(self): |
| 894 |
# Issue #19940: ssl.cert_time_to_seconds() returns wrong |
| 895 |
# results if local timezone is not UTC |
| 896 |
self.cert_time_ok("May 9 00:00:00 2007 GMT", 1178668800.0) |
| 897 |
self.cert_time_ok("Jan 5 09:34:43 2018 GMT", 1515144883.0) |
| 898 |
|
| 899 |
def test_cert_time_to_seconds(self): |
| 900 |
timestring = "Jan 5 09:34:43 2018 GMT" |
| 901 |
ts = 1515144883.0 |
| 902 |
self.cert_time_ok(timestring, ts) |
| 903 |
# accept keyword parameter, assert its name |
| 904 |
self.assertEqual(ssl.cert_time_to_seconds(cert_time=timestring), ts) |
| 905 |
# accept both %e and %d (space or zero generated by strftime) |
| 906 |
self.cert_time_ok("Jan 05 09:34:43 2018 GMT", ts) |
| 907 |
# case-insensitive |
| 908 |
self.cert_time_ok("JaN 5 09:34:43 2018 GmT", ts) |
| 909 |
self.cert_time_fail("Jan 5 09:34 2018 GMT") # no seconds |
| 910 |
self.cert_time_fail("Jan 5 09:34:43 2018") # no GMT |
| 911 |
self.cert_time_fail("Jan 5 09:34:43 2018 UTC") # not GMT timezone |
| 912 |
self.cert_time_fail("Jan 35 09:34:43 2018 GMT") # invalid day |
| 913 |
self.cert_time_fail("Jon 5 09:34:43 2018 GMT") # invalid month |
| 914 |
self.cert_time_fail("Jan 5 24:00:00 2018 GMT") # invalid hour |
| 915 |
self.cert_time_fail("Jan 5 09:60:43 2018 GMT") # invalid minute |
| 916 |
|
| 917 |
newyear_ts = 1230768000.0 |
| 918 |
# leap seconds |
| 919 |
self.cert_time_ok("Dec 31 23:59:60 2008 GMT", newyear_ts) |
| 920 |
# same timestamp |
| 921 |
self.cert_time_ok("Jan 1 00:00:00 2009 GMT", newyear_ts) |
| 922 |
|
| 923 |
self.cert_time_ok("Jan 5 09:34:59 2018 GMT", 1515144899) |
| 924 |
# allow 60th second (even if it is not a leap second) |
| 925 |
self.cert_time_ok("Jan 5 09:34:60 2018 GMT", 1515144900) |
| 926 |
# allow 2nd leap second for compatibility with time.strptime() |
| 927 |
self.cert_time_ok("Jan 5 09:34:61 2018 GMT", 1515144901) |
| 928 |
self.cert_time_fail("Jan 5 09:34:62 2018 GMT") # invalid seconds |
| 929 |
|
| 930 |
# no special treatment for the special value: |
| 931 |
# 99991231235959Z (rfc 5280) |
| 932 |
self.cert_time_ok("Dec 31 23:59:59 9999 GMT", 253402300799.0) |
| 933 |
|
| 934 |
@support.run_with_locale('LC_ALL', '') |
| 935 |
def test_cert_time_to_seconds_locale(self): |
| 936 |
# `cert_time_to_seconds()` should be locale independent |
| 937 |
|
| 938 |
def local_february_name(): |
| 939 |
return time.strftime('%b', (1, 2, 3, 4, 5, 6, 0, 0, 0)) |
| 940 |
|
| 941 |
if local_february_name().lower() == 'feb': |
| 942 |
self.skipTest("locale-specific month name needs to be " |
| 943 |
"different from C locale") |
| 944 |
|
| 945 |
# locale-independent |
| 946 |
self.cert_time_ok("Feb 9 00:00:00 2007 GMT", 1170979200.0) |
| 947 |
self.cert_time_fail(local_february_name() + " 9 00:00:00 2007 GMT") |
| 948 |
|
| 949 |
def test_connect_ex_error(self): |
| 950 |
server = socket.socket(socket.AF_INET) |
| 951 |
self.addCleanup(server.close) |
| 952 |
port = socket_helper.bind_port(server) # Reserve port but don't listen |
| 953 |
s = test_wrap_socket(socket.socket(socket.AF_INET), |
| 954 |
cert_reqs=ssl.CERT_REQUIRED) |
| 955 |
self.addCleanup(s.close) |
| 956 |
rc = s.connect_ex((HOST, port)) |
| 957 |
# Issue #19919: Windows machines or VMs hosted on Windows |
| 958 |
# machines sometimes return EWOULDBLOCK. |
| 959 |
errors = ( |
| 960 |
errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, |
| 961 |
errno.EWOULDBLOCK, |
| 962 |
) |
| 963 |
self.assertIn(rc, errors) |
| 964 |
|
| 965 |
def test_read_write_zero(self): |
| 966 |
# empty reads and writes now work, bpo-42854, bpo-31711 |
| 967 |
client_context, server_context, hostname = testing_context() |
| 968 |
server = ThreadedEchoServer(context=server_context) |
| 969 |
with server: |
| 970 |
with client_context.wrap_socket(socket.socket(), |
| 971 |
server_hostname=hostname) as s: |
| 972 |
s.connect((HOST, server.port)) |
| 973 |
self.assertEqual(s.recv(0), b"") |
| 974 |
self.assertEqual(s.send(b""), 0) |
| 975 |
|
| 976 |
|
| 977 |
class ContextTests(unittest.TestCase): |
| 978 |
|
| 979 |
def test_constructor(self): |
| 980 |
for protocol in PROTOCOLS: |
| 981 |
if has_tls_protocol(protocol): |
| 982 |
with warnings_helper.check_warnings(): |
| 983 |
ctx = ssl.SSLContext(protocol) |
| 984 |
self.assertEqual(ctx.protocol, protocol) |
| 985 |
with warnings_helper.check_warnings(): |
| 986 |
ctx = ssl.SSLContext() |
| 987 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS) |
| 988 |
self.assertRaises(ValueError, ssl.SSLContext, -1) |
| 989 |
self.assertRaises(ValueError, ssl.SSLContext, 42) |
| 990 |
|
| 991 |
def test_ciphers(self): |
| 992 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 993 |
ctx.set_ciphers("ALL") |
| 994 |
ctx.set_ciphers("DEFAULT") |
| 995 |
with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
| 996 |
ctx.set_ciphers("^$:,;?*'dorothyx") |
| 997 |
|
| 998 |
@unittest.skipUnless(PY_SSL_DEFAULT_CIPHERS == 1, |
| 999 |
"Test applies only to Python default ciphers") |
| 1000 |
def test_python_ciphers(self): |
| 1001 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1002 |
ciphers = ctx.get_ciphers() |
| 1003 |
for suite in ciphers: |
| 1004 |
name = suite['name'] |
| 1005 |
self.assertNotIn("PSK", name) |
| 1006 |
self.assertNotIn("SRP", name) |
| 1007 |
self.assertNotIn("MD5", name) |
| 1008 |
self.assertNotIn("RC4", name) |
| 1009 |
self.assertNotIn("3DES", name) |
| 1010 |
|
| 1011 |
def test_get_ciphers(self): |
| 1012 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1013 |
ctx.set_ciphers('AESGCM') |
| 1014 |
names = set(d['name'] for d in ctx.get_ciphers()) |
| 1015 |
expected = { |
| 1016 |
'AES128-GCM-SHA256', |
| 1017 |
'ECDHE-ECDSA-AES128-GCM-SHA256', |
| 1018 |
'ECDHE-RSA-AES128-GCM-SHA256', |
| 1019 |
'DHE-RSA-AES128-GCM-SHA256', |
| 1020 |
'AES256-GCM-SHA384', |
| 1021 |
'ECDHE-ECDSA-AES256-GCM-SHA384', |
| 1022 |
'ECDHE-RSA-AES256-GCM-SHA384', |
| 1023 |
'DHE-RSA-AES256-GCM-SHA384', |
| 1024 |
} |
| 1025 |
intersection = names.intersection(expected) |
| 1026 |
self.assertGreaterEqual( |
| 1027 |
len(intersection), 2, f"\ngot: {sorted(names)}\nexpected: {sorted(expected)}" |
| 1028 |
) |
| 1029 |
|
| 1030 |
def test_options(self): |
| 1031 |
# Test default SSLContext options |
| 1032 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1033 |
# OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value |
| 1034 |
default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
| 1035 |
# SSLContext also enables these by default |
| 1036 |
default |= (OP_NO_COMPRESSION | OP_CIPHER_SERVER_PREFERENCE | |
| 1037 |
OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE | |
| 1038 |
OP_ENABLE_MIDDLEBOX_COMPAT) |
| 1039 |
self.assertEqual(default, ctx.options) |
| 1040 |
|
| 1041 |
# disallow TLSv1 |
| 1042 |
with warnings_helper.check_warnings(): |
| 1043 |
ctx.options |= ssl.OP_NO_TLSv1 |
| 1044 |
self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options) |
| 1045 |
|
| 1046 |
# allow TLSv1 |
| 1047 |
with warnings_helper.check_warnings(): |
| 1048 |
ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1) |
| 1049 |
self.assertEqual(default, ctx.options) |
| 1050 |
|
| 1051 |
# clear all options |
| 1052 |
ctx.options = 0 |
| 1053 |
# Ubuntu has OP_NO_SSLv3 forced on by default |
| 1054 |
self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) |
| 1055 |
|
| 1056 |
# invalid options |
| 1057 |
with self.assertRaises(ValueError): |
| 1058 |
ctx.options = -1 |
| 1059 |
with self.assertRaises(OverflowError): |
| 1060 |
ctx.options = 2 ** 100 |
| 1061 |
with self.assertRaises(TypeError): |
| 1062 |
ctx.options = "abc" |
| 1063 |
|
| 1064 |
def test_verify_mode_protocol(self): |
| 1065 |
with warnings_helper.check_warnings(): |
| 1066 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) |
| 1067 |
# Default value |
| 1068 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1069 |
ctx.verify_mode = ssl.CERT_OPTIONAL |
| 1070 |
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
| 1071 |
ctx.verify_mode = ssl.CERT_REQUIRED |
| 1072 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1073 |
ctx.verify_mode = ssl.CERT_NONE |
| 1074 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1075 |
with self.assertRaises(TypeError): |
| 1076 |
ctx.verify_mode = None |
| 1077 |
with self.assertRaises(ValueError): |
| 1078 |
ctx.verify_mode = 42 |
| 1079 |
|
| 1080 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1081 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1082 |
self.assertFalse(ctx.check_hostname) |
| 1083 |
|
| 1084 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1085 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1086 |
self.assertTrue(ctx.check_hostname) |
| 1087 |
|
| 1088 |
def test_hostname_checks_common_name(self): |
| 1089 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1090 |
self.assertTrue(ctx.hostname_checks_common_name) |
| 1091 |
if ssl.HAS_NEVER_CHECK_COMMON_NAME: |
| 1092 |
ctx.hostname_checks_common_name = True |
| 1093 |
self.assertTrue(ctx.hostname_checks_common_name) |
| 1094 |
ctx.hostname_checks_common_name = False |
| 1095 |
self.assertFalse(ctx.hostname_checks_common_name) |
| 1096 |
ctx.hostname_checks_common_name = True |
| 1097 |
self.assertTrue(ctx.hostname_checks_common_name) |
| 1098 |
else: |
| 1099 |
with self.assertRaises(AttributeError): |
| 1100 |
ctx.hostname_checks_common_name = True |
| 1101 |
|
| 1102 |
@ignore_deprecation |
| 1103 |
def test_min_max_version(self): |
| 1104 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1105 |
# OpenSSL default is MINIMUM_SUPPORTED, however some vendors like |
| 1106 |
# Fedora override the setting to TLS 1.0. |
| 1107 |
minimum_range = { |
| 1108 |
# stock OpenSSL |
| 1109 |
ssl.TLSVersion.MINIMUM_SUPPORTED, |
| 1110 |
# Fedora 29 uses TLS 1.0 by default |
| 1111 |
ssl.TLSVersion.TLSv1, |
| 1112 |
# RHEL 8 uses TLS 1.2 by default |
| 1113 |
ssl.TLSVersion.TLSv1_2 |
| 1114 |
} |
| 1115 |
maximum_range = { |
| 1116 |
# stock OpenSSL |
| 1117 |
ssl.TLSVersion.MAXIMUM_SUPPORTED, |
| 1118 |
# Fedora 32 uses TLS 1.3 by default |
| 1119 |
ssl.TLSVersion.TLSv1_3 |
| 1120 |
} |
| 1121 |
|
| 1122 |
self.assertIn( |
| 1123 |
ctx.minimum_version, minimum_range |
| 1124 |
) |
| 1125 |
self.assertIn( |
| 1126 |
ctx.maximum_version, maximum_range |
| 1127 |
) |
| 1128 |
|
| 1129 |
ctx.minimum_version = ssl.TLSVersion.TLSv1_1 |
| 1130 |
ctx.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 1131 |
self.assertEqual( |
| 1132 |
ctx.minimum_version, ssl.TLSVersion.TLSv1_1 |
| 1133 |
) |
| 1134 |
self.assertEqual( |
| 1135 |
ctx.maximum_version, ssl.TLSVersion.TLSv1_2 |
| 1136 |
) |
| 1137 |
|
| 1138 |
ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED |
| 1139 |
ctx.maximum_version = ssl.TLSVersion.TLSv1 |
| 1140 |
self.assertEqual( |
| 1141 |
ctx.minimum_version, ssl.TLSVersion.MINIMUM_SUPPORTED |
| 1142 |
) |
| 1143 |
self.assertEqual( |
| 1144 |
ctx.maximum_version, ssl.TLSVersion.TLSv1 |
| 1145 |
) |
| 1146 |
|
| 1147 |
ctx.maximum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED |
| 1148 |
self.assertEqual( |
| 1149 |
ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED |
| 1150 |
) |
| 1151 |
|
| 1152 |
ctx.maximum_version = ssl.TLSVersion.MINIMUM_SUPPORTED |
| 1153 |
self.assertIn( |
| 1154 |
ctx.maximum_version, |
| 1155 |
{ |
| 1156 |
ssl.TLSVersion.TLSv1, |
| 1157 |
ssl.TLSVersion.TLSv1_1, |
| 1158 |
ssl.TLSVersion.TLSv1_2, |
| 1159 |
ssl.TLSVersion.SSLv3, |
| 1160 |
} |
| 1161 |
) |
| 1162 |
|
| 1163 |
ctx.minimum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED |
| 1164 |
self.assertIn( |
| 1165 |
ctx.minimum_version, |
| 1166 |
{ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_3} |
| 1167 |
) |
| 1168 |
|
| 1169 |
with self.assertRaises(ValueError): |
| 1170 |
ctx.minimum_version = 42 |
| 1171 |
|
| 1172 |
if has_tls_protocol(ssl.PROTOCOL_TLSv1_1): |
| 1173 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1) |
| 1174 |
|
| 1175 |
self.assertIn( |
| 1176 |
ctx.minimum_version, minimum_range |
| 1177 |
) |
| 1178 |
self.assertEqual( |
| 1179 |
ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED |
| 1180 |
) |
| 1181 |
with self.assertRaises(ValueError): |
| 1182 |
ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED |
| 1183 |
with self.assertRaises(ValueError): |
| 1184 |
ctx.maximum_version = ssl.TLSVersion.TLSv1 |
| 1185 |
|
| 1186 |
@unittest.skipUnless( |
| 1187 |
hasattr(ssl.SSLContext, 'security_level'), |
| 1188 |
"requires OpenSSL >= 1.1.0" |
| 1189 |
) |
| 1190 |
def test_security_level(self): |
| 1191 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1192 |
# The default security callback allows for levels between 0-5 |
| 1193 |
# with OpenSSL defaulting to 1, however some vendors override the |
| 1194 |
# default value (e.g. Debian defaults to 2) |
| 1195 |
security_level_range = { |
| 1196 |
0, |
| 1197 |
1, # OpenSSL default |
| 1198 |
2, # Debian |
| 1199 |
3, |
| 1200 |
4, |
| 1201 |
5, |
| 1202 |
} |
| 1203 |
self.assertIn(ctx.security_level, security_level_range) |
| 1204 |
|
| 1205 |
def test_verify_flags(self): |
| 1206 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1207 |
# default value |
| 1208 |
tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) |
| 1209 |
self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf) |
| 1210 |
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF |
| 1211 |
self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF) |
| 1212 |
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN |
| 1213 |
self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN) |
| 1214 |
ctx.verify_flags = ssl.VERIFY_DEFAULT |
| 1215 |
self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT) |
| 1216 |
ctx.verify_flags = ssl.VERIFY_ALLOW_PROXY_CERTS |
| 1217 |
self.assertEqual(ctx.verify_flags, ssl.VERIFY_ALLOW_PROXY_CERTS) |
| 1218 |
# supports any value |
| 1219 |
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT |
| 1220 |
self.assertEqual(ctx.verify_flags, |
| 1221 |
ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT) |
| 1222 |
with self.assertRaises(TypeError): |
| 1223 |
ctx.verify_flags = None |
| 1224 |
|
| 1225 |
def test_load_cert_chain(self): |
| 1226 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1227 |
# Combined key and cert in a single file |
| 1228 |
ctx.load_cert_chain(CERTFILE, keyfile=None) |
| 1229 |
ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) |
| 1230 |
self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) |
| 1231 |
with self.assertRaises(OSError) as cm: |
| 1232 |
ctx.load_cert_chain(NONEXISTINGCERT) |
| 1233 |
self.assertEqual(cm.exception.errno, errno.ENOENT) |
| 1234 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1235 |
ctx.load_cert_chain(BADCERT) |
| 1236 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1237 |
ctx.load_cert_chain(EMPTYCERT) |
| 1238 |
# Separate key and cert |
| 1239 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1240 |
ctx.load_cert_chain(ONLYCERT, ONLYKEY) |
| 1241 |
ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) |
| 1242 |
ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY) |
| 1243 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1244 |
ctx.load_cert_chain(ONLYCERT) |
| 1245 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1246 |
ctx.load_cert_chain(ONLYKEY) |
| 1247 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1248 |
ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT) |
| 1249 |
# Mismatching key and cert |
| 1250 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1251 |
# Allow for flexible libssl error messages. |
| 1252 |
regex = re.compile(r"""( |
| 1253 |
key values mismatch # OpenSSL |
| 1254 |
| |
| 1255 |
KEY_VALUES_MISMATCH # AWS-LC |
| 1256 |
)""", re.X) |
| 1257 |
with self.assertRaisesRegex(ssl.SSLError, regex): |
| 1258 |
ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY) |
| 1259 |
# Password protected key and cert |
| 1260 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD) |
| 1261 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode()) |
| 1262 |
ctx.load_cert_chain(CERTFILE_PROTECTED, |
| 1263 |
password=bytearray(KEY_PASSWORD.encode())) |
| 1264 |
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD) |
| 1265 |
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode()) |
| 1266 |
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, |
| 1267 |
bytearray(KEY_PASSWORD.encode())) |
| 1268 |
with self.assertRaisesRegex(TypeError, "should be a string"): |
| 1269 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=True) |
| 1270 |
with self.assertRaises(ssl.SSLError): |
| 1271 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password="badpass") |
| 1272 |
with self.assertRaisesRegex(ValueError, "cannot be longer"): |
| 1273 |
# openssl has a fixed limit on the password buffer. |
| 1274 |
# PEM_BUFSIZE is generally set to 1kb. |
| 1275 |
# Return a string larger than this. |
| 1276 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400) |
| 1277 |
# Password callback |
| 1278 |
def getpass_unicode(): |
| 1279 |
return KEY_PASSWORD |
| 1280 |
def getpass_bytes(): |
| 1281 |
return KEY_PASSWORD.encode() |
| 1282 |
def getpass_bytearray(): |
| 1283 |
return bytearray(KEY_PASSWORD.encode()) |
| 1284 |
def getpass_badpass(): |
| 1285 |
return "badpass" |
| 1286 |
def getpass_huge(): |
| 1287 |
return b'a' * (1024 * 1024) |
| 1288 |
def getpass_bad_type(): |
| 1289 |
return 9 |
| 1290 |
def getpass_exception(): |
| 1291 |
raise Exception('getpass error') |
| 1292 |
class GetPassCallable: |
| 1293 |
def __call__(self): |
| 1294 |
return KEY_PASSWORD |
| 1295 |
def getpass(self): |
| 1296 |
return KEY_PASSWORD |
| 1297 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode) |
| 1298 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes) |
| 1299 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray) |
| 1300 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable()) |
| 1301 |
ctx.load_cert_chain(CERTFILE_PROTECTED, |
| 1302 |
password=GetPassCallable().getpass) |
| 1303 |
with self.assertRaises(ssl.SSLError): |
| 1304 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass) |
| 1305 |
with self.assertRaisesRegex(ValueError, "cannot be longer"): |
| 1306 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge) |
| 1307 |
with self.assertRaisesRegex(TypeError, "must return a string"): |
| 1308 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type) |
| 1309 |
with self.assertRaisesRegex(Exception, "getpass error"): |
| 1310 |
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception) |
| 1311 |
# Make sure the password function isn't called if it isn't needed |
| 1312 |
ctx.load_cert_chain(CERTFILE, password=getpass_exception) |
| 1313 |
|
| 1314 |
@threading_helper.requires_working_threading() |
| 1315 |
def test_load_cert_chain_thread_safety(self): |
| 1316 |
# gh-134698: _ssl detaches the thread state (and as such, |
| 1317 |
# releases the GIL and critical sections) around expensive |
| 1318 |
# OpenSSL calls. Unfortunately, OpenSSL structures aren't |
| 1319 |
# thread-safe, so executing these calls concurrently led |
| 1320 |
# to crashes. |
| 1321 |
ctx = ssl.create_default_context() |
| 1322 |
|
| 1323 |
def race(): |
| 1324 |
ctx.load_cert_chain(CERTFILE) |
| 1325 |
|
| 1326 |
threads = [threading.Thread(target=race) for _ in range(8)] |
| 1327 |
with threading_helper.catch_threading_exception() as cm: |
| 1328 |
with threading_helper.start_threads(threads): |
| 1329 |
pass |
| 1330 |
|
| 1331 |
self.assertIsNone(cm.exc_value) |
| 1332 |
|
| 1333 |
def test_load_verify_locations(self): |
| 1334 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1335 |
ctx.load_verify_locations(CERTFILE) |
| 1336 |
ctx.load_verify_locations(cafile=CERTFILE, capath=None) |
| 1337 |
ctx.load_verify_locations(BYTES_CERTFILE) |
| 1338 |
ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None) |
| 1339 |
self.assertRaises(TypeError, ctx.load_verify_locations) |
| 1340 |
self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None) |
| 1341 |
with self.assertRaises(OSError) as cm: |
| 1342 |
ctx.load_verify_locations(NONEXISTINGCERT) |
| 1343 |
self.assertEqual(cm.exception.errno, errno.ENOENT) |
| 1344 |
with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): |
| 1345 |
ctx.load_verify_locations(BADCERT) |
| 1346 |
ctx.load_verify_locations(CERTFILE, CAPATH) |
| 1347 |
ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH) |
| 1348 |
|
| 1349 |
# Issue #10989: crash if the second argument type is invalid |
| 1350 |
self.assertRaises(TypeError, ctx.load_verify_locations, None, True) |
| 1351 |
|
| 1352 |
def test_load_verify_cadata(self): |
| 1353 |
# test cadata |
| 1354 |
with open(CAFILE_CACERT) as f: |
| 1355 |
cacert_pem = f.read() |
| 1356 |
cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem) |
| 1357 |
with open(CAFILE_NEURONIO) as f: |
| 1358 |
neuronio_pem = f.read() |
| 1359 |
neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem) |
| 1360 |
|
| 1361 |
# test PEM |
| 1362 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1363 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 0) |
| 1364 |
ctx.load_verify_locations(cadata=cacert_pem) |
| 1365 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 1) |
| 1366 |
ctx.load_verify_locations(cadata=neuronio_pem) |
| 1367 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1368 |
# cert already in hash table |
| 1369 |
ctx.load_verify_locations(cadata=neuronio_pem) |
| 1370 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1371 |
|
| 1372 |
# combined |
| 1373 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1374 |
combined = "\n".join((cacert_pem, neuronio_pem)) |
| 1375 |
ctx.load_verify_locations(cadata=combined) |
| 1376 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1377 |
|
| 1378 |
# with junk around the certs |
| 1379 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1380 |
combined = ["head", cacert_pem, "other", neuronio_pem, "again", |
| 1381 |
neuronio_pem, "tail"] |
| 1382 |
ctx.load_verify_locations(cadata="\n".join(combined)) |
| 1383 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1384 |
|
| 1385 |
# test DER |
| 1386 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1387 |
ctx.load_verify_locations(cadata=cacert_der) |
| 1388 |
ctx.load_verify_locations(cadata=neuronio_der) |
| 1389 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1390 |
# cert already in hash table |
| 1391 |
ctx.load_verify_locations(cadata=cacert_der) |
| 1392 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1393 |
|
| 1394 |
# combined |
| 1395 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1396 |
combined = b"".join((cacert_der, neuronio_der)) |
| 1397 |
ctx.load_verify_locations(cadata=combined) |
| 1398 |
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2) |
| 1399 |
|
| 1400 |
# error cases |
| 1401 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1402 |
self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object) |
| 1403 |
|
| 1404 |
with self.assertRaisesRegex( |
| 1405 |
ssl.SSLError, |
| 1406 |
"no start line: cadata does not contain a certificate" |
| 1407 |
): |
| 1408 |
ctx.load_verify_locations(cadata="broken") |
| 1409 |
with self.assertRaisesRegex( |
| 1410 |
ssl.SSLError, |
| 1411 |
"not enough data: cadata does not contain a certificate" |
| 1412 |
): |
| 1413 |
ctx.load_verify_locations(cadata=b"broken") |
| 1414 |
with self.assertRaises(ssl.SSLError): |
| 1415 |
ctx.load_verify_locations(cadata=cacert_der + b"A") |
| 1416 |
|
| 1417 |
def test_load_dh_params(self): |
| 1418 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1419 |
try: |
| 1420 |
ctx.load_dh_params(DHFILE) |
| 1421 |
except RuntimeError: |
| 1422 |
if Py_DEBUG_WIN32: |
| 1423 |
self.skipTest("not supported on Win32 debug build") |
| 1424 |
raise |
| 1425 |
ctx.load_dh_params(BYTES_DHFILE) |
| 1426 |
self.assertRaises(TypeError, ctx.load_dh_params) |
| 1427 |
self.assertRaises(TypeError, ctx.load_dh_params, None) |
| 1428 |
with self.assertRaises(FileNotFoundError) as cm: |
| 1429 |
ctx.load_dh_params(NONEXISTINGCERT) |
| 1430 |
self.assertEqual(cm.exception.errno, errno.ENOENT) |
| 1431 |
with self.assertRaises(ssl.SSLError) as cm: |
| 1432 |
ctx.load_dh_params(CERTFILE) |
| 1433 |
|
| 1434 |
def test_session_stats(self): |
| 1435 |
for proto in {ssl.PROTOCOL_TLS_CLIENT, ssl.PROTOCOL_TLS_SERVER}: |
| 1436 |
ctx = ssl.SSLContext(proto) |
| 1437 |
self.assertEqual(ctx.session_stats(), { |
| 1438 |
'number': 0, |
| 1439 |
'connect': 0, |
| 1440 |
'connect_good': 0, |
| 1441 |
'connect_renegotiate': 0, |
| 1442 |
'accept': 0, |
| 1443 |
'accept_good': 0, |
| 1444 |
'accept_renegotiate': 0, |
| 1445 |
'hits': 0, |
| 1446 |
'misses': 0, |
| 1447 |
'timeouts': 0, |
| 1448 |
'cache_full': 0, |
| 1449 |
}) |
| 1450 |
|
| 1451 |
def test_set_default_verify_paths(self): |
| 1452 |
# There's not much we can do to test that it acts as expected, |
| 1453 |
# so just check it doesn't crash or raise an exception. |
| 1454 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1455 |
ctx.set_default_verify_paths() |
| 1456 |
|
| 1457 |
@unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build") |
| 1458 |
def test_set_ecdh_curve(self): |
| 1459 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1460 |
ctx.set_ecdh_curve("prime256v1") |
| 1461 |
ctx.set_ecdh_curve(b"prime256v1") |
| 1462 |
self.assertRaises(TypeError, ctx.set_ecdh_curve) |
| 1463 |
self.assertRaises(TypeError, ctx.set_ecdh_curve, None) |
| 1464 |
self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo") |
| 1465 |
self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo") |
| 1466 |
|
| 1467 |
def test_sni_callback(self): |
| 1468 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1469 |
|
| 1470 |
# set_servername_callback expects a callable, or None |
| 1471 |
self.assertRaises(TypeError, ctx.set_servername_callback) |
| 1472 |
self.assertRaises(TypeError, ctx.set_servername_callback, 4) |
| 1473 |
self.assertRaises(TypeError, ctx.set_servername_callback, "") |
| 1474 |
self.assertRaises(TypeError, ctx.set_servername_callback, ctx) |
| 1475 |
|
| 1476 |
def dummycallback(sock, servername, ctx): |
| 1477 |
pass |
| 1478 |
ctx.set_servername_callback(None) |
| 1479 |
ctx.set_servername_callback(dummycallback) |
| 1480 |
|
| 1481 |
def test_sni_callback_on_dead_references(self): |
| 1482 |
# See https://github.com/python/cpython/issues/146080. |
| 1483 |
c_ctx = make_test_context() |
| 1484 |
c_inc, c_out = ssl.MemoryBIO(), ssl.MemoryBIO() |
| 1485 |
client = c_ctx.wrap_bio(c_inc, c_out, server_hostname=SIGNED_CERTFILE_HOSTNAME) |
| 1486 |
|
| 1487 |
def sni_callback(sock, servername, ctx): pass |
| 1488 |
sni_callback = unittest.mock.Mock(wraps=sni_callback) |
| 1489 |
s_ctx = make_test_context(server_side=True, certfile=SIGNED_CERTFILE) |
| 1490 |
s_ctx.set_servername_callback(sni_callback) |
| 1491 |
|
| 1492 |
s_inc, s_out = ssl.MemoryBIO(), ssl.MemoryBIO() |
| 1493 |
server = s_ctx.wrap_bio(s_inc, s_out, server_side=True) |
| 1494 |
server_impl = server._sslobj |
| 1495 |
|
| 1496 |
# Perform the handshake on the client side first. |
| 1497 |
data = do_ssl_object_handshake(client, c_out) |
| 1498 |
sni_callback.assert_not_called() |
| 1499 |
if data is None: |
| 1500 |
self.skipTest("cannot establish a handshake from the client") |
| 1501 |
s_inc.write(data) |
| 1502 |
sni_callback.assert_not_called() |
| 1503 |
# Delete the server object before it starts doing its handshake |
| 1504 |
# and ensure that we did not call the SNI callback yet. |
| 1505 |
del server |
| 1506 |
gc.collect() |
| 1507 |
# Try to continue the server's handshake by directly using |
| 1508 |
# the internal SSL object. The latter is a weak reference |
| 1509 |
# stored in the server context and has now a dead owner. |
| 1510 |
with self.assertRaises(ssl.SSLError) as cm: |
| 1511 |
server_impl.do_handshake() |
| 1512 |
# The SNI C callback raised an exception before calling our callback. |
| 1513 |
sni_callback.assert_not_called() |
| 1514 |
|
| 1515 |
# In AWS-LC, any handshake failures reports SSL_R_PARSE_TLSEXT, |
| 1516 |
# while OpenSSL uses SSL_R_CALLBACK_FAILED on SNI callback failures. |
| 1517 |
if IS_AWS_LC: |
| 1518 |
libssl_error_reason = "PARSE_TLSEXT" |
| 1519 |
else: |
| 1520 |
libssl_error_reason = "callback failed" |
| 1521 |
self.assertIn(libssl_error_reason, str(cm.exception)) |
| 1522 |
self.assertEqual(cm.exception.errno, ssl.SSL_ERROR_SSL) |
| 1523 |
|
| 1524 |
def test_sni_callback_refcycle(self): |
| 1525 |
# Reference cycles through the servername callback are detected |
| 1526 |
# and cleared. |
| 1527 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1528 |
def dummycallback(sock, servername, ctx, cycle=ctx): |
| 1529 |
pass |
| 1530 |
ctx.set_servername_callback(dummycallback) |
| 1531 |
wr = weakref.ref(ctx) |
| 1532 |
del ctx, dummycallback |
| 1533 |
gc.collect() |
| 1534 |
self.assertIs(wr(), None) |
| 1535 |
|
| 1536 |
def test_cert_store_stats(self): |
| 1537 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1538 |
self.assertEqual(ctx.cert_store_stats(), |
| 1539 |
{'x509_ca': 0, 'crl': 0, 'x509': 0}) |
| 1540 |
ctx.load_cert_chain(CERTFILE) |
| 1541 |
self.assertEqual(ctx.cert_store_stats(), |
| 1542 |
{'x509_ca': 0, 'crl': 0, 'x509': 0}) |
| 1543 |
ctx.load_verify_locations(CERTFILE) |
| 1544 |
self.assertEqual(ctx.cert_store_stats(), |
| 1545 |
{'x509_ca': 0, 'crl': 0, 'x509': 1}) |
| 1546 |
ctx.load_verify_locations(CAFILE_CACERT) |
| 1547 |
self.assertEqual(ctx.cert_store_stats(), |
| 1548 |
{'x509_ca': 1, 'crl': 0, 'x509': 2}) |
| 1549 |
|
| 1550 |
def test_get_ca_certs(self): |
| 1551 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1552 |
self.assertEqual(ctx.get_ca_certs(), []) |
| 1553 |
# CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE |
| 1554 |
ctx.load_verify_locations(CERTFILE) |
| 1555 |
self.assertEqual(ctx.get_ca_certs(), []) |
| 1556 |
# but CAFILE_CACERT is a CA cert |
| 1557 |
ctx.load_verify_locations(CAFILE_CACERT) |
| 1558 |
self.assertEqual(ctx.get_ca_certs(), |
| 1559 |
[{'issuer': ((('organizationName', 'Root CA'),), |
| 1560 |
(('organizationalUnitName', 'http://www.cacert.org'),), |
| 1561 |
(('commonName', 'CA Cert Signing Authority'),), |
| 1562 |
(('emailAddress', '[email protected]'),)), |
| 1563 |
'notAfter': 'Mar 29 12:29:49 2033 GMT', |
| 1564 |
'notBefore': 'Mar 30 12:29:49 2003 GMT', |
| 1565 |
'serialNumber': '00', |
| 1566 |
'crlDistributionPoints': ('https://www.cacert.org/revoke.crl',), |
| 1567 |
'subject': ((('organizationName', 'Root CA'),), |
| 1568 |
(('organizationalUnitName', 'http://www.cacert.org'),), |
| 1569 |
(('commonName', 'CA Cert Signing Authority'),), |
| 1570 |
(('emailAddress', '[email protected]'),)), |
| 1571 |
'version': 3}]) |
| 1572 |
|
| 1573 |
with open(CAFILE_CACERT) as f: |
| 1574 |
pem = f.read() |
| 1575 |
der = ssl.PEM_cert_to_DER_cert(pem) |
| 1576 |
self.assertEqual(ctx.get_ca_certs(True), [der]) |
| 1577 |
|
| 1578 |
def test_load_default_certs(self): |
| 1579 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1580 |
ctx.load_default_certs() |
| 1581 |
|
| 1582 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1583 |
ctx.load_default_certs(ssl.Purpose.SERVER_AUTH) |
| 1584 |
ctx.load_default_certs() |
| 1585 |
|
| 1586 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1587 |
ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH) |
| 1588 |
|
| 1589 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1590 |
self.assertRaises(TypeError, ctx.load_default_certs, None) |
| 1591 |
self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH') |
| 1592 |
|
| 1593 |
@unittest.skipIf(sys.platform == "win32", "not-Windows specific") |
| 1594 |
def test_load_default_certs_env(self): |
| 1595 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1596 |
with os_helper.EnvironmentVarGuard() as env: |
| 1597 |
env["SSL_CERT_DIR"] = CAPATH |
| 1598 |
env["SSL_CERT_FILE"] = CERTFILE |
| 1599 |
ctx.load_default_certs() |
| 1600 |
self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0}) |
| 1601 |
|
| 1602 |
@unittest.skipUnless(sys.platform == "win32", "Windows specific") |
| 1603 |
@unittest.skipIf(support.Py_DEBUG, |
| 1604 |
"Debug build does not share environment between CRTs") |
| 1605 |
def test_load_default_certs_env_windows(self): |
| 1606 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1607 |
ctx.load_default_certs() |
| 1608 |
stats = ctx.cert_store_stats() |
| 1609 |
|
| 1610 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1611 |
with os_helper.EnvironmentVarGuard() as env: |
| 1612 |
env["SSL_CERT_DIR"] = CAPATH |
| 1613 |
env["SSL_CERT_FILE"] = CERTFILE |
| 1614 |
ctx.load_default_certs() |
| 1615 |
stats["x509"] += 1 |
| 1616 |
self.assertEqual(ctx.cert_store_stats(), stats) |
| 1617 |
|
| 1618 |
def _assert_context_options(self, ctx): |
| 1619 |
self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2) |
| 1620 |
if OP_NO_COMPRESSION != 0: |
| 1621 |
self.assertEqual(ctx.options & OP_NO_COMPRESSION, |
| 1622 |
OP_NO_COMPRESSION) |
| 1623 |
if OP_SINGLE_DH_USE != 0: |
| 1624 |
self.assertEqual(ctx.options & OP_SINGLE_DH_USE, |
| 1625 |
OP_SINGLE_DH_USE) |
| 1626 |
if OP_SINGLE_ECDH_USE != 0: |
| 1627 |
self.assertEqual(ctx.options & OP_SINGLE_ECDH_USE, |
| 1628 |
OP_SINGLE_ECDH_USE) |
| 1629 |
if OP_CIPHER_SERVER_PREFERENCE != 0: |
| 1630 |
self.assertEqual(ctx.options & OP_CIPHER_SERVER_PREFERENCE, |
| 1631 |
OP_CIPHER_SERVER_PREFERENCE) |
| 1632 |
self.assertEqual(ctx.options & ssl.OP_LEGACY_SERVER_CONNECT, |
| 1633 |
0 if IS_OPENSSL_3_0_0 else ssl.OP_LEGACY_SERVER_CONNECT) |
| 1634 |
|
| 1635 |
def test_create_default_context(self): |
| 1636 |
ctx = ssl.create_default_context() |
| 1637 |
|
| 1638 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_CLIENT) |
| 1639 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1640 |
self.assertEqual(ctx.verify_flags & ssl.VERIFY_X509_PARTIAL_CHAIN, |
| 1641 |
ssl.VERIFY_X509_PARTIAL_CHAIN) |
| 1642 |
self.assertEqual(ctx.verify_flags & ssl.VERIFY_X509_STRICT, |
| 1643 |
ssl.VERIFY_X509_STRICT) |
| 1644 |
self.assertTrue(ctx.check_hostname) |
| 1645 |
self._assert_context_options(ctx) |
| 1646 |
|
| 1647 |
with open(SIGNING_CA) as f: |
| 1648 |
cadata = f.read() |
| 1649 |
ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH, |
| 1650 |
cadata=cadata) |
| 1651 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_CLIENT) |
| 1652 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1653 |
self._assert_context_options(ctx) |
| 1654 |
|
| 1655 |
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
| 1656 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_SERVER) |
| 1657 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1658 |
self._assert_context_options(ctx) |
| 1659 |
|
| 1660 |
def test__create_stdlib_context(self): |
| 1661 |
ctx = ssl._create_stdlib_context() |
| 1662 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_CLIENT) |
| 1663 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1664 |
self.assertFalse(ctx.check_hostname) |
| 1665 |
self._assert_context_options(ctx) |
| 1666 |
|
| 1667 |
if has_tls_protocol(ssl.PROTOCOL_TLSv1): |
| 1668 |
with warnings_helper.check_warnings(): |
| 1669 |
ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1) |
| 1670 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) |
| 1671 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1672 |
self._assert_context_options(ctx) |
| 1673 |
|
| 1674 |
with warnings_helper.check_warnings(): |
| 1675 |
ctx = ssl._create_stdlib_context( |
| 1676 |
ssl.PROTOCOL_TLSv1_2, |
| 1677 |
cert_reqs=ssl.CERT_REQUIRED, |
| 1678 |
check_hostname=True |
| 1679 |
) |
| 1680 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1_2) |
| 1681 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1682 |
self.assertTrue(ctx.check_hostname) |
| 1683 |
self._assert_context_options(ctx) |
| 1684 |
|
| 1685 |
ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH) |
| 1686 |
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_SERVER) |
| 1687 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1688 |
self._assert_context_options(ctx) |
| 1689 |
|
| 1690 |
def test_check_hostname(self): |
| 1691 |
with warnings_helper.check_warnings(): |
| 1692 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) |
| 1693 |
self.assertFalse(ctx.check_hostname) |
| 1694 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1695 |
|
| 1696 |
# Auto set CERT_REQUIRED |
| 1697 |
ctx.check_hostname = True |
| 1698 |
self.assertTrue(ctx.check_hostname) |
| 1699 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1700 |
ctx.check_hostname = False |
| 1701 |
ctx.verify_mode = ssl.CERT_REQUIRED |
| 1702 |
self.assertFalse(ctx.check_hostname) |
| 1703 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1704 |
|
| 1705 |
# Changing verify_mode does not affect check_hostname |
| 1706 |
ctx.check_hostname = False |
| 1707 |
ctx.verify_mode = ssl.CERT_NONE |
| 1708 |
ctx.check_hostname = False |
| 1709 |
self.assertFalse(ctx.check_hostname) |
| 1710 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1711 |
# Auto set |
| 1712 |
ctx.check_hostname = True |
| 1713 |
self.assertTrue(ctx.check_hostname) |
| 1714 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1715 |
|
| 1716 |
ctx.check_hostname = False |
| 1717 |
ctx.verify_mode = ssl.CERT_OPTIONAL |
| 1718 |
ctx.check_hostname = False |
| 1719 |
self.assertFalse(ctx.check_hostname) |
| 1720 |
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
| 1721 |
# keep CERT_OPTIONAL |
| 1722 |
ctx.check_hostname = True |
| 1723 |
self.assertTrue(ctx.check_hostname) |
| 1724 |
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
| 1725 |
|
| 1726 |
# Cannot set CERT_NONE with check_hostname enabled |
| 1727 |
with self.assertRaises(ValueError): |
| 1728 |
ctx.verify_mode = ssl.CERT_NONE |
| 1729 |
ctx.check_hostname = False |
| 1730 |
self.assertFalse(ctx.check_hostname) |
| 1731 |
ctx.verify_mode = ssl.CERT_NONE |
| 1732 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1733 |
|
| 1734 |
def test_context_client_server(self): |
| 1735 |
# PROTOCOL_TLS_CLIENT has sane defaults |
| 1736 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1737 |
self.assertTrue(ctx.check_hostname) |
| 1738 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 1739 |
|
| 1740 |
# PROTOCOL_TLS_SERVER has different but also sane defaults |
| 1741 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1742 |
self.assertFalse(ctx.check_hostname) |
| 1743 |
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) |
| 1744 |
|
| 1745 |
def test_context_custom_class(self): |
| 1746 |
class MySSLSocket(ssl.SSLSocket): |
| 1747 |
pass |
| 1748 |
|
| 1749 |
class MySSLObject(ssl.SSLObject): |
| 1750 |
pass |
| 1751 |
|
| 1752 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1753 |
ctx.sslsocket_class = MySSLSocket |
| 1754 |
ctx.sslobject_class = MySSLObject |
| 1755 |
|
| 1756 |
with ctx.wrap_socket(socket.socket(), server_side=True) as sock: |
| 1757 |
self.assertIsInstance(sock, MySSLSocket) |
| 1758 |
obj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), server_side=True) |
| 1759 |
self.assertIsInstance(obj, MySSLObject) |
| 1760 |
|
| 1761 |
def test_num_tickest(self): |
| 1762 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1763 |
self.assertEqual(ctx.num_tickets, 2) |
| 1764 |
ctx.num_tickets = 1 |
| 1765 |
self.assertEqual(ctx.num_tickets, 1) |
| 1766 |
ctx.num_tickets = 0 |
| 1767 |
self.assertEqual(ctx.num_tickets, 0) |
| 1768 |
with self.assertRaises(ValueError): |
| 1769 |
ctx.num_tickets = -1 |
| 1770 |
with self.assertRaises(TypeError): |
| 1771 |
ctx.num_tickets = None |
| 1772 |
|
| 1773 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1774 |
self.assertEqual(ctx.num_tickets, 2) |
| 1775 |
with self.assertRaises(ValueError): |
| 1776 |
ctx.num_tickets = 1 |
| 1777 |
|
| 1778 |
@support.cpython_only |
| 1779 |
def test_refcycle_msg_callback(self): |
| 1780 |
# See https://github.com/python/cpython/issues/142516. |
| 1781 |
ctx = make_test_context() |
| 1782 |
def msg_callback(*args, _=ctx, **kwargs): ... |
| 1783 |
ctx._msg_callback = msg_callback |
| 1784 |
|
| 1785 |
@support.cpython_only |
| 1786 |
@requires_keylog_setter |
| 1787 |
def test_refcycle_keylog_filename(self): |
| 1788 |
# See https://github.com/python/cpython/issues/142516. |
| 1789 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 1790 |
ctx = make_test_context() |
| 1791 |
class KeylogFilename(str): ... |
| 1792 |
ctx.keylog_filename = KeylogFilename(os_helper.TESTFN) |
| 1793 |
ctx.keylog_filename._ = ctx |
| 1794 |
|
| 1795 |
@support.cpython_only |
| 1796 |
@unittest.skipUnless(ssl.HAS_PSK, 'requires TLS-PSK') |
| 1797 |
def test_refcycle_psk_client_callback(self): |
| 1798 |
# See https://github.com/python/cpython/issues/142516. |
| 1799 |
ctx = make_test_context() |
| 1800 |
def psk_client_callback(*args, _=ctx, **kwargs): ... |
| 1801 |
ctx.set_psk_client_callback(psk_client_callback) |
| 1802 |
|
| 1803 |
@support.cpython_only |
| 1804 |
@unittest.skipUnless(ssl.HAS_PSK, 'requires TLS-PSK') |
| 1805 |
def test_refcycle_psk_server_callback(self): |
| 1806 |
# See https://github.com/python/cpython/issues/142516. |
| 1807 |
ctx = make_test_context(server_side=True) |
| 1808 |
def psk_server_callback(*args, _=ctx, **kwargs): ... |
| 1809 |
ctx.set_psk_server_callback(psk_server_callback) |
| 1810 |
|
| 1811 |
|
| 1812 |
class SSLErrorTests(unittest.TestCase): |
| 1813 |
|
| 1814 |
def test_str(self): |
| 1815 |
# The str() of a SSLError doesn't include the errno |
| 1816 |
e = ssl.SSLError(1, "foo") |
| 1817 |
self.assertEqual(str(e), "foo") |
| 1818 |
self.assertEqual(e.errno, 1) |
| 1819 |
# Same for a subclass |
| 1820 |
e = ssl.SSLZeroReturnError(1, "foo") |
| 1821 |
self.assertEqual(str(e), "foo") |
| 1822 |
self.assertEqual(e.errno, 1) |
| 1823 |
|
| 1824 |
def test_lib_reason(self): |
| 1825 |
# Test the library and reason attributes |
| 1826 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1827 |
try: |
| 1828 |
with self.assertRaises(ssl.SSLError) as cm: |
| 1829 |
ctx.load_dh_params(CERTFILE) |
| 1830 |
except RuntimeError: |
| 1831 |
if Py_DEBUG_WIN32: |
| 1832 |
self.skipTest("not supported on Win32 debug build") |
| 1833 |
raise |
| 1834 |
|
| 1835 |
self.assertEqual(cm.exception.library, 'PEM') |
| 1836 |
regex = "(NO_START_LINE|UNSUPPORTED_PUBLIC_KEY_TYPE)" |
| 1837 |
self.assertRegex(cm.exception.reason, regex) |
| 1838 |
s = str(cm.exception) |
| 1839 |
self.assertIn("NO_START_LINE", s) |
| 1840 |
|
| 1841 |
def test_subclass(self): |
| 1842 |
# Check that the appropriate SSLError subclass is raised |
| 1843 |
# (this only tests one of them) |
| 1844 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 1845 |
ctx.check_hostname = False |
| 1846 |
ctx.verify_mode = ssl.CERT_NONE |
| 1847 |
with socket.create_server(("127.0.0.1", 0)) as s: |
| 1848 |
c = socket.create_connection(s.getsockname()) |
| 1849 |
c.setblocking(False) |
| 1850 |
with ctx.wrap_socket(c, False, do_handshake_on_connect=False) as c: |
| 1851 |
with self.assertRaises(ssl.SSLWantReadError) as cm: |
| 1852 |
c.do_handshake() |
| 1853 |
s = str(cm.exception) |
| 1854 |
self.assertStartsWith(s, "The operation did not complete (read)") |
| 1855 |
# For compatibility |
| 1856 |
self.assertEqual(cm.exception.errno, ssl.SSL_ERROR_WANT_READ) |
| 1857 |
|
| 1858 |
|
| 1859 |
def test_bad_server_hostname(self): |
| 1860 |
ctx = ssl.create_default_context() |
| 1861 |
with self.assertRaises(ValueError): |
| 1862 |
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), |
| 1863 |
server_hostname="") |
| 1864 |
with self.assertRaises(ValueError): |
| 1865 |
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), |
| 1866 |
server_hostname=".example.org") |
| 1867 |
with self.assertRaises(TypeError): |
| 1868 |
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), |
| 1869 |
server_hostname="example.org\x00evil.com") |
| 1870 |
|
| 1871 |
|
| 1872 |
class MemoryBIOTests(unittest.TestCase): |
| 1873 |
|
| 1874 |
def test_read_write(self): |
| 1875 |
bio = ssl.MemoryBIO() |
| 1876 |
bio.write(b'foo') |
| 1877 |
self.assertEqual(bio.read(), b'foo') |
| 1878 |
self.assertEqual(bio.read(), b'') |
| 1879 |
bio.write(b'foo') |
| 1880 |
bio.write(b'bar') |
| 1881 |
self.assertEqual(bio.read(), b'foobar') |
| 1882 |
self.assertEqual(bio.read(), b'') |
| 1883 |
bio.write(b'baz') |
| 1884 |
self.assertEqual(bio.read(2), b'ba') |
| 1885 |
self.assertEqual(bio.read(1), b'z') |
| 1886 |
self.assertEqual(bio.read(1), b'') |
| 1887 |
|
| 1888 |
def test_eof(self): |
| 1889 |
bio = ssl.MemoryBIO() |
| 1890 |
self.assertFalse(bio.eof) |
| 1891 |
self.assertEqual(bio.read(), b'') |
| 1892 |
self.assertFalse(bio.eof) |
| 1893 |
bio.write(b'foo') |
| 1894 |
self.assertFalse(bio.eof) |
| 1895 |
bio.write_eof() |
| 1896 |
self.assertFalse(bio.eof) |
| 1897 |
self.assertEqual(bio.read(2), b'fo') |
| 1898 |
self.assertFalse(bio.eof) |
| 1899 |
self.assertEqual(bio.read(1), b'o') |
| 1900 |
self.assertTrue(bio.eof) |
| 1901 |
self.assertEqual(bio.read(), b'') |
| 1902 |
self.assertTrue(bio.eof) |
| 1903 |
|
| 1904 |
def test_pending(self): |
| 1905 |
bio = ssl.MemoryBIO() |
| 1906 |
self.assertEqual(bio.pending, 0) |
| 1907 |
bio.write(b'foo') |
| 1908 |
self.assertEqual(bio.pending, 3) |
| 1909 |
for i in range(3): |
| 1910 |
bio.read(1) |
| 1911 |
self.assertEqual(bio.pending, 3-i-1) |
| 1912 |
for i in range(3): |
| 1913 |
bio.write(b'x') |
| 1914 |
self.assertEqual(bio.pending, i+1) |
| 1915 |
bio.read() |
| 1916 |
self.assertEqual(bio.pending, 0) |
| 1917 |
|
| 1918 |
def test_buffer_types(self): |
| 1919 |
bio = ssl.MemoryBIO() |
| 1920 |
bio.write(b'foo') |
| 1921 |
self.assertEqual(bio.read(), b'foo') |
| 1922 |
bio.write(bytearray(b'bar')) |
| 1923 |
self.assertEqual(bio.read(), b'bar') |
| 1924 |
bio.write(memoryview(b'baz')) |
| 1925 |
self.assertEqual(bio.read(), b'baz') |
| 1926 |
m = memoryview(bytearray(b'noncontig')) |
| 1927 |
noncontig_writable = m[::-2] |
| 1928 |
with self.assertRaises(BufferError): |
| 1929 |
bio.write(memoryview(noncontig_writable)) |
| 1930 |
|
| 1931 |
def test_error_types(self): |
| 1932 |
bio = ssl.MemoryBIO() |
| 1933 |
self.assertRaises(TypeError, bio.write, 'foo') |
| 1934 |
self.assertRaises(TypeError, bio.write, None) |
| 1935 |
self.assertRaises(TypeError, bio.write, True) |
| 1936 |
self.assertRaises(TypeError, bio.write, 1) |
| 1937 |
|
| 1938 |
|
| 1939 |
class SSLObjectTests(unittest.TestCase): |
| 1940 |
def test_private_init(self): |
| 1941 |
bio = ssl.MemoryBIO() |
| 1942 |
with self.assertRaisesRegex(TypeError, "public constructor"): |
| 1943 |
ssl.SSLObject(bio, bio) |
| 1944 |
|
| 1945 |
def test_unwrap(self): |
| 1946 |
client_ctx, server_ctx, hostname = testing_context() |
| 1947 |
c_in = ssl.MemoryBIO() |
| 1948 |
c_out = ssl.MemoryBIO() |
| 1949 |
s_in = ssl.MemoryBIO() |
| 1950 |
s_out = ssl.MemoryBIO() |
| 1951 |
client = client_ctx.wrap_bio(c_in, c_out, server_hostname=hostname) |
| 1952 |
server = server_ctx.wrap_bio(s_in, s_out, server_side=True) |
| 1953 |
|
| 1954 |
# Loop on the handshake for a bit to get it settled |
| 1955 |
for _ in range(5): |
| 1956 |
try: |
| 1957 |
client.do_handshake() |
| 1958 |
except ssl.SSLWantReadError: |
| 1959 |
pass |
| 1960 |
if c_out.pending: |
| 1961 |
s_in.write(c_out.read()) |
| 1962 |
try: |
| 1963 |
server.do_handshake() |
| 1964 |
except ssl.SSLWantReadError: |
| 1965 |
pass |
| 1966 |
if s_out.pending: |
| 1967 |
c_in.write(s_out.read()) |
| 1968 |
# Now the handshakes should be complete (don't raise WantReadError) |
| 1969 |
client.do_handshake() |
| 1970 |
server.do_handshake() |
| 1971 |
|
| 1972 |
# Now if we unwrap one side unilaterally, it should send close-notify |
| 1973 |
# and raise WantReadError: |
| 1974 |
with self.assertRaises(ssl.SSLWantReadError): |
| 1975 |
client.unwrap() |
| 1976 |
|
| 1977 |
# But server.unwrap() does not raise, because it reads the client's |
| 1978 |
# close-notify: |
| 1979 |
s_in.write(c_out.read()) |
| 1980 |
server.unwrap() |
| 1981 |
|
| 1982 |
# And now that the client gets the server's close-notify, it doesn't |
| 1983 |
# raise either. |
| 1984 |
c_in.write(s_out.read()) |
| 1985 |
client.unwrap() |
| 1986 |
|
| 1987 |
class SimpleBackgroundTests(unittest.TestCase): |
| 1988 |
"""Tests that connect to a simple server running in the background""" |
| 1989 |
|
| 1990 |
def setUp(self): |
| 1991 |
self.server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 1992 |
self.server_context.load_cert_chain(SIGNED_CERTFILE) |
| 1993 |
server = ThreadedEchoServer(context=self.server_context) |
| 1994 |
self.enterContext(server) |
| 1995 |
self.server_addr = (HOST, server.port) |
| 1996 |
|
| 1997 |
def test_connect(self): |
| 1998 |
with test_wrap_socket(socket.socket(socket.AF_INET), |
| 1999 |
cert_reqs=ssl.CERT_NONE) as s: |
| 2000 |
s.connect(self.server_addr) |
| 2001 |
self.assertEqual({}, s.getpeercert()) |
| 2002 |
self.assertFalse(s.server_side) |
| 2003 |
|
| 2004 |
# this should succeed because we specify the root cert |
| 2005 |
with test_wrap_socket(socket.socket(socket.AF_INET), |
| 2006 |
cert_reqs=ssl.CERT_REQUIRED, |
| 2007 |
ca_certs=SIGNING_CA) as s: |
| 2008 |
s.connect(self.server_addr) |
| 2009 |
self.assertTrue(s.getpeercert()) |
| 2010 |
self.assertFalse(s.server_side) |
| 2011 |
|
| 2012 |
def test_connect_fail(self): |
| 2013 |
# This should fail because we have no verification certs. Connection |
| 2014 |
# failure crashes ThreadedEchoServer, so run this in an independent |
| 2015 |
# test method. |
| 2016 |
s = test_wrap_socket(socket.socket(socket.AF_INET), |
| 2017 |
cert_reqs=ssl.CERT_REQUIRED) |
| 2018 |
self.addCleanup(s.close) |
| 2019 |
# Allow for flexible libssl error messages. |
| 2020 |
regex = re.compile(r"""( |
| 2021 |
certificate verify failed # OpenSSL |
| 2022 |
| |
| 2023 |
CERTIFICATE_VERIFY_FAILED # AWS-LC |
| 2024 |
)""", re.X) |
| 2025 |
self.assertRaisesRegex(ssl.SSLError, regex, |
| 2026 |
s.connect, self.server_addr) |
| 2027 |
|
| 2028 |
def test_connect_ex(self): |
| 2029 |
# Issue #11326: check connect_ex() implementation |
| 2030 |
s = test_wrap_socket(socket.socket(socket.AF_INET), |
| 2031 |
cert_reqs=ssl.CERT_REQUIRED, |
| 2032 |
ca_certs=SIGNING_CA) |
| 2033 |
self.addCleanup(s.close) |
| 2034 |
self.assertEqual(0, s.connect_ex(self.server_addr)) |
| 2035 |
self.assertTrue(s.getpeercert()) |
| 2036 |
|
| 2037 |
def test_non_blocking_connect_ex(self): |
| 2038 |
# Issue #11326: non-blocking connect_ex() should allow handshake |
| 2039 |
# to proceed after the socket gets ready. |
| 2040 |
s = test_wrap_socket(socket.socket(socket.AF_INET), |
| 2041 |
cert_reqs=ssl.CERT_REQUIRED, |
| 2042 |
ca_certs=SIGNING_CA, |
| 2043 |
do_handshake_on_connect=False) |
| 2044 |
self.addCleanup(s.close) |
| 2045 |
s.setblocking(False) |
| 2046 |
rc = s.connect_ex(self.server_addr) |
| 2047 |
# EWOULDBLOCK under Windows, EINPROGRESS elsewhere |
| 2048 |
self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) |
| 2049 |
# Wait for connect to finish |
| 2050 |
select.select([], [s], [], 5.0) |
| 2051 |
# Non-blocking handshake |
| 2052 |
while True: |
| 2053 |
try: |
| 2054 |
s.do_handshake() |
| 2055 |
break |
| 2056 |
except ssl.SSLWantReadError: |
| 2057 |
select.select([s], [], [], 5.0) |
| 2058 |
except ssl.SSLWantWriteError: |
| 2059 |
select.select([], [s], [], 5.0) |
| 2060 |
# SSL established |
| 2061 |
self.assertTrue(s.getpeercert()) |
| 2062 |
|
| 2063 |
def test_connect_with_context(self): |
| 2064 |
# Same as test_connect, but with a separately created context |
| 2065 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2066 |
ctx.check_hostname = False |
| 2067 |
ctx.verify_mode = ssl.CERT_NONE |
| 2068 |
with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
| 2069 |
s.connect(self.server_addr) |
| 2070 |
self.assertEqual({}, s.getpeercert()) |
| 2071 |
# Same with a server hostname |
| 2072 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2073 |
server_hostname="dummy") as s: |
| 2074 |
s.connect(self.server_addr) |
| 2075 |
ctx.verify_mode = ssl.CERT_REQUIRED |
| 2076 |
# This should succeed because we specify the root cert |
| 2077 |
ctx.load_verify_locations(SIGNING_CA) |
| 2078 |
with ctx.wrap_socket(socket.socket(socket.AF_INET)) as s: |
| 2079 |
s.connect(self.server_addr) |
| 2080 |
cert = s.getpeercert() |
| 2081 |
self.assertTrue(cert) |
| 2082 |
|
| 2083 |
def test_connect_with_context_fail(self): |
| 2084 |
# This should fail because we have no verification certs. Connection |
| 2085 |
# failure crashes ThreadedEchoServer, so run this in an independent |
| 2086 |
# test method. |
| 2087 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2088 |
s = ctx.wrap_socket( |
| 2089 |
socket.socket(socket.AF_INET), |
| 2090 |
server_hostname=SIGNED_CERTFILE_HOSTNAME |
| 2091 |
) |
| 2092 |
self.addCleanup(s.close) |
| 2093 |
# Allow for flexible libssl error messages. |
| 2094 |
regex = re.compile(r"""( |
| 2095 |
certificate verify failed # OpenSSL |
| 2096 |
| |
| 2097 |
CERTIFICATE_VERIFY_FAILED # AWS-LC |
| 2098 |
)""", re.X) |
| 2099 |
self.assertRaisesRegex(ssl.SSLError, regex, |
| 2100 |
s.connect, self.server_addr) |
| 2101 |
|
| 2102 |
def test_connect_capath(self): |
| 2103 |
# Verify server certificates using the `capath` argument |
| 2104 |
# NOTE: the subject hashing algorithm has been changed between |
| 2105 |
# OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must |
| 2106 |
# contain both versions of each certificate (same content, different |
| 2107 |
# filename) for this test to be portable across OpenSSL releases. |
| 2108 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2109 |
ctx.load_verify_locations(capath=CAPATH) |
| 2110 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2111 |
server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: |
| 2112 |
s.connect(self.server_addr) |
| 2113 |
cert = s.getpeercert() |
| 2114 |
self.assertTrue(cert) |
| 2115 |
|
| 2116 |
# Same with a bytes `capath` argument |
| 2117 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2118 |
ctx.load_verify_locations(capath=BYTES_CAPATH) |
| 2119 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2120 |
server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: |
| 2121 |
s.connect(self.server_addr) |
| 2122 |
cert = s.getpeercert() |
| 2123 |
self.assertTrue(cert) |
| 2124 |
|
| 2125 |
def test_connect_cadata(self): |
| 2126 |
with open(SIGNING_CA) as f: |
| 2127 |
pem = f.read() |
| 2128 |
der = ssl.PEM_cert_to_DER_cert(pem) |
| 2129 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2130 |
ctx.load_verify_locations(cadata=pem) |
| 2131 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2132 |
server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: |
| 2133 |
s.connect(self.server_addr) |
| 2134 |
cert = s.getpeercert() |
| 2135 |
self.assertTrue(cert) |
| 2136 |
|
| 2137 |
# same with DER |
| 2138 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2139 |
ctx.load_verify_locations(cadata=der) |
| 2140 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2141 |
server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: |
| 2142 |
s.connect(self.server_addr) |
| 2143 |
cert = s.getpeercert() |
| 2144 |
self.assertTrue(cert) |
| 2145 |
|
| 2146 |
@unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") |
| 2147 |
def test_makefile_close(self): |
| 2148 |
# Issue #5238: creating a file-like object with makefile() shouldn't |
| 2149 |
# delay closing the underlying "real socket" (here tested with its |
| 2150 |
# file descriptor, hence skipping the test under Windows). |
| 2151 |
ss = test_wrap_socket(socket.socket(socket.AF_INET)) |
| 2152 |
ss.connect(self.server_addr) |
| 2153 |
fd = ss.fileno() |
| 2154 |
f = ss.makefile() |
| 2155 |
f.close() |
| 2156 |
# The fd is still open |
| 2157 |
os.read(fd, 0) |
| 2158 |
# Closing the SSL socket should close the fd too |
| 2159 |
ss.close() |
| 2160 |
gc.collect() |
| 2161 |
with self.assertRaises(OSError) as e: |
| 2162 |
os.read(fd, 0) |
| 2163 |
self.assertEqual(e.exception.errno, errno.EBADF) |
| 2164 |
|
| 2165 |
def test_non_blocking_handshake(self): |
| 2166 |
s = socket.socket(socket.AF_INET) |
| 2167 |
s.connect(self.server_addr) |
| 2168 |
s.setblocking(False) |
| 2169 |
s = test_wrap_socket(s, |
| 2170 |
cert_reqs=ssl.CERT_NONE, |
| 2171 |
do_handshake_on_connect=False) |
| 2172 |
self.addCleanup(s.close) |
| 2173 |
count = 0 |
| 2174 |
while True: |
| 2175 |
try: |
| 2176 |
count += 1 |
| 2177 |
s.do_handshake() |
| 2178 |
break |
| 2179 |
except ssl.SSLWantReadError: |
| 2180 |
select.select([s], [], []) |
| 2181 |
except ssl.SSLWantWriteError: |
| 2182 |
select.select([], [s], []) |
| 2183 |
if support.verbose: |
| 2184 |
sys.stdout.write("\nNeeded %d calls to do_handshake() to establish session.\n" % count) |
| 2185 |
|
| 2186 |
def test_get_server_certificate(self): |
| 2187 |
_test_get_server_certificate(self, *self.server_addr, cert=SIGNING_CA) |
| 2188 |
|
| 2189 |
def test_get_server_certificate_sni(self): |
| 2190 |
host, port = self.server_addr |
| 2191 |
server_names = [] |
| 2192 |
|
| 2193 |
# We store servername_cb arguments to make sure they match the host |
| 2194 |
def servername_cb(ssl_sock, server_name, initial_context): |
| 2195 |
server_names.append(server_name) |
| 2196 |
self.server_context.set_servername_callback(servername_cb) |
| 2197 |
|
| 2198 |
pem = ssl.get_server_certificate((host, port)) |
| 2199 |
if not pem: |
| 2200 |
self.fail("No server certificate on %s:%s!" % (host, port)) |
| 2201 |
|
| 2202 |
pem = ssl.get_server_certificate((host, port), ca_certs=SIGNING_CA) |
| 2203 |
if not pem: |
| 2204 |
self.fail("No server certificate on %s:%s!" % (host, port)) |
| 2205 |
if support.verbose: |
| 2206 |
sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port, pem)) |
| 2207 |
|
| 2208 |
self.assertEqual(server_names, [host, host]) |
| 2209 |
|
| 2210 |
def test_get_server_certificate_fail(self): |
| 2211 |
# Connection failure crashes ThreadedEchoServer, so run this in an |
| 2212 |
# independent test method |
| 2213 |
_test_get_server_certificate_fail(self, *self.server_addr) |
| 2214 |
|
| 2215 |
def test_get_server_certificate_timeout(self): |
| 2216 |
def servername_cb(ssl_sock, server_name, initial_context): |
| 2217 |
time.sleep(0.2) |
| 2218 |
self.server_context.set_servername_callback(servername_cb) |
| 2219 |
|
| 2220 |
with self.assertRaises(socket.timeout): |
| 2221 |
ssl.get_server_certificate(self.server_addr, ca_certs=SIGNING_CA, |
| 2222 |
timeout=0.1) |
| 2223 |
|
| 2224 |
def test_ciphers(self): |
| 2225 |
with test_wrap_socket(socket.socket(socket.AF_INET), |
| 2226 |
cert_reqs=ssl.CERT_NONE, ciphers="ALL") as s: |
| 2227 |
s.connect(self.server_addr) |
| 2228 |
with test_wrap_socket(socket.socket(socket.AF_INET), |
| 2229 |
cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT") as s: |
| 2230 |
s.connect(self.server_addr) |
| 2231 |
# Error checking can happen at instantiation or when connecting |
| 2232 |
with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"): |
| 2233 |
with socket.socket(socket.AF_INET) as sock: |
| 2234 |
s = test_wrap_socket(sock, |
| 2235 |
cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx") |
| 2236 |
s.connect(self.server_addr) |
| 2237 |
|
| 2238 |
def test_get_ca_certs_capath(self): |
| 2239 |
# capath certs are loaded on request |
| 2240 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2241 |
ctx.load_verify_locations(capath=CAPATH) |
| 2242 |
self.assertEqual(ctx.get_ca_certs(), []) |
| 2243 |
with ctx.wrap_socket(socket.socket(socket.AF_INET), |
| 2244 |
server_hostname='localhost') as s: |
| 2245 |
s.connect(self.server_addr) |
| 2246 |
cert = s.getpeercert() |
| 2247 |
self.assertTrue(cert) |
| 2248 |
self.assertEqual(len(ctx.get_ca_certs()), 1) |
| 2249 |
|
| 2250 |
def test_context_setget(self): |
| 2251 |
# Check that the context of a connected socket can be replaced. |
| 2252 |
ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2253 |
ctx1.load_verify_locations(capath=CAPATH) |
| 2254 |
ctx2 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2255 |
ctx2.load_verify_locations(capath=CAPATH) |
| 2256 |
s = socket.socket(socket.AF_INET) |
| 2257 |
with ctx1.wrap_socket(s, server_hostname='localhost') as ss: |
| 2258 |
ss.connect(self.server_addr) |
| 2259 |
self.assertIs(ss.context, ctx1) |
| 2260 |
self.assertIs(ss._sslobj.context, ctx1) |
| 2261 |
ss.context = ctx2 |
| 2262 |
self.assertIs(ss.context, ctx2) |
| 2263 |
self.assertIs(ss._sslobj.context, ctx2) |
| 2264 |
|
| 2265 |
def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs): |
| 2266 |
# A simple IO loop. Call func(*args) depending on the error we get |
| 2267 |
# (WANT_READ or WANT_WRITE) move data between the socket and the BIOs. |
| 2268 |
timeout = kwargs.get('timeout', support.SHORT_TIMEOUT) |
| 2269 |
count = 0 |
| 2270 |
for _ in support.busy_retry(timeout): |
| 2271 |
errno = None |
| 2272 |
count += 1 |
| 2273 |
try: |
| 2274 |
ret = func(*args) |
| 2275 |
except ssl.SSLError as e: |
| 2276 |
if e.errno not in (ssl.SSL_ERROR_WANT_READ, |
| 2277 |
ssl.SSL_ERROR_WANT_WRITE): |
| 2278 |
raise |
| 2279 |
errno = e.errno |
| 2280 |
# Get any data from the outgoing BIO irrespective of any error, and |
| 2281 |
# send it to the socket. |
| 2282 |
buf = outgoing.read() |
| 2283 |
sock.sendall(buf) |
| 2284 |
# If there's no error, we're done. For WANT_READ, we need to get |
| 2285 |
# data from the socket and put it in the incoming BIO. |
| 2286 |
if errno is None: |
| 2287 |
break |
| 2288 |
elif errno == ssl.SSL_ERROR_WANT_READ: |
| 2289 |
buf = sock.recv(32768) |
| 2290 |
if buf: |
| 2291 |
incoming.write(buf) |
| 2292 |
else: |
| 2293 |
incoming.write_eof() |
| 2294 |
if support.verbose: |
| 2295 |
sys.stdout.write("Needed %d calls to complete %s().\n" |
| 2296 |
% (count, func.__name__)) |
| 2297 |
return ret |
| 2298 |
|
| 2299 |
def test_bio_handshake(self): |
| 2300 |
sock = socket.socket(socket.AF_INET) |
| 2301 |
self.addCleanup(sock.close) |
| 2302 |
sock.connect(self.server_addr) |
| 2303 |
incoming = ssl.MemoryBIO() |
| 2304 |
outgoing = ssl.MemoryBIO() |
| 2305 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2306 |
self.assertTrue(ctx.check_hostname) |
| 2307 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 2308 |
ctx.load_verify_locations(SIGNING_CA) |
| 2309 |
sslobj = ctx.wrap_bio(incoming, outgoing, False, |
| 2310 |
SIGNED_CERTFILE_HOSTNAME) |
| 2311 |
self.assertIs(sslobj._sslobj.owner, sslobj) |
| 2312 |
self.assertIsNone(sslobj.cipher()) |
| 2313 |
self.assertIsNone(sslobj.version()) |
| 2314 |
self.assertIsNone(sslobj.shared_ciphers()) |
| 2315 |
self.assertRaises(ValueError, sslobj.getpeercert) |
| 2316 |
# tls-unique is not defined for TLSv1.3 |
| 2317 |
# https://datatracker.ietf.org/doc/html/rfc8446#appendix-C.5 |
| 2318 |
if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES and sslobj.version() != "TLSv1.3": |
| 2319 |
self.assertIsNone(sslobj.get_channel_binding('tls-unique')) |
| 2320 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) |
| 2321 |
self.assertTrue(sslobj.cipher()) |
| 2322 |
self.assertIsNone(sslobj.shared_ciphers()) |
| 2323 |
self.assertIsNotNone(sslobj.version()) |
| 2324 |
self.assertTrue(sslobj.getpeercert()) |
| 2325 |
if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES and sslobj.version() != "TLSv1.3": |
| 2326 |
self.assertTrue(sslobj.get_channel_binding('tls-unique')) |
| 2327 |
try: |
| 2328 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) |
| 2329 |
except ssl.SSLSyscallError: |
| 2330 |
# If the server shuts down the TCP connection without sending a |
| 2331 |
# secure shutdown message, this is reported as SSL_ERROR_SYSCALL |
| 2332 |
pass |
| 2333 |
self.assertRaises(ssl.SSLError, sslobj.write, b'foo') |
| 2334 |
|
| 2335 |
def test_bio_read_write_data(self): |
| 2336 |
sock = socket.socket(socket.AF_INET) |
| 2337 |
self.addCleanup(sock.close) |
| 2338 |
sock.connect(self.server_addr) |
| 2339 |
incoming = ssl.MemoryBIO() |
| 2340 |
outgoing = ssl.MemoryBIO() |
| 2341 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 2342 |
ctx.check_hostname = False |
| 2343 |
ctx.verify_mode = ssl.CERT_NONE |
| 2344 |
sslobj = ctx.wrap_bio(incoming, outgoing, False) |
| 2345 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) |
| 2346 |
req = b'FOO\n' |
| 2347 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.write, req) |
| 2348 |
buf = self.ssl_io_loop(sock, incoming, outgoing, sslobj.read, 1024) |
| 2349 |
self.assertEqual(buf, b'foo\n') |
| 2350 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap) |
| 2351 |
|
| 2352 |
def test_transport_eof(self): |
| 2353 |
client_context, server_context, hostname = testing_context() |
| 2354 |
with socket.socket(socket.AF_INET) as sock: |
| 2355 |
sock.connect(self.server_addr) |
| 2356 |
incoming = ssl.MemoryBIO() |
| 2357 |
outgoing = ssl.MemoryBIO() |
| 2358 |
sslobj = client_context.wrap_bio(incoming, outgoing, |
| 2359 |
server_hostname=hostname) |
| 2360 |
self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake) |
| 2361 |
|
| 2362 |
# Simulate EOF from the transport. |
| 2363 |
incoming.write_eof() |
| 2364 |
self.assertRaises(ssl.SSLEOFError, sslobj.read) |
| 2365 |
|
| 2366 |
|
| 2367 |
@support.requires_resource('network') |
| 2368 |
class NetworkedTests(unittest.TestCase): |
| 2369 |
|
| 2370 |
def test_timeout_connect_ex(self): |
| 2371 |
# Issue #12065: on a timeout, connect_ex() should return the original |
| 2372 |
# errno (mimicking the behaviour of non-SSL sockets). |
| 2373 |
with socket_helper.transient_internet(REMOTE_HOST): |
| 2374 |
s = test_wrap_socket(socket.socket(socket.AF_INET), |
| 2375 |
cert_reqs=ssl.CERT_REQUIRED, |
| 2376 |
do_handshake_on_connect=False) |
| 2377 |
self.addCleanup(s.close) |
| 2378 |
s.settimeout(0.0000001) |
| 2379 |
rc = s.connect_ex((REMOTE_HOST, 443)) |
| 2380 |
if rc == 0: |
| 2381 |
self.skipTest("REMOTE_HOST responded too quickly") |
| 2382 |
elif rc == errno.ENETUNREACH: |
| 2383 |
self.skipTest("Network unreachable.") |
| 2384 |
self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) |
| 2385 |
|
| 2386 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'Needs IPv6') |
| 2387 |
@support.requires_resource('walltime') |
| 2388 |
def test_get_server_certificate_ipv6(self): |
| 2389 |
with socket_helper.transient_internet('ipv6.google.com'): |
| 2390 |
_test_get_server_certificate(self, 'ipv6.google.com', 443) |
| 2391 |
_test_get_server_certificate_fail(self, 'ipv6.google.com', 443) |
| 2392 |
|
| 2393 |
|
| 2394 |
def _test_get_server_certificate(test, host, port, cert=None): |
| 2395 |
pem = ssl.get_server_certificate((host, port)) |
| 2396 |
if not pem: |
| 2397 |
test.fail("No server certificate on %s:%s!" % (host, port)) |
| 2398 |
|
| 2399 |
pem = ssl.get_server_certificate((host, port), ca_certs=cert) |
| 2400 |
if not pem: |
| 2401 |
test.fail("No server certificate on %s:%s!" % (host, port)) |
| 2402 |
if support.verbose: |
| 2403 |
sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem)) |
| 2404 |
|
| 2405 |
def _test_get_server_certificate_fail(test, host, port): |
| 2406 |
with warnings_helper.check_no_resource_warning(test): |
| 2407 |
try: |
| 2408 |
pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE) |
| 2409 |
except ssl.SSLError as x: |
| 2410 |
#should fail |
| 2411 |
if support.verbose: |
| 2412 |
sys.stdout.write("%s\n" % x) |
| 2413 |
else: |
| 2414 |
test.fail("Got server certificate %s for %s:%s!" % (pem, host, port)) |
| 2415 |
|
| 2416 |
|
| 2417 |
from test.ssl_servers import make_https_server |
| 2418 |
|
| 2419 |
class ThreadedEchoServer(threading.Thread): |
| 2420 |
|
| 2421 |
class ConnectionHandler(threading.Thread): |
| 2422 |
|
| 2423 |
"""A mildly complicated class, because we want it to work both |
| 2424 |
with and without the SSL wrapper around the socket connection, so |
| 2425 |
that we can test the STARTTLS functionality.""" |
| 2426 |
|
| 2427 |
def __init__(self, server, connsock, addr): |
| 2428 |
self.server = server |
| 2429 |
self.running = False |
| 2430 |
self.sock = connsock |
| 2431 |
self.addr = addr |
| 2432 |
self.sock.setblocking(True) |
| 2433 |
self.sslconn = None |
| 2434 |
threading.Thread.__init__(self) |
| 2435 |
self.daemon = True |
| 2436 |
|
| 2437 |
def wrap_conn(self): |
| 2438 |
try: |
| 2439 |
self.sslconn = self.server.context.wrap_socket( |
| 2440 |
self.sock, server_side=True) |
| 2441 |
self.server.selected_alpn_protocols.append(self.sslconn.selected_alpn_protocol()) |
| 2442 |
except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError) as e: |
| 2443 |
# We treat ConnectionResetError as though it were an |
| 2444 |
# SSLError - OpenSSL on Ubuntu abruptly closes the |
| 2445 |
# connection when asked to use an unsupported protocol. |
| 2446 |
# |
| 2447 |
# BrokenPipeError is raised in TLS 1.3 mode, when OpenSSL |
| 2448 |
# tries to send session tickets after handshake. |
| 2449 |
# https://github.com/openssl/openssl/issues/6342 |
| 2450 |
# |
| 2451 |
# ConnectionAbortedError is raised in TLS 1.3 mode, when OpenSSL |
| 2452 |
# tries to send session tickets after handshake when using WinSock. |
| 2453 |
self.server.conn_errors.append(str(e)) |
| 2454 |
if self.server.chatty: |
| 2455 |
handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") |
| 2456 |
self.running = False |
| 2457 |
self.close() |
| 2458 |
return False |
| 2459 |
except (ssl.SSLError, OSError) as e: |
| 2460 |
# OSError may occur with wrong protocols, e.g. both |
| 2461 |
# sides use PROTOCOL_TLS_SERVER. |
| 2462 |
# |
| 2463 |
# XXX Various errors can have happened here, for example |
| 2464 |
# a mismatching protocol version, an invalid certificate, |
| 2465 |
# or a low-level bug. This should be made more discriminating. |
| 2466 |
# |
| 2467 |
# bpo-31323: Store the exception as string to prevent |
| 2468 |
# a reference leak: server -> conn_errors -> exception |
| 2469 |
# -> traceback -> self (ConnectionHandler) -> server |
| 2470 |
self.server.conn_errors.append(str(e)) |
| 2471 |
if self.server.chatty: |
| 2472 |
handle_error("\n server: bad connection attempt from " + repr(self.addr) + ":\n") |
| 2473 |
|
| 2474 |
# bpo-44229, bpo-43855, bpo-44237, and bpo-33450: |
| 2475 |
# Ignore spurious EPROTOTYPE returned by write() on macOS. |
| 2476 |
# See also http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/ |
| 2477 |
if e.errno != errno.EPROTOTYPE and sys.platform != "darwin": |
| 2478 |
self.running = False |
| 2479 |
self.close() |
| 2480 |
return False |
| 2481 |
else: |
| 2482 |
self.server.shared_ciphers.append(self.sslconn.shared_ciphers()) |
| 2483 |
if self.server.context.verify_mode == ssl.CERT_REQUIRED: |
| 2484 |
cert = self.sslconn.getpeercert() |
| 2485 |
if support.verbose and self.server.chatty: |
| 2486 |
sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") |
| 2487 |
cert_binary = self.sslconn.getpeercert(True) |
| 2488 |
if support.verbose and self.server.chatty: |
| 2489 |
if cert_binary is None: |
| 2490 |
sys.stdout.write(" client did not provide a cert\n") |
| 2491 |
else: |
| 2492 |
sys.stdout.write(f" cert binary is {len(cert_binary)}b\n") |
| 2493 |
cipher = self.sslconn.cipher() |
| 2494 |
if support.verbose and self.server.chatty: |
| 2495 |
sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") |
| 2496 |
return True |
| 2497 |
|
| 2498 |
def read(self): |
| 2499 |
if self.sslconn: |
| 2500 |
return self.sslconn.read() |
| 2501 |
else: |
| 2502 |
return self.sock.recv(1024) |
| 2503 |
|
| 2504 |
def write(self, bytes): |
| 2505 |
if self.sslconn: |
| 2506 |
return self.sslconn.write(bytes) |
| 2507 |
else: |
| 2508 |
return self.sock.send(bytes) |
| 2509 |
|
| 2510 |
def close(self): |
| 2511 |
if self.sslconn: |
| 2512 |
self.sslconn.close() |
| 2513 |
else: |
| 2514 |
self.sock.close() |
| 2515 |
|
| 2516 |
def run(self): |
| 2517 |
self.running = True |
| 2518 |
if not self.server.starttls_server: |
| 2519 |
if not self.wrap_conn(): |
| 2520 |
return |
| 2521 |
while self.running: |
| 2522 |
try: |
| 2523 |
msg = self.read() |
| 2524 |
stripped = msg.strip() |
| 2525 |
if not stripped: |
| 2526 |
# eof, so quit this handler |
| 2527 |
self.running = False |
| 2528 |
try: |
| 2529 |
self.sock = self.sslconn.unwrap() |
| 2530 |
except OSError: |
| 2531 |
# Many tests shut the TCP connection down |
| 2532 |
# without an SSL shutdown. This causes |
| 2533 |
# unwrap() to raise OSError with errno=0! |
| 2534 |
pass |
| 2535 |
else: |
| 2536 |
self.sslconn = None |
| 2537 |
self.close() |
| 2538 |
elif stripped == b'over': |
| 2539 |
if support.verbose and self.server.connectionchatty: |
| 2540 |
sys.stdout.write(" server: client closed connection\n") |
| 2541 |
self.close() |
| 2542 |
return |
| 2543 |
elif (self.server.starttls_server and |
| 2544 |
stripped == b'STARTTLS'): |
| 2545 |
if support.verbose and self.server.connectionchatty: |
| 2546 |
sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") |
| 2547 |
self.write(b"OK\n") |
| 2548 |
if not self.wrap_conn(): |
| 2549 |
return |
| 2550 |
elif (self.server.starttls_server and self.sslconn |
| 2551 |
and stripped == b'ENDTLS'): |
| 2552 |
if support.verbose and self.server.connectionchatty: |
| 2553 |
sys.stdout.write(" server: read ENDTLS from client, sending OK...\n") |
| 2554 |
self.write(b"OK\n") |
| 2555 |
self.sock = self.sslconn.unwrap() |
| 2556 |
self.sslconn = None |
| 2557 |
if support.verbose and self.server.connectionchatty: |
| 2558 |
sys.stdout.write(" server: connection is now unencrypted...\n") |
| 2559 |
elif stripped == b'CB tls-unique': |
| 2560 |
if support.verbose and self.server.connectionchatty: |
| 2561 |
sys.stdout.write(" server: read CB tls-unique from client, sending our CB data...\n") |
| 2562 |
data = self.sslconn.get_channel_binding("tls-unique") |
| 2563 |
self.write(repr(data).encode("us-ascii") + b"\n") |
| 2564 |
elif stripped == b'PHA': |
| 2565 |
if support.verbose and self.server.connectionchatty: |
| 2566 |
sys.stdout.write(" server: initiating post handshake auth\n") |
| 2567 |
try: |
| 2568 |
self.sslconn.verify_client_post_handshake() |
| 2569 |
except ssl.SSLError as e: |
| 2570 |
self.write(repr(e).encode("us-ascii") + b"\n") |
| 2571 |
else: |
| 2572 |
self.write(b"OK\n") |
| 2573 |
elif stripped == b'HASCERT': |
| 2574 |
if self.sslconn.getpeercert() is not None: |
| 2575 |
self.write(b'TRUE\n') |
| 2576 |
else: |
| 2577 |
self.write(b'FALSE\n') |
| 2578 |
elif stripped == b'GETCERT': |
| 2579 |
cert = self.sslconn.getpeercert() |
| 2580 |
self.write(repr(cert).encode("us-ascii") + b"\n") |
| 2581 |
elif stripped == b'VERIFIEDCHAIN': |
| 2582 |
certs = self.sslconn._sslobj.get_verified_chain() |
| 2583 |
self.write(len(certs).to_bytes(1, "big") + b"\n") |
| 2584 |
elif stripped == b'UNVERIFIEDCHAIN': |
| 2585 |
certs = self.sslconn._sslobj.get_unverified_chain() |
| 2586 |
self.write(len(certs).to_bytes(1, "big") + b"\n") |
| 2587 |
else: |
| 2588 |
if (support.verbose and |
| 2589 |
self.server.connectionchatty): |
| 2590 |
ctype = (self.sslconn and "encrypted") or "unencrypted" |
| 2591 |
sys.stdout.write(" server: read %r (%s), sending back %r (%s)...\n" |
| 2592 |
% (msg, ctype, msg.lower(), ctype)) |
| 2593 |
self.write(msg.lower()) |
| 2594 |
except OSError as e: |
| 2595 |
# handles SSLError and socket errors |
| 2596 |
if isinstance(e, ConnectionError): |
| 2597 |
# OpenSSL 1.1.1 sometimes raises |
| 2598 |
# ConnectionResetError when connection is not |
| 2599 |
# shut down gracefully. |
| 2600 |
if self.server.chatty and support.verbose: |
| 2601 |
print(f" Connection reset by peer: {self.addr}") |
| 2602 |
|
| 2603 |
self.close() |
| 2604 |
self.running = False |
| 2605 |
return |
| 2606 |
if self.server.chatty and support.verbose: |
| 2607 |
handle_error("Test server failure:\n") |
| 2608 |
try: |
| 2609 |
self.write(b"ERROR\n") |
| 2610 |
except OSError: |
| 2611 |
pass |
| 2612 |
self.close() |
| 2613 |
self.running = False |
| 2614 |
|
| 2615 |
def __init__(self, certificate=None, ssl_version=None, |
| 2616 |
certreqs=None, cacerts=None, |
| 2617 |
chatty=True, connectionchatty=False, starttls_server=False, |
| 2618 |
alpn_protocols=None, |
| 2619 |
ciphers=None, context=None): |
| 2620 |
if context: |
| 2621 |
self.context = context |
| 2622 |
else: |
| 2623 |
self.context = ssl.SSLContext(ssl_version |
| 2624 |
if ssl_version is not None |
| 2625 |
else ssl.PROTOCOL_TLS_SERVER) |
| 2626 |
self.context.verify_mode = (certreqs if certreqs is not None |
| 2627 |
else ssl.CERT_NONE) |
| 2628 |
if cacerts: |
| 2629 |
self.context.load_verify_locations(cacerts) |
| 2630 |
if certificate: |
| 2631 |
self.context.load_cert_chain(certificate) |
| 2632 |
if alpn_protocols: |
| 2633 |
self.context.set_alpn_protocols(alpn_protocols) |
| 2634 |
if ciphers: |
| 2635 |
self.context.set_ciphers(ciphers) |
| 2636 |
self.chatty = chatty |
| 2637 |
self.connectionchatty = connectionchatty |
| 2638 |
self.starttls_server = starttls_server |
| 2639 |
self.sock = socket.socket() |
| 2640 |
self.port = socket_helper.bind_port(self.sock) |
| 2641 |
self.flag = None |
| 2642 |
self.active = False |
| 2643 |
self.selected_alpn_protocols = [] |
| 2644 |
self.shared_ciphers = [] |
| 2645 |
self.conn_errors = [] |
| 2646 |
threading.Thread.__init__(self) |
| 2647 |
self.daemon = True |
| 2648 |
self._in_context = False |
| 2649 |
|
| 2650 |
def __enter__(self): |
| 2651 |
if self._in_context: |
| 2652 |
raise ValueError('Re-entering ThreadedEchoServer context') |
| 2653 |
self._in_context = True |
| 2654 |
self.start(threading.Event()) |
| 2655 |
self.flag.wait() |
| 2656 |
return self |
| 2657 |
|
| 2658 |
def __exit__(self, *args): |
| 2659 |
assert self._in_context |
| 2660 |
self._in_context = False |
| 2661 |
self.stop() |
| 2662 |
self.join() |
| 2663 |
|
| 2664 |
def start(self, flag=None): |
| 2665 |
if not self._in_context: |
| 2666 |
raise ValueError( |
| 2667 |
'ThreadedEchoServer must be used as a context manager') |
| 2668 |
self.flag = flag |
| 2669 |
threading.Thread.start(self) |
| 2670 |
|
| 2671 |
def run(self): |
| 2672 |
if not self._in_context: |
| 2673 |
raise ValueError( |
| 2674 |
'ThreadedEchoServer must be used as a context manager') |
| 2675 |
self.sock.settimeout(1.0) |
| 2676 |
self.sock.listen(5) |
| 2677 |
self.active = True |
| 2678 |
if self.flag: |
| 2679 |
# signal an event |
| 2680 |
self.flag.set() |
| 2681 |
while self.active: |
| 2682 |
try: |
| 2683 |
newconn, connaddr = self.sock.accept() |
| 2684 |
if support.verbose and self.chatty: |
| 2685 |
sys.stdout.write(' server: new connection from ' |
| 2686 |
+ repr(connaddr) + '\n') |
| 2687 |
handler = self.ConnectionHandler(self, newconn, connaddr) |
| 2688 |
handler.start() |
| 2689 |
handler.join() |
| 2690 |
except TimeoutError as e: |
| 2691 |
if support.verbose: |
| 2692 |
sys.stdout.write(f' connection timeout {e!r}\n') |
| 2693 |
except KeyboardInterrupt: |
| 2694 |
self.stop() |
| 2695 |
except BaseException as e: |
| 2696 |
if support.verbose and self.chatty: |
| 2697 |
sys.stdout.write( |
| 2698 |
' connection handling failed: ' + repr(e) + '\n') |
| 2699 |
|
| 2700 |
self.close() |
| 2701 |
|
| 2702 |
def close(self): |
| 2703 |
if self.sock is not None: |
| 2704 |
self.sock.close() |
| 2705 |
self.sock = None |
| 2706 |
|
| 2707 |
def stop(self): |
| 2708 |
self.active = False |
| 2709 |
|
| 2710 |
class AsyncoreEchoServer(threading.Thread): |
| 2711 |
|
| 2712 |
# this one's based on asyncore.dispatcher |
| 2713 |
|
| 2714 |
class EchoServer (asyncore.dispatcher): |
| 2715 |
|
| 2716 |
class ConnectionHandler(asyncore.dispatcher_with_send): |
| 2717 |
|
| 2718 |
def __init__(self, conn, certfile): |
| 2719 |
self.socket = test_wrap_socket(conn, server_side=True, |
| 2720 |
certfile=certfile, |
| 2721 |
do_handshake_on_connect=False) |
| 2722 |
asyncore.dispatcher_with_send.__init__(self, self.socket) |
| 2723 |
self._ssl_accepting = True |
| 2724 |
self._do_ssl_handshake() |
| 2725 |
|
| 2726 |
def readable(self): |
| 2727 |
if isinstance(self.socket, ssl.SSLSocket): |
| 2728 |
while self.socket.pending() > 0: |
| 2729 |
self.handle_read_event() |
| 2730 |
return True |
| 2731 |
|
| 2732 |
def _do_ssl_handshake(self): |
| 2733 |
try: |
| 2734 |
self.socket.do_handshake() |
| 2735 |
except (ssl.SSLWantReadError, ssl.SSLWantWriteError): |
| 2736 |
return |
| 2737 |
except ssl.SSLEOFError: |
| 2738 |
return self.handle_close() |
| 2739 |
except ssl.SSLError: |
| 2740 |
raise |
| 2741 |
except OSError as err: |
| 2742 |
if err.args[0] == errno.ECONNABORTED: |
| 2743 |
return self.handle_close() |
| 2744 |
else: |
| 2745 |
self._ssl_accepting = False |
| 2746 |
|
| 2747 |
def handle_read(self): |
| 2748 |
if self._ssl_accepting: |
| 2749 |
self._do_ssl_handshake() |
| 2750 |
else: |
| 2751 |
data = self.recv(1024) |
| 2752 |
if support.verbose: |
| 2753 |
sys.stdout.write(" server: read %s from client\n" % repr(data)) |
| 2754 |
if not data: |
| 2755 |
self.close() |
| 2756 |
else: |
| 2757 |
self.send(data.lower()) |
| 2758 |
|
| 2759 |
def handle_close(self): |
| 2760 |
self.close() |
| 2761 |
if support.verbose: |
| 2762 |
sys.stdout.write(" server: closed connection %s\n" % self.socket) |
| 2763 |
|
| 2764 |
def handle_error(self): |
| 2765 |
raise |
| 2766 |
|
| 2767 |
def __init__(self, certfile): |
| 2768 |
self.certfile = certfile |
| 2769 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 2770 |
self.port = socket_helper.bind_port(sock, '') |
| 2771 |
asyncore.dispatcher.__init__(self, sock) |
| 2772 |
self.listen(5) |
| 2773 |
|
| 2774 |
def handle_accepted(self, sock_obj, addr): |
| 2775 |
if support.verbose: |
| 2776 |
sys.stdout.write(" server: new connection from %s:%s\n" %addr) |
| 2777 |
self.ConnectionHandler(sock_obj, self.certfile) |
| 2778 |
|
| 2779 |
def handle_error(self): |
| 2780 |
raise |
| 2781 |
|
| 2782 |
def __init__(self, certfile): |
| 2783 |
self.flag = None |
| 2784 |
self.active = False |
| 2785 |
self.server = self.EchoServer(certfile) |
| 2786 |
self.port = self.server.port |
| 2787 |
threading.Thread.__init__(self) |
| 2788 |
self.daemon = True |
| 2789 |
|
| 2790 |
def __str__(self): |
| 2791 |
return "<%s %s>" % (self.__class__.__name__, self.server) |
| 2792 |
|
| 2793 |
def __enter__(self): |
| 2794 |
self.start(threading.Event()) |
| 2795 |
self.flag.wait() |
| 2796 |
return self |
| 2797 |
|
| 2798 |
def __exit__(self, *args): |
| 2799 |
if support.verbose: |
| 2800 |
sys.stdout.write(" cleanup: stopping server.\n") |
| 2801 |
self.stop() |
| 2802 |
if support.verbose: |
| 2803 |
sys.stdout.write(" cleanup: joining server thread.\n") |
| 2804 |
self.join() |
| 2805 |
if support.verbose: |
| 2806 |
sys.stdout.write(" cleanup: successfully joined.\n") |
| 2807 |
# make sure that ConnectionHandler is removed from socket_map |
| 2808 |
asyncore.close_all(ignore_all=True) |
| 2809 |
|
| 2810 |
def start (self, flag=None): |
| 2811 |
self.flag = flag |
| 2812 |
threading.Thread.start(self) |
| 2813 |
|
| 2814 |
def run(self): |
| 2815 |
self.active = True |
| 2816 |
if self.flag: |
| 2817 |
self.flag.set() |
| 2818 |
while self.active: |
| 2819 |
try: |
| 2820 |
asyncore.loop(1) |
| 2821 |
except: |
| 2822 |
pass |
| 2823 |
|
| 2824 |
def stop(self): |
| 2825 |
self.active = False |
| 2826 |
self.server.close() |
| 2827 |
|
| 2828 |
def server_params_test(client_context, server_context, indata=b"FOO\n", |
| 2829 |
chatty=True, connectionchatty=False, sni_name=None, |
| 2830 |
session=None): |
| 2831 |
""" |
| 2832 |
Launch a server, connect a client to it and try various reads |
| 2833 |
and writes. |
| 2834 |
""" |
| 2835 |
stats = {} |
| 2836 |
server = ThreadedEchoServer(context=server_context, |
| 2837 |
chatty=chatty, |
| 2838 |
connectionchatty=False) |
| 2839 |
with server: |
| 2840 |
with client_context.wrap_socket(socket.socket(), |
| 2841 |
server_hostname=sni_name, session=session) as s: |
| 2842 |
s.connect((HOST, server.port)) |
| 2843 |
for arg in [indata, bytearray(indata), memoryview(indata)]: |
| 2844 |
if connectionchatty: |
| 2845 |
if support.verbose: |
| 2846 |
sys.stdout.write( |
| 2847 |
" client: sending %r...\n" % indata) |
| 2848 |
s.write(arg) |
| 2849 |
outdata = s.read() |
| 2850 |
if connectionchatty: |
| 2851 |
if support.verbose: |
| 2852 |
sys.stdout.write(" client: read %r\n" % outdata) |
| 2853 |
if outdata != indata.lower(): |
| 2854 |
raise AssertionError( |
| 2855 |
"bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 2856 |
% (outdata[:20], len(outdata), |
| 2857 |
indata[:20].lower(), len(indata))) |
| 2858 |
s.write(b"over\n") |
| 2859 |
if connectionchatty: |
| 2860 |
if support.verbose: |
| 2861 |
sys.stdout.write(" client: closing connection.\n") |
| 2862 |
stats.update({ |
| 2863 |
'compression': s.compression(), |
| 2864 |
'cipher': s.cipher(), |
| 2865 |
'peercert': s.getpeercert(), |
| 2866 |
'client_alpn_protocol': s.selected_alpn_protocol(), |
| 2867 |
'version': s.version(), |
| 2868 |
'session_reused': s.session_reused, |
| 2869 |
'session': s.session, |
| 2870 |
}) |
| 2871 |
s.close() |
| 2872 |
stats['server_alpn_protocols'] = server.selected_alpn_protocols |
| 2873 |
stats['server_shared_ciphers'] = server.shared_ciphers |
| 2874 |
return stats |
| 2875 |
|
| 2876 |
def try_protocol_combo(server_protocol, client_protocol, expect_success, |
| 2877 |
certsreqs=None, server_options=0, client_options=0): |
| 2878 |
""" |
| 2879 |
Try to SSL-connect using *client_protocol* to *server_protocol*. |
| 2880 |
If *expect_success* is true, assert that the connection succeeds, |
| 2881 |
if it's false, assert that the connection fails. |
| 2882 |
Also, if *expect_success* is a string, assert that it is the protocol |
| 2883 |
version actually used by the connection. |
| 2884 |
""" |
| 2885 |
if certsreqs is None: |
| 2886 |
certsreqs = ssl.CERT_NONE |
| 2887 |
certtype = { |
| 2888 |
ssl.CERT_NONE: "CERT_NONE", |
| 2889 |
ssl.CERT_OPTIONAL: "CERT_OPTIONAL", |
| 2890 |
ssl.CERT_REQUIRED: "CERT_REQUIRED", |
| 2891 |
}[certsreqs] |
| 2892 |
if support.verbose: |
| 2893 |
formatstr = (expect_success and " %s->%s %s\n") or " {%s->%s} %s\n" |
| 2894 |
sys.stdout.write(formatstr % |
| 2895 |
(ssl.get_protocol_name(client_protocol), |
| 2896 |
ssl.get_protocol_name(server_protocol), |
| 2897 |
certtype)) |
| 2898 |
|
| 2899 |
with warnings_helper.check_warnings(): |
| 2900 |
# ignore Deprecation warnings |
| 2901 |
client_context = ssl.SSLContext(client_protocol) |
| 2902 |
client_context.options |= client_options |
| 2903 |
server_context = ssl.SSLContext(server_protocol) |
| 2904 |
server_context.options |= server_options |
| 2905 |
|
| 2906 |
min_version = PROTOCOL_TO_TLS_VERSION.get(client_protocol, None) |
| 2907 |
if (min_version is not None |
| 2908 |
# SSLContext.minimum_version is only available on recent OpenSSL |
| 2909 |
# (setter added in OpenSSL 1.1.0, getter added in OpenSSL 1.1.1) |
| 2910 |
and hasattr(server_context, 'minimum_version') |
| 2911 |
and server_protocol == ssl.PROTOCOL_TLS |
| 2912 |
and server_context.minimum_version > min_version |
| 2913 |
): |
| 2914 |
# If OpenSSL configuration is strict and requires more recent TLS |
| 2915 |
# version, we have to change the minimum to test old TLS versions. |
| 2916 |
with warnings_helper.check_warnings(): |
| 2917 |
server_context.minimum_version = min_version |
| 2918 |
|
| 2919 |
# NOTE: we must enable "ALL" ciphers on the client, otherwise an |
| 2920 |
# SSLv23 client will send an SSLv3 hello (rather than SSLv2) |
| 2921 |
# starting from OpenSSL 1.0.0 (see issue #8322). |
| 2922 |
if client_context.protocol == ssl.PROTOCOL_TLS: |
| 2923 |
client_context.set_ciphers("ALL") |
| 2924 |
|
| 2925 |
seclevel_workaround(server_context, client_context) |
| 2926 |
|
| 2927 |
for ctx in (client_context, server_context): |
| 2928 |
ctx.verify_mode = certsreqs |
| 2929 |
ctx.load_cert_chain(SIGNED_CERTFILE) |
| 2930 |
ctx.load_verify_locations(SIGNING_CA) |
| 2931 |
try: |
| 2932 |
stats = server_params_test(client_context, server_context, |
| 2933 |
chatty=False, connectionchatty=False) |
| 2934 |
# Protocol mismatch can result in either an SSLError, or a |
| 2935 |
# "Connection reset by peer" error. |
| 2936 |
except ssl.SSLError: |
| 2937 |
if expect_success: |
| 2938 |
raise |
| 2939 |
except OSError as e: |
| 2940 |
if expect_success or e.errno != errno.ECONNRESET: |
| 2941 |
raise |
| 2942 |
else: |
| 2943 |
if not expect_success: |
| 2944 |
raise AssertionError( |
| 2945 |
"Client protocol %s succeeded with server protocol %s!" |
| 2946 |
% (ssl.get_protocol_name(client_protocol), |
| 2947 |
ssl.get_protocol_name(server_protocol))) |
| 2948 |
elif (expect_success is not True |
| 2949 |
and expect_success != stats['version']): |
| 2950 |
raise AssertionError("version mismatch: expected %r, got %r" |
| 2951 |
% (expect_success, stats['version'])) |
| 2952 |
|
| 2953 |
|
| 2954 |
def supports_kx_alias(ctx, aliases): |
| 2955 |
for cipher in ctx.get_ciphers(): |
| 2956 |
for alias in aliases: |
| 2957 |
if f"Kx={alias}" in cipher['description']: |
| 2958 |
return True |
| 2959 |
return False |
| 2960 |
|
| 2961 |
|
| 2962 |
class ThreadedTests(unittest.TestCase): |
| 2963 |
|
| 2964 |
@support.requires_resource('walltime') |
| 2965 |
def test_echo(self): |
| 2966 |
"""Basic test of an SSL client connecting to a server""" |
| 2967 |
if support.verbose: |
| 2968 |
sys.stdout.write("\n") |
| 2969 |
|
| 2970 |
client_context, server_context, hostname = testing_context() |
| 2971 |
|
| 2972 |
with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_SERVER): |
| 2973 |
server_params_test(client_context=client_context, |
| 2974 |
server_context=server_context, |
| 2975 |
chatty=True, connectionchatty=True, |
| 2976 |
sni_name=hostname) |
| 2977 |
|
| 2978 |
client_context.check_hostname = False |
| 2979 |
with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_CLIENT): |
| 2980 |
with self.assertRaises(ssl.SSLError) as e: |
| 2981 |
server_params_test(client_context=server_context, |
| 2982 |
server_context=client_context, |
| 2983 |
chatty=True, connectionchatty=True, |
| 2984 |
sni_name=hostname) |
| 2985 |
self.assertIn( |
| 2986 |
'Cannot create a client socket with a PROTOCOL_TLS_SERVER context', |
| 2987 |
str(e.exception) |
| 2988 |
) |
| 2989 |
|
| 2990 |
with self.subTest(client=ssl.PROTOCOL_TLS_SERVER, server=ssl.PROTOCOL_TLS_SERVER): |
| 2991 |
with self.assertRaises(ssl.SSLError) as e: |
| 2992 |
server_params_test(client_context=server_context, |
| 2993 |
server_context=server_context, |
| 2994 |
chatty=True, connectionchatty=True) |
| 2995 |
self.assertIn( |
| 2996 |
'Cannot create a client socket with a PROTOCOL_TLS_SERVER context', |
| 2997 |
str(e.exception) |
| 2998 |
) |
| 2999 |
|
| 3000 |
with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server=ssl.PROTOCOL_TLS_CLIENT): |
| 3001 |
with self.assertRaises(ssl.SSLError) as e: |
| 3002 |
server_params_test(client_context=server_context, |
| 3003 |
server_context=client_context, |
| 3004 |
chatty=True, connectionchatty=True) |
| 3005 |
self.assertIn( |
| 3006 |
'Cannot create a client socket with a PROTOCOL_TLS_SERVER context', |
| 3007 |
str(e.exception)) |
| 3008 |
|
| 3009 |
@unittest.skipUnless(support.Py_GIL_DISABLED, "test is only useful if the GIL is disabled") |
| 3010 |
def test_ssl_in_multiple_threads(self): |
| 3011 |
# See GH-124984: OpenSSL is not thread safe. |
| 3012 |
threads = [] |
| 3013 |
|
| 3014 |
warnings_filters = sys.flags.context_aware_warnings |
| 3015 |
global USE_SAME_TEST_CONTEXT |
| 3016 |
USE_SAME_TEST_CONTEXT = True |
| 3017 |
try: |
| 3018 |
for func in ( |
| 3019 |
self.test_echo, |
| 3020 |
self.test_alpn_protocols, |
| 3021 |
self.test_getpeercert, |
| 3022 |
self.test_crl_check, |
| 3023 |
functools.partial( |
| 3024 |
self.test_check_hostname_idn, |
| 3025 |
warnings_filters=warnings_filters, |
| 3026 |
), |
| 3027 |
self.test_wrong_cert_tls12, |
| 3028 |
self.test_wrong_cert_tls13, |
| 3029 |
): |
| 3030 |
# Be careful with the number of threads here. |
| 3031 |
# Too many can result in failing tests. |
| 3032 |
for num in range(5): |
| 3033 |
with self.subTest(func=func, num=num): |
| 3034 |
threads.append(Thread(target=func)) |
| 3035 |
|
| 3036 |
with threading_helper.catch_threading_exception() as cm: |
| 3037 |
for thread in threads: |
| 3038 |
with self.subTest(thread=thread): |
| 3039 |
thread.start() |
| 3040 |
|
| 3041 |
for thread in threads: |
| 3042 |
with self.subTest(thread=thread): |
| 3043 |
thread.join() |
| 3044 |
if cm.exc_value is not None: |
| 3045 |
# Some threads can skip their test |
| 3046 |
if not isinstance(cm.exc_value, unittest.SkipTest): |
| 3047 |
raise cm.exc_value |
| 3048 |
finally: |
| 3049 |
USE_SAME_TEST_CONTEXT = False |
| 3050 |
|
| 3051 |
def test_getpeercert(self): |
| 3052 |
if support.verbose: |
| 3053 |
sys.stdout.write("\n") |
| 3054 |
|
| 3055 |
client_context, server_context, hostname = testing_context() |
| 3056 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 3057 |
with server: |
| 3058 |
with client_context.wrap_socket(socket.socket(), |
| 3059 |
do_handshake_on_connect=False, |
| 3060 |
server_hostname=hostname) as s: |
| 3061 |
s.connect((HOST, server.port)) |
| 3062 |
# getpeercert() raise ValueError while the handshake isn't |
| 3063 |
# done. |
| 3064 |
with self.assertRaises(ValueError): |
| 3065 |
s.getpeercert() |
| 3066 |
s.do_handshake() |
| 3067 |
cert = s.getpeercert() |
| 3068 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3069 |
cipher = s.cipher() |
| 3070 |
if support.verbose: |
| 3071 |
sys.stdout.write(pprint.pformat(cert) + '\n') |
| 3072 |
sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') |
| 3073 |
if 'subject' not in cert: |
| 3074 |
self.fail("No subject field in certificate: %s." % |
| 3075 |
pprint.pformat(cert)) |
| 3076 |
if ((('organizationName', 'Python Software Foundation'),) |
| 3077 |
not in cert['subject']): |
| 3078 |
self.fail( |
| 3079 |
"Missing or invalid 'organizationName' field in certificate subject; " |
| 3080 |
"should be 'Python Software Foundation'.") |
| 3081 |
self.assertIn('notBefore', cert) |
| 3082 |
self.assertIn('notAfter', cert) |
| 3083 |
before = ssl.cert_time_to_seconds(cert['notBefore']) |
| 3084 |
after = ssl.cert_time_to_seconds(cert['notAfter']) |
| 3085 |
self.assertLess(before, after) |
| 3086 |
|
| 3087 |
def test_crl_check(self): |
| 3088 |
if support.verbose: |
| 3089 |
sys.stdout.write("\n") |
| 3090 |
|
| 3091 |
client_context, server_context, hostname = testing_context() |
| 3092 |
|
| 3093 |
tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0) |
| 3094 |
self.assertEqual(client_context.verify_flags, ssl.VERIFY_DEFAULT | tf) |
| 3095 |
|
| 3096 |
# VERIFY_DEFAULT should pass |
| 3097 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3098 |
with server: |
| 3099 |
with client_context.wrap_socket(socket.socket(), |
| 3100 |
server_hostname=hostname) as s: |
| 3101 |
s.connect((HOST, server.port)) |
| 3102 |
cert = s.getpeercert() |
| 3103 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3104 |
|
| 3105 |
# VERIFY_CRL_CHECK_LEAF without a loaded CRL file fails |
| 3106 |
client_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF |
| 3107 |
|
| 3108 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3109 |
# Allow for flexible libssl error messages. |
| 3110 |
regex = re.compile(r"""( |
| 3111 |
certificate verify failed # OpenSSL |
| 3112 |
| |
| 3113 |
CERTIFICATE_VERIFY_FAILED # AWS-LC |
| 3114 |
)""", re.X) |
| 3115 |
with server: |
| 3116 |
with client_context.wrap_socket(socket.socket(), |
| 3117 |
server_hostname=hostname) as s: |
| 3118 |
with self.assertRaisesRegex(ssl.SSLError, regex): |
| 3119 |
s.connect((HOST, server.port)) |
| 3120 |
|
| 3121 |
# now load a CRL file. The CRL file is signed by the CA. |
| 3122 |
client_context.load_verify_locations(CRLFILE) |
| 3123 |
|
| 3124 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3125 |
with server: |
| 3126 |
with client_context.wrap_socket(socket.socket(), |
| 3127 |
server_hostname=hostname) as s: |
| 3128 |
s.connect((HOST, server.port)) |
| 3129 |
cert = s.getpeercert() |
| 3130 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3131 |
|
| 3132 |
def test_check_hostname(self): |
| 3133 |
if support.verbose: |
| 3134 |
sys.stdout.write("\n") |
| 3135 |
|
| 3136 |
client_context, server_context, hostname = testing_context() |
| 3137 |
|
| 3138 |
# correct hostname should verify |
| 3139 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3140 |
with server: |
| 3141 |
with client_context.wrap_socket(socket.socket(), |
| 3142 |
server_hostname=hostname) as s: |
| 3143 |
s.connect((HOST, server.port)) |
| 3144 |
cert = s.getpeercert() |
| 3145 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3146 |
|
| 3147 |
# incorrect hostname should raise an exception |
| 3148 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3149 |
# Allow for flexible libssl error messages. |
| 3150 |
regex = re.compile(r"""( |
| 3151 |
certificate verify failed # OpenSSL |
| 3152 |
| |
| 3153 |
CERTIFICATE_VERIFY_FAILED # AWS-LC |
| 3154 |
)""", re.X) |
| 3155 |
with server: |
| 3156 |
with client_context.wrap_socket(socket.socket(), |
| 3157 |
server_hostname="invalid") as s: |
| 3158 |
with self.assertRaisesRegex(ssl.CertificateError, regex): |
| 3159 |
s.connect((HOST, server.port)) |
| 3160 |
|
| 3161 |
# missing server_hostname arg should cause an exception, too |
| 3162 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3163 |
with server: |
| 3164 |
with socket.socket() as s: |
| 3165 |
with self.assertRaisesRegex(ValueError, |
| 3166 |
"check_hostname requires server_hostname"): |
| 3167 |
client_context.wrap_socket(s) |
| 3168 |
|
| 3169 |
@unittest.skipUnless( |
| 3170 |
ssl.HAS_NEVER_CHECK_COMMON_NAME, "test requires hostname_checks_common_name" |
| 3171 |
) |
| 3172 |
def test_hostname_checks_common_name(self): |
| 3173 |
client_context, server_context, hostname = testing_context() |
| 3174 |
assert client_context.hostname_checks_common_name |
| 3175 |
client_context.hostname_checks_common_name = False |
| 3176 |
|
| 3177 |
# default cert has a SAN |
| 3178 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3179 |
with server: |
| 3180 |
with client_context.wrap_socket(socket.socket(), |
| 3181 |
server_hostname=hostname) as s: |
| 3182 |
s.connect((HOST, server.port)) |
| 3183 |
|
| 3184 |
client_context, server_context, hostname = testing_context(NOSANFILE) |
| 3185 |
client_context.hostname_checks_common_name = False |
| 3186 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3187 |
with server: |
| 3188 |
with client_context.wrap_socket(socket.socket(), |
| 3189 |
server_hostname=hostname) as s: |
| 3190 |
with self.assertRaises(ssl.SSLCertVerificationError): |
| 3191 |
s.connect((HOST, server.port)) |
| 3192 |
|
| 3193 |
def test_ecc_cert(self): |
| 3194 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 3195 |
client_context.load_verify_locations(SIGNING_CA) |
| 3196 |
client_context.set_ciphers('ECDHE:ECDSA:!NULL:!aRSA') |
| 3197 |
hostname = SIGNED_CERTFILE_ECC_HOSTNAME |
| 3198 |
|
| 3199 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 3200 |
# load ECC cert |
| 3201 |
server_context.load_cert_chain(SIGNED_CERTFILE_ECC) |
| 3202 |
|
| 3203 |
# correct hostname should verify |
| 3204 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3205 |
with server: |
| 3206 |
with client_context.wrap_socket(socket.socket(), |
| 3207 |
server_hostname=hostname) as s: |
| 3208 |
s.connect((HOST, server.port)) |
| 3209 |
cert = s.getpeercert() |
| 3210 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3211 |
cipher = s.cipher()[0].split('-') |
| 3212 |
self.assertTrue(cipher[:2], ('ECDHE', 'ECDSA')) |
| 3213 |
|
| 3214 |
@unittest.skipUnless(IS_OPENSSL_3_0_0, |
| 3215 |
"test requires RFC 5280 check added in OpenSSL 3.0+") |
| 3216 |
def test_verify_strict(self): |
| 3217 |
# verification fails by default, since the server cert is non-conforming |
| 3218 |
client_context = ssl.create_default_context() |
| 3219 |
client_context.load_verify_locations(LEAF_MISSING_AKI_CA) |
| 3220 |
hostname = LEAF_MISSING_AKI_CERTFILE_HOSTNAME |
| 3221 |
|
| 3222 |
server_context = ssl.create_default_context(purpose=Purpose.CLIENT_AUTH) |
| 3223 |
server_context.load_cert_chain(LEAF_MISSING_AKI_CERTFILE) |
| 3224 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3225 |
with server: |
| 3226 |
with client_context.wrap_socket(socket.socket(), |
| 3227 |
server_hostname=hostname) as s: |
| 3228 |
with self.assertRaises(ssl.SSLError): |
| 3229 |
s.connect((HOST, server.port)) |
| 3230 |
|
| 3231 |
# explicitly disabling VERIFY_X509_STRICT allows it to succeed |
| 3232 |
client_context = ssl.create_default_context() |
| 3233 |
client_context.load_verify_locations(LEAF_MISSING_AKI_CA) |
| 3234 |
client_context.verify_flags &= ~ssl.VERIFY_X509_STRICT |
| 3235 |
|
| 3236 |
server_context = ssl.create_default_context(purpose=Purpose.CLIENT_AUTH) |
| 3237 |
server_context.load_cert_chain(LEAF_MISSING_AKI_CERTFILE) |
| 3238 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3239 |
with server: |
| 3240 |
with client_context.wrap_socket(socket.socket(), |
| 3241 |
server_hostname=hostname) as s: |
| 3242 |
s.connect((HOST, server.port)) |
| 3243 |
cert = s.getpeercert() |
| 3244 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3245 |
|
| 3246 |
def test_dual_rsa_ecc(self): |
| 3247 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 3248 |
client_context.load_verify_locations(SIGNING_CA) |
| 3249 |
# TODO: fix TLSv1.3 once SSLContext can restrict signature |
| 3250 |
# algorithms. |
| 3251 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 3252 |
# only ECDSA certs |
| 3253 |
client_context.set_ciphers('ECDHE:ECDSA:!NULL:!aRSA') |
| 3254 |
hostname = SIGNED_CERTFILE_ECC_HOSTNAME |
| 3255 |
|
| 3256 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 3257 |
# load ECC and RSA key/cert pairs |
| 3258 |
server_context.load_cert_chain(SIGNED_CERTFILE_ECC) |
| 3259 |
server_context.load_cert_chain(SIGNED_CERTFILE) |
| 3260 |
|
| 3261 |
# correct hostname should verify |
| 3262 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3263 |
with server: |
| 3264 |
with client_context.wrap_socket(socket.socket(), |
| 3265 |
server_hostname=hostname) as s: |
| 3266 |
s.connect((HOST, server.port)) |
| 3267 |
cert = s.getpeercert() |
| 3268 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3269 |
cipher = s.cipher()[0].split('-') |
| 3270 |
self.assertTrue(cipher[:2], ('ECDHE', 'ECDSA')) |
| 3271 |
|
| 3272 |
def test_check_hostname_idn(self, warnings_filters=True): |
| 3273 |
if support.verbose: |
| 3274 |
sys.stdout.write("\n") |
| 3275 |
|
| 3276 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 3277 |
server_context.load_cert_chain(IDNSANSFILE) |
| 3278 |
|
| 3279 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 3280 |
context.verify_mode = ssl.CERT_REQUIRED |
| 3281 |
context.check_hostname = True |
| 3282 |
context.load_verify_locations(SIGNING_CA) |
| 3283 |
|
| 3284 |
# correct hostname should verify, when specified in several |
| 3285 |
# different ways |
| 3286 |
idn_hostnames = [ |
| 3287 |
('könig.idn.pythontest.net', |
| 3288 |
'xn--knig-5qa.idn.pythontest.net'), |
| 3289 |
('xn--knig-5qa.idn.pythontest.net', |
| 3290 |
'xn--knig-5qa.idn.pythontest.net'), |
| 3291 |
(b'xn--knig-5qa.idn.pythontest.net', |
| 3292 |
'xn--knig-5qa.idn.pythontest.net'), |
| 3293 |
|
| 3294 |
('königsgäßchen.idna2003.pythontest.net', |
| 3295 |
'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), |
| 3296 |
('xn--knigsgsschen-lcb0w.idna2003.pythontest.net', |
| 3297 |
'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), |
| 3298 |
(b'xn--knigsgsschen-lcb0w.idna2003.pythontest.net', |
| 3299 |
'xn--knigsgsschen-lcb0w.idna2003.pythontest.net'), |
| 3300 |
|
| 3301 |
# ('königsgäßchen.idna2008.pythontest.net', |
| 3302 |
# 'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), |
| 3303 |
('xn--knigsgchen-b4a3dun.idna2008.pythontest.net', |
| 3304 |
'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), |
| 3305 |
(b'xn--knigsgchen-b4a3dun.idna2008.pythontest.net', |
| 3306 |
'xn--knigsgchen-b4a3dun.idna2008.pythontest.net'), |
| 3307 |
|
| 3308 |
] |
| 3309 |
for server_hostname, expected_hostname in idn_hostnames: |
| 3310 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3311 |
with server: |
| 3312 |
with context.wrap_socket(socket.socket(), |
| 3313 |
server_hostname=server_hostname) as s: |
| 3314 |
self.assertEqual(s.server_hostname, expected_hostname) |
| 3315 |
s.connect((HOST, server.port)) |
| 3316 |
cert = s.getpeercert() |
| 3317 |
self.assertEqual(s.server_hostname, expected_hostname) |
| 3318 |
self.assertTrue(cert, "Can't get peer certificate.") |
| 3319 |
|
| 3320 |
# incorrect hostname should raise an exception |
| 3321 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3322 |
with server: |
| 3323 |
with context.wrap_socket(socket.socket(), |
| 3324 |
server_hostname="python.example.org") as s: |
| 3325 |
with self.assertRaises(ssl.CertificateError): |
| 3326 |
s.connect((HOST, server.port)) |
| 3327 |
with ( |
| 3328 |
ThreadedEchoServer(context=server_context, chatty=True) as server, |
| 3329 |
( |
| 3330 |
warnings_helper.check_no_resource_warning(self) |
| 3331 |
if warnings_filters |
| 3332 |
else nullcontext() |
| 3333 |
), |
| 3334 |
self.assertRaises(UnicodeError), |
| 3335 |
): |
| 3336 |
context.wrap_socket(socket.socket(), server_hostname='.pythontest.net') |
| 3337 |
|
| 3338 |
with ( |
| 3339 |
ThreadedEchoServer(context=server_context, chatty=True) as server, |
| 3340 |
( |
| 3341 |
warnings_helper.check_no_resource_warning(self) |
| 3342 |
if warnings_filters |
| 3343 |
else nullcontext() |
| 3344 |
), |
| 3345 |
self.assertRaises(UnicodeDecodeError), |
| 3346 |
): |
| 3347 |
context.wrap_socket( |
| 3348 |
socket.socket(), |
| 3349 |
server_hostname=b'k\xf6nig.idn.pythontest.net', |
| 3350 |
) |
| 3351 |
|
| 3352 |
def test_wrong_cert_tls12(self): |
| 3353 |
"""Connecting when the server rejects the client's certificate |
| 3354 |
|
| 3355 |
Launch a server with CERT_REQUIRED, and check that trying to |
| 3356 |
connect to it with a wrong client certificate fails. |
| 3357 |
""" |
| 3358 |
client_context, server_context, hostname = testing_context() |
| 3359 |
# load client cert that is not signed by trusted CA |
| 3360 |
client_context.load_cert_chain(CERTFILE) |
| 3361 |
# require TLS client authentication |
| 3362 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 3363 |
# TLS 1.3 has different handshake |
| 3364 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 3365 |
|
| 3366 |
server = ThreadedEchoServer( |
| 3367 |
context=server_context, chatty=True, connectionchatty=True, |
| 3368 |
) |
| 3369 |
|
| 3370 |
with server, \ |
| 3371 |
client_context.wrap_socket(socket.socket(), |
| 3372 |
server_hostname=hostname) as s: |
| 3373 |
try: |
| 3374 |
# Expect either an SSL error about the server rejecting |
| 3375 |
# the connection, or a low-level connection reset (which |
| 3376 |
# sometimes happens on Windows) |
| 3377 |
s.connect((HOST, server.port)) |
| 3378 |
except ssl.SSLError as e: |
| 3379 |
if support.verbose: |
| 3380 |
sys.stdout.write("\nSSLError is %r\n" % e) |
| 3381 |
except OSError as e: |
| 3382 |
if e.errno != errno.ECONNRESET: |
| 3383 |
raise |
| 3384 |
if support.verbose: |
| 3385 |
sys.stdout.write("\nsocket.error is %r\n" % e) |
| 3386 |
else: |
| 3387 |
self.fail("Use of invalid cert should have failed!") |
| 3388 |
|
| 3389 |
@requires_tls_version('TLSv1_3') |
| 3390 |
def test_wrong_cert_tls13(self): |
| 3391 |
client_context, server_context, hostname = testing_context() |
| 3392 |
# load client cert that is not signed by trusted CA |
| 3393 |
client_context.load_cert_chain(CERTFILE) |
| 3394 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 3395 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_3 |
| 3396 |
client_context.minimum_version = ssl.TLSVersion.TLSv1_3 |
| 3397 |
|
| 3398 |
server = ThreadedEchoServer( |
| 3399 |
context=server_context, chatty=True, connectionchatty=True, |
| 3400 |
) |
| 3401 |
with server, \ |
| 3402 |
client_context.wrap_socket(socket.socket(), |
| 3403 |
server_hostname=hostname, |
| 3404 |
suppress_ragged_eofs=False) as s: |
| 3405 |
s.connect((HOST, server.port)) |
| 3406 |
with self.assertRaisesRegex( |
| 3407 |
OSError, |
| 3408 |
'alert unknown ca|EOF occurred|TLSV1_ALERT_UNKNOWN_CA|' |
| 3409 |
'closed by the remote host|Connection reset by peer|' |
| 3410 |
'Broken pipe' |
| 3411 |
): |
| 3412 |
# TLS 1.3 perform client cert exchange after handshake |
| 3413 |
s.write(b'data') |
| 3414 |
s.read(1000) |
| 3415 |
s.write(b'should have failed already') |
| 3416 |
s.read(1000) |
| 3417 |
|
| 3418 |
def test_rude_shutdown(self): |
| 3419 |
"""A brutal shutdown of an SSL server should raise an OSError |
| 3420 |
in the client when attempting handshake. |
| 3421 |
""" |
| 3422 |
listener_ready = threading.Event() |
| 3423 |
listener_gone = threading.Event() |
| 3424 |
|
| 3425 |
s = socket.socket() |
| 3426 |
port = socket_helper.bind_port(s, HOST) |
| 3427 |
|
| 3428 |
# `listener` runs in a thread. It sits in an accept() until |
| 3429 |
# the main thread connects. Then it rudely closes the socket, |
| 3430 |
# and sets Event `listener_gone` to let the main thread know |
| 3431 |
# the socket is gone. |
| 3432 |
def listener(): |
| 3433 |
s.listen() |
| 3434 |
listener_ready.set() |
| 3435 |
newsock, addr = s.accept() |
| 3436 |
newsock.close() |
| 3437 |
s.close() |
| 3438 |
listener_gone.set() |
| 3439 |
|
| 3440 |
def connector(): |
| 3441 |
listener_ready.wait() |
| 3442 |
with socket.socket() as c: |
| 3443 |
c.connect((HOST, port)) |
| 3444 |
listener_gone.wait() |
| 3445 |
try: |
| 3446 |
ssl_sock = test_wrap_socket(c) |
| 3447 |
except OSError: |
| 3448 |
pass |
| 3449 |
else: |
| 3450 |
self.fail('connecting to closed SSL socket should have failed') |
| 3451 |
|
| 3452 |
t = threading.Thread(target=listener) |
| 3453 |
t.start() |
| 3454 |
try: |
| 3455 |
connector() |
| 3456 |
finally: |
| 3457 |
t.join() |
| 3458 |
|
| 3459 |
def test_ssl_cert_verify_error(self): |
| 3460 |
if support.verbose: |
| 3461 |
sys.stdout.write("\n") |
| 3462 |
|
| 3463 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 3464 |
server_context.load_cert_chain(SIGNED_CERTFILE) |
| 3465 |
|
| 3466 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 3467 |
|
| 3468 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 3469 |
with server: |
| 3470 |
with context.wrap_socket(socket.socket(), |
| 3471 |
server_hostname=SIGNED_CERTFILE_HOSTNAME) as s: |
| 3472 |
try: |
| 3473 |
s.connect((HOST, server.port)) |
| 3474 |
self.fail("Expected connection failure") |
| 3475 |
except ssl.SSLError as e: |
| 3476 |
msg = 'unable to get local issuer certificate' |
| 3477 |
self.assertIsInstance(e, ssl.SSLCertVerificationError) |
| 3478 |
self.assertEqual(e.verify_code, 20) |
| 3479 |
self.assertEqual(e.verify_message, msg) |
| 3480 |
# Allow for flexible libssl error messages. |
| 3481 |
regex = f"({msg}|CERTIFICATE_VERIFY_FAILED)" |
| 3482 |
self.assertRegex(repr(e), regex) |
| 3483 |
regex = re.compile(r"""( |
| 3484 |
certificate verify failed # OpenSSL |
| 3485 |
| |
| 3486 |
CERTIFICATE_VERIFY_FAILED # AWS-LC |
| 3487 |
)""", re.X) |
| 3488 |
self.assertRegex(repr(e), regex) |
| 3489 |
|
| 3490 |
def test_PROTOCOL_TLS(self): |
| 3491 |
"""Connecting to an SSLv23 server with various client options""" |
| 3492 |
if support.verbose: |
| 3493 |
sys.stdout.write("\n") |
| 3494 |
if has_tls_version('SSLv3'): |
| 3495 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False) |
| 3496 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True) |
| 3497 |
if has_tls_version('TLSv1'): |
| 3498 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1') |
| 3499 |
|
| 3500 |
if has_tls_version('SSLv3'): |
| 3501 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, ssl.CERT_OPTIONAL) |
| 3502 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, ssl.CERT_OPTIONAL) |
| 3503 |
if has_tls_version('TLSv1'): |
| 3504 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) |
| 3505 |
|
| 3506 |
if has_tls_version('SSLv3'): |
| 3507 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, ssl.CERT_REQUIRED) |
| 3508 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, ssl.CERT_REQUIRED) |
| 3509 |
if has_tls_version('TLSv1'): |
| 3510 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) |
| 3511 |
|
| 3512 |
# Server with specific SSL options |
| 3513 |
if has_tls_version('SSLv3'): |
| 3514 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_SSLv3, False, |
| 3515 |
server_options=ssl.OP_NO_SSLv3) |
| 3516 |
# Will choose TLSv1 |
| 3517 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS, True, |
| 3518 |
server_options=ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) |
| 3519 |
if has_tls_version('TLSv1'): |
| 3520 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1, False, |
| 3521 |
server_options=ssl.OP_NO_TLSv1) |
| 3522 |
|
| 3523 |
@requires_tls_version('SSLv3') |
| 3524 |
def test_protocol_sslv3(self): |
| 3525 |
"""Connecting to an SSLv3 server with various client options""" |
| 3526 |
if support.verbose: |
| 3527 |
sys.stdout.write("\n") |
| 3528 |
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3') |
| 3529 |
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_OPTIONAL) |
| 3530 |
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, 'SSLv3', ssl.CERT_REQUIRED) |
| 3531 |
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLS, False, |
| 3532 |
client_options=ssl.OP_NO_SSLv3) |
| 3533 |
try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) |
| 3534 |
|
| 3535 |
@requires_tls_version('TLSv1') |
| 3536 |
def test_protocol_tlsv1(self): |
| 3537 |
"""Connecting to a TLSv1 server with various client options""" |
| 3538 |
if support.verbose: |
| 3539 |
sys.stdout.write("\n") |
| 3540 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1') |
| 3541 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_OPTIONAL) |
| 3542 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, 'TLSv1', ssl.CERT_REQUIRED) |
| 3543 |
if has_tls_version('SSLv3'): |
| 3544 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) |
| 3545 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLS, False, |
| 3546 |
client_options=ssl.OP_NO_TLSv1) |
| 3547 |
|
| 3548 |
@requires_tls_version('TLSv1_1') |
| 3549 |
def test_protocol_tlsv1_1(self): |
| 3550 |
"""Connecting to a TLSv1.1 server with various client options. |
| 3551 |
Testing against older TLS versions.""" |
| 3552 |
if support.verbose: |
| 3553 |
sys.stdout.write("\n") |
| 3554 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') |
| 3555 |
if has_tls_version('SSLv3'): |
| 3556 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_SSLv3, False) |
| 3557 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLS, False, |
| 3558 |
client_options=ssl.OP_NO_TLSv1_1) |
| 3559 |
|
| 3560 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_1, 'TLSv1.1') |
| 3561 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) |
| 3562 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False) |
| 3563 |
|
| 3564 |
@requires_tls_version('TLSv1_2') |
| 3565 |
def test_protocol_tlsv1_2(self): |
| 3566 |
"""Connecting to a TLSv1.2 server with various client options. |
| 3567 |
Testing against older TLS versions.""" |
| 3568 |
if support.verbose: |
| 3569 |
sys.stdout.write("\n") |
| 3570 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2', |
| 3571 |
server_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2, |
| 3572 |
client_options=ssl.OP_NO_SSLv3|ssl.OP_NO_SSLv2,) |
| 3573 |
if has_tls_version('SSLv3'): |
| 3574 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_SSLv3, False) |
| 3575 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLS, False, |
| 3576 |
client_options=ssl.OP_NO_TLSv1_2) |
| 3577 |
|
| 3578 |
try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2') |
| 3579 |
if has_tls_protocol(ssl.PROTOCOL_TLSv1): |
| 3580 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False) |
| 3581 |
try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False) |
| 3582 |
if has_tls_protocol(ssl.PROTOCOL_TLSv1_1): |
| 3583 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False) |
| 3584 |
try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) |
| 3585 |
|
| 3586 |
def test_starttls(self): |
| 3587 |
"""Switching from clear text to encrypted and back again.""" |
| 3588 |
msgs = (b"msg 1", b"MSG 2", b"STARTTLS", b"MSG 3", b"msg 4", b"ENDTLS", b"msg 5", b"msg 6") |
| 3589 |
|
| 3590 |
server = ThreadedEchoServer(CERTFILE, |
| 3591 |
starttls_server=True, |
| 3592 |
chatty=True, |
| 3593 |
connectionchatty=True) |
| 3594 |
wrapped = False |
| 3595 |
with server: |
| 3596 |
s = socket.socket() |
| 3597 |
s.setblocking(True) |
| 3598 |
s.connect((HOST, server.port)) |
| 3599 |
if support.verbose: |
| 3600 |
sys.stdout.write("\n") |
| 3601 |
for indata in msgs: |
| 3602 |
if support.verbose: |
| 3603 |
sys.stdout.write( |
| 3604 |
" client: sending %r...\n" % indata) |
| 3605 |
if wrapped: |
| 3606 |
conn.write(indata) |
| 3607 |
outdata = conn.read() |
| 3608 |
else: |
| 3609 |
s.send(indata) |
| 3610 |
outdata = s.recv(1024) |
| 3611 |
msg = outdata.strip().lower() |
| 3612 |
if indata == b"STARTTLS" and msg.startswith(b"ok"): |
| 3613 |
# STARTTLS ok, switch to secure mode |
| 3614 |
if support.verbose: |
| 3615 |
sys.stdout.write( |
| 3616 |
" client: read %r from server, starting TLS...\n" |
| 3617 |
% msg) |
| 3618 |
conn = test_wrap_socket(s) |
| 3619 |
wrapped = True |
| 3620 |
elif indata == b"ENDTLS" and msg.startswith(b"ok"): |
| 3621 |
# ENDTLS ok, switch back to clear text |
| 3622 |
if support.verbose: |
| 3623 |
sys.stdout.write( |
| 3624 |
" client: read %r from server, ending TLS...\n" |
| 3625 |
% msg) |
| 3626 |
s = conn.unwrap() |
| 3627 |
wrapped = False |
| 3628 |
else: |
| 3629 |
if support.verbose: |
| 3630 |
sys.stdout.write( |
| 3631 |
" client: read %r from server\n" % msg) |
| 3632 |
if support.verbose: |
| 3633 |
sys.stdout.write(" client: closing connection.\n") |
| 3634 |
if wrapped: |
| 3635 |
conn.write(b"over\n") |
| 3636 |
else: |
| 3637 |
s.send(b"over\n") |
| 3638 |
if wrapped: |
| 3639 |
conn.close() |
| 3640 |
else: |
| 3641 |
s.close() |
| 3642 |
|
| 3643 |
def test_socketserver(self): |
| 3644 |
"""Using socketserver to create and manage SSL connections.""" |
| 3645 |
server = make_https_server(self, certfile=SIGNED_CERTFILE) |
| 3646 |
# try to connect |
| 3647 |
if support.verbose: |
| 3648 |
sys.stdout.write('\n') |
| 3649 |
# Get this test file itself: |
| 3650 |
with open(__file__, 'rb') as f: |
| 3651 |
d1 = f.read() |
| 3652 |
d2 = '' |
| 3653 |
# now fetch the same data from the HTTPS server |
| 3654 |
url = f'https://localhost:{server.port}/test_ssl.py' |
| 3655 |
context = ssl.create_default_context(cafile=SIGNING_CA) |
| 3656 |
f = urllib.request.urlopen(url, context=context) |
| 3657 |
try: |
| 3658 |
dlen = f.info().get("content-length") |
| 3659 |
if dlen and (int(dlen) > 0): |
| 3660 |
d2 = f.read(int(dlen)) |
| 3661 |
if support.verbose: |
| 3662 |
sys.stdout.write( |
| 3663 |
" client: read %d bytes from remote server '%s'\n" |
| 3664 |
% (len(d2), server)) |
| 3665 |
finally: |
| 3666 |
f.close() |
| 3667 |
self.assertEqual(d1, d2) |
| 3668 |
|
| 3669 |
def test_asyncore_server(self): |
| 3670 |
"""Check the example asyncore integration.""" |
| 3671 |
if support.verbose: |
| 3672 |
sys.stdout.write("\n") |
| 3673 |
|
| 3674 |
indata = b"FOO\n" |
| 3675 |
server = AsyncoreEchoServer(CERTFILE) |
| 3676 |
with server: |
| 3677 |
s = test_wrap_socket(socket.socket()) |
| 3678 |
s.connect(('127.0.0.1', server.port)) |
| 3679 |
if support.verbose: |
| 3680 |
sys.stdout.write( |
| 3681 |
" client: sending %r...\n" % indata) |
| 3682 |
s.write(indata) |
| 3683 |
outdata = s.read() |
| 3684 |
if support.verbose: |
| 3685 |
sys.stdout.write(" client: read %r\n" % outdata) |
| 3686 |
if outdata != indata.lower(): |
| 3687 |
self.fail( |
| 3688 |
"bad data <<%r>> (%d) received; expected <<%r>> (%d)\n" |
| 3689 |
% (outdata[:20], len(outdata), |
| 3690 |
indata[:20].lower(), len(indata))) |
| 3691 |
s.write(b"over\n") |
| 3692 |
if support.verbose: |
| 3693 |
sys.stdout.write(" client: closing connection.\n") |
| 3694 |
s.close() |
| 3695 |
if support.verbose: |
| 3696 |
sys.stdout.write(" client: connection closed.\n") |
| 3697 |
|
| 3698 |
def test_recv_send(self): |
| 3699 |
"""Test recv(), send() and friends.""" |
| 3700 |
if support.verbose: |
| 3701 |
sys.stdout.write("\n") |
| 3702 |
|
| 3703 |
server = ThreadedEchoServer(CERTFILE, |
| 3704 |
certreqs=ssl.CERT_NONE, |
| 3705 |
ssl_version=ssl.PROTOCOL_TLS_SERVER, |
| 3706 |
cacerts=CERTFILE, |
| 3707 |
chatty=True, |
| 3708 |
connectionchatty=False) |
| 3709 |
with server: |
| 3710 |
s = test_wrap_socket(socket.socket(), |
| 3711 |
server_side=False, |
| 3712 |
certfile=CERTFILE, |
| 3713 |
ca_certs=CERTFILE, |
| 3714 |
cert_reqs=ssl.CERT_NONE) |
| 3715 |
s.connect((HOST, server.port)) |
| 3716 |
# helper methods for standardising recv* method signatures |
| 3717 |
def _recv_into(): |
| 3718 |
b = bytearray(b"\0"*100) |
| 3719 |
count = s.recv_into(b) |
| 3720 |
return b[:count] |
| 3721 |
|
| 3722 |
def _recvfrom_into(): |
| 3723 |
b = bytearray(b"\0"*100) |
| 3724 |
count, addr = s.recvfrom_into(b) |
| 3725 |
return b[:count] |
| 3726 |
|
| 3727 |
# (name, method, expect success?, *args, return value func) |
| 3728 |
send_methods = [ |
| 3729 |
('send', s.send, True, [], len), |
| 3730 |
('sendto', s.sendto, False, ["some.address"], len), |
| 3731 |
('sendall', s.sendall, True, [], lambda x: None), |
| 3732 |
] |
| 3733 |
# (name, method, whether to expect success, *args) |
| 3734 |
recv_methods = [ |
| 3735 |
('recv', s.recv, True, []), |
| 3736 |
('recvfrom', s.recvfrom, False, ["some.address"]), |
| 3737 |
('recv_into', _recv_into, True, []), |
| 3738 |
('recvfrom_into', _recvfrom_into, False, []), |
| 3739 |
] |
| 3740 |
data_prefix = "PREFIX_" |
| 3741 |
|
| 3742 |
for (meth_name, send_meth, expect_success, args, |
| 3743 |
ret_val_meth) in send_methods: |
| 3744 |
indata = (data_prefix + meth_name).encode('ascii') |
| 3745 |
try: |
| 3746 |
ret = send_meth(indata, *args) |
| 3747 |
msg = "sending with {}".format(meth_name) |
| 3748 |
self.assertEqual(ret, ret_val_meth(indata), msg=msg) |
| 3749 |
outdata = s.read() |
| 3750 |
if outdata != indata.lower(): |
| 3751 |
self.fail( |
| 3752 |
"While sending with <<{name:s}>> bad data " |
| 3753 |
"<<{outdata:r}>> ({nout:d}) received; " |
| 3754 |
"expected <<{indata:r}>> ({nin:d})\n".format( |
| 3755 |
name=meth_name, outdata=outdata[:20], |
| 3756 |
nout=len(outdata), |
| 3757 |
indata=indata[:20], nin=len(indata) |
| 3758 |
) |
| 3759 |
) |
| 3760 |
except ValueError as e: |
| 3761 |
if expect_success: |
| 3762 |
self.fail( |
| 3763 |
"Failed to send with method <<{name:s}>>; " |
| 3764 |
"expected to succeed.\n".format(name=meth_name) |
| 3765 |
) |
| 3766 |
if not str(e).startswith(meth_name): |
| 3767 |
self.fail( |
| 3768 |
"Method <<{name:s}>> failed with unexpected " |
| 3769 |
"exception message: {exp:s}\n".format( |
| 3770 |
name=meth_name, exp=e |
| 3771 |
) |
| 3772 |
) |
| 3773 |
|
| 3774 |
for meth_name, recv_meth, expect_success, args in recv_methods: |
| 3775 |
indata = (data_prefix + meth_name).encode('ascii') |
| 3776 |
try: |
| 3777 |
s.send(indata) |
| 3778 |
outdata = recv_meth(*args) |
| 3779 |
if outdata != indata.lower(): |
| 3780 |
self.fail( |
| 3781 |
"While receiving with <<{name:s}>> bad data " |
| 3782 |
"<<{outdata:r}>> ({nout:d}) received; " |
| 3783 |
"expected <<{indata:r}>> ({nin:d})\n".format( |
| 3784 |
name=meth_name, outdata=outdata[:20], |
| 3785 |
nout=len(outdata), |
| 3786 |
indata=indata[:20], nin=len(indata) |
| 3787 |
) |
| 3788 |
) |
| 3789 |
except ValueError as e: |
| 3790 |
if expect_success: |
| 3791 |
self.fail( |
| 3792 |
"Failed to receive with method <<{name:s}>>; " |
| 3793 |
"expected to succeed.\n".format(name=meth_name) |
| 3794 |
) |
| 3795 |
if not str(e).startswith(meth_name): |
| 3796 |
self.fail( |
| 3797 |
"Method <<{name:s}>> failed with unexpected " |
| 3798 |
"exception message: {exp:s}\n".format( |
| 3799 |
name=meth_name, exp=e |
| 3800 |
) |
| 3801 |
) |
| 3802 |
# consume data |
| 3803 |
s.read() |
| 3804 |
|
| 3805 |
# read(-1, buffer) is supported, even though read(-1) is not |
| 3806 |
data = b"data" |
| 3807 |
s.send(data) |
| 3808 |
buffer = bytearray(len(data)) |
| 3809 |
self.assertEqual(s.read(-1, buffer), len(data)) |
| 3810 |
self.assertEqual(buffer, data) |
| 3811 |
|
| 3812 |
# sendall accepts bytes-like objects |
| 3813 |
if ctypes is not None: |
| 3814 |
ubyte = ctypes.c_ubyte * len(data) |
| 3815 |
byteslike = ubyte.from_buffer_copy(data) |
| 3816 |
s.sendall(byteslike) |
| 3817 |
self.assertEqual(s.read(), data) |
| 3818 |
|
| 3819 |
# Make sure sendmsg et al are disallowed to avoid |
| 3820 |
# inadvertent disclosure of data and/or corruption |
| 3821 |
# of the encrypted data stream |
| 3822 |
self.assertRaises(NotImplementedError, s.dup) |
| 3823 |
self.assertRaises(NotImplementedError, s.sendmsg, [b"data"]) |
| 3824 |
self.assertRaises(NotImplementedError, s.recvmsg, 100) |
| 3825 |
self.assertRaises(NotImplementedError, |
| 3826 |
s.recvmsg_into, [bytearray(100)]) |
| 3827 |
s.write(b"over\n") |
| 3828 |
|
| 3829 |
self.assertRaises(ValueError, s.recv, -1) |
| 3830 |
self.assertRaises(ValueError, s.read, -1) |
| 3831 |
|
| 3832 |
s.close() |
| 3833 |
|
| 3834 |
def test_recv_zero(self): |
| 3835 |
server = ThreadedEchoServer(CERTFILE) |
| 3836 |
self.enterContext(server) |
| 3837 |
s = socket.create_connection((HOST, server.port)) |
| 3838 |
self.addCleanup(s.close) |
| 3839 |
s = test_wrap_socket(s, suppress_ragged_eofs=False) |
| 3840 |
self.addCleanup(s.close) |
| 3841 |
|
| 3842 |
# recv/read(0) should return no data |
| 3843 |
s.send(b"data") |
| 3844 |
self.assertEqual(s.recv(0), b"") |
| 3845 |
self.assertEqual(s.read(0), b"") |
| 3846 |
self.assertEqual(s.read(), b"data") |
| 3847 |
|
| 3848 |
# Should not block if the other end sends no data |
| 3849 |
s.setblocking(False) |
| 3850 |
self.assertEqual(s.recv(0), b"") |
| 3851 |
self.assertEqual(s.recv_into(bytearray()), 0) |
| 3852 |
|
| 3853 |
def test_recv_into_buffer_protocol_len(self): |
| 3854 |
server = ThreadedEchoServer(CERTFILE) |
| 3855 |
self.enterContext(server) |
| 3856 |
s = socket.create_connection((HOST, server.port)) |
| 3857 |
self.addCleanup(s.close) |
| 3858 |
s = test_wrap_socket(s, suppress_ragged_eofs=False) |
| 3859 |
self.addCleanup(s.close) |
| 3860 |
|
| 3861 |
s.send(b"data") |
| 3862 |
buf = array.array('I', [0, 0]) |
| 3863 |
self.assertEqual(s.recv_into(buf), 4) |
| 3864 |
self.assertEqual(bytes(buf)[:4], b"data") |
| 3865 |
|
| 3866 |
class B(bytearray): |
| 3867 |
def __len__(self): |
| 3868 |
1/0 |
| 3869 |
s.send(b"data") |
| 3870 |
buf = B(6) |
| 3871 |
self.assertEqual(s.recv_into(buf), 4) |
| 3872 |
self.assertEqual(bytes(buf), b"data\0\0") |
| 3873 |
|
| 3874 |
def test_nonblocking_send(self): |
| 3875 |
server = ThreadedEchoServer(CERTFILE, |
| 3876 |
certreqs=ssl.CERT_NONE, |
| 3877 |
ssl_version=ssl.PROTOCOL_TLS_SERVER, |
| 3878 |
cacerts=CERTFILE, |
| 3879 |
chatty=True, |
| 3880 |
connectionchatty=False) |
| 3881 |
with server: |
| 3882 |
s = test_wrap_socket(socket.socket(), |
| 3883 |
server_side=False, |
| 3884 |
certfile=CERTFILE, |
| 3885 |
ca_certs=CERTFILE, |
| 3886 |
cert_reqs=ssl.CERT_NONE) |
| 3887 |
s.connect((HOST, server.port)) |
| 3888 |
s.setblocking(False) |
| 3889 |
|
| 3890 |
# If we keep sending data, at some point the buffers |
| 3891 |
# will be full and the call will block |
| 3892 |
buf = bytearray(8192) |
| 3893 |
def fill_buffer(): |
| 3894 |
while True: |
| 3895 |
s.send(buf) |
| 3896 |
self.assertRaises((ssl.SSLWantWriteError, |
| 3897 |
ssl.SSLWantReadError), fill_buffer) |
| 3898 |
|
| 3899 |
# Now read all the output and discard it |
| 3900 |
s.setblocking(True) |
| 3901 |
s.close() |
| 3902 |
|
| 3903 |
def test_handshake_timeout(self): |
| 3904 |
# Issue #5103: SSL handshake must respect the socket timeout |
| 3905 |
server = socket.socket(socket.AF_INET) |
| 3906 |
host = "127.0.0.1" |
| 3907 |
port = socket_helper.bind_port(server) |
| 3908 |
started = threading.Event() |
| 3909 |
finish = False |
| 3910 |
|
| 3911 |
def serve(): |
| 3912 |
server.listen() |
| 3913 |
started.set() |
| 3914 |
conns = [] |
| 3915 |
while not finish: |
| 3916 |
r, w, e = select.select([server], [], [], 0.1) |
| 3917 |
if server in r: |
| 3918 |
# Let the socket hang around rather than having |
| 3919 |
# it closed by garbage collection. |
| 3920 |
conns.append(server.accept()[0]) |
| 3921 |
for sock in conns: |
| 3922 |
sock.close() |
| 3923 |
|
| 3924 |
t = threading.Thread(target=serve) |
| 3925 |
t.start() |
| 3926 |
started.wait() |
| 3927 |
|
| 3928 |
try: |
| 3929 |
try: |
| 3930 |
c = socket.socket(socket.AF_INET) |
| 3931 |
c.settimeout(0.2) |
| 3932 |
c.connect((host, port)) |
| 3933 |
# Will attempt handshake and time out |
| 3934 |
self.assertRaisesRegex(TimeoutError, "timed out", |
| 3935 |
test_wrap_socket, c) |
| 3936 |
finally: |
| 3937 |
c.close() |
| 3938 |
try: |
| 3939 |
c = socket.socket(socket.AF_INET) |
| 3940 |
c = test_wrap_socket(c) |
| 3941 |
c.settimeout(0.2) |
| 3942 |
# Will attempt handshake and time out |
| 3943 |
self.assertRaisesRegex(TimeoutError, "timed out", |
| 3944 |
c.connect, (host, port)) |
| 3945 |
finally: |
| 3946 |
c.close() |
| 3947 |
finally: |
| 3948 |
finish = True |
| 3949 |
t.join() |
| 3950 |
server.close() |
| 3951 |
|
| 3952 |
def test_server_accept(self): |
| 3953 |
# Issue #16357: accept() on a SSLSocket created through |
| 3954 |
# SSLContext.wrap_socket(). |
| 3955 |
client_ctx, server_ctx, hostname = testing_context() |
| 3956 |
server = socket.socket(socket.AF_INET) |
| 3957 |
host = "127.0.0.1" |
| 3958 |
port = socket_helper.bind_port(server) |
| 3959 |
server = server_ctx.wrap_socket(server, server_side=True) |
| 3960 |
self.assertTrue(server.server_side) |
| 3961 |
|
| 3962 |
evt = threading.Event() |
| 3963 |
remote = None |
| 3964 |
peer = None |
| 3965 |
def serve(): |
| 3966 |
nonlocal remote, peer |
| 3967 |
server.listen() |
| 3968 |
# Block on the accept and wait on the connection to close. |
| 3969 |
evt.set() |
| 3970 |
remote, peer = server.accept() |
| 3971 |
remote.send(remote.recv(4)) |
| 3972 |
|
| 3973 |
t = threading.Thread(target=serve) |
| 3974 |
t.start() |
| 3975 |
# Client wait until server setup and perform a connect. |
| 3976 |
evt.wait() |
| 3977 |
client = client_ctx.wrap_socket( |
| 3978 |
socket.socket(), server_hostname=hostname |
| 3979 |
) |
| 3980 |
client.connect((hostname, port)) |
| 3981 |
client.send(b'data') |
| 3982 |
client.recv() |
| 3983 |
client_addr = client.getsockname() |
| 3984 |
client.close() |
| 3985 |
t.join() |
| 3986 |
remote.close() |
| 3987 |
server.close() |
| 3988 |
# Sanity checks. |
| 3989 |
self.assertIsInstance(remote, ssl.SSLSocket) |
| 3990 |
self.assertEqual(peer, client_addr) |
| 3991 |
|
| 3992 |
def test_getpeercert_enotconn(self): |
| 3993 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 3994 |
context.check_hostname = False |
| 3995 |
with context.wrap_socket(socket.socket()) as sock: |
| 3996 |
with self.assertRaises(OSError) as cm: |
| 3997 |
sock.getpeercert() |
| 3998 |
self.assertEqual(cm.exception.errno, errno.ENOTCONN) |
| 3999 |
|
| 4000 |
def test_do_handshake_enotconn(self): |
| 4001 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4002 |
context.check_hostname = False |
| 4003 |
with context.wrap_socket(socket.socket()) as sock: |
| 4004 |
with self.assertRaises(OSError) as cm: |
| 4005 |
sock.do_handshake() |
| 4006 |
self.assertEqual(cm.exception.errno, errno.ENOTCONN) |
| 4007 |
|
| 4008 |
def test_no_shared_ciphers(self): |
| 4009 |
client_context, server_context, hostname = testing_context() |
| 4010 |
# OpenSSL enables all TLS 1.3 ciphers, enforce TLS 1.2 for test |
| 4011 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4012 |
# Force different suites on client and server |
| 4013 |
client_context.set_ciphers("AES128") |
| 4014 |
server_context.set_ciphers("AES256") |
| 4015 |
with ThreadedEchoServer(context=server_context) as server: |
| 4016 |
with client_context.wrap_socket(socket.socket(), |
| 4017 |
server_hostname=hostname) as s: |
| 4018 |
with self.assertRaises(OSError): |
| 4019 |
s.connect((HOST, server.port)) |
| 4020 |
self.assertIn("NO_SHARED_CIPHER", server.conn_errors[0]) |
| 4021 |
|
| 4022 |
def test_version_basic(self): |
| 4023 |
""" |
| 4024 |
Basic tests for SSLSocket.version(). |
| 4025 |
More tests are done in the test_protocol_*() methods. |
| 4026 |
""" |
| 4027 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4028 |
context.check_hostname = False |
| 4029 |
context.verify_mode = ssl.CERT_NONE |
| 4030 |
with ThreadedEchoServer(CERTFILE, |
| 4031 |
ssl_version=ssl.PROTOCOL_TLS_SERVER, |
| 4032 |
chatty=False) as server: |
| 4033 |
with context.wrap_socket(socket.socket()) as s: |
| 4034 |
self.assertIs(s.version(), None) |
| 4035 |
self.assertIs(s._sslobj, None) |
| 4036 |
s.connect((HOST, server.port)) |
| 4037 |
self.assertEqual(s.version(), 'TLSv1.3') |
| 4038 |
self.assertIs(s._sslobj, None) |
| 4039 |
self.assertIs(s.version(), None) |
| 4040 |
|
| 4041 |
@requires_tls_version('TLSv1_3') |
| 4042 |
def test_tls1_3(self): |
| 4043 |
client_context, server_context, hostname = testing_context() |
| 4044 |
client_context.minimum_version = ssl.TLSVersion.TLSv1_3 |
| 4045 |
with ThreadedEchoServer(context=server_context) as server: |
| 4046 |
with client_context.wrap_socket(socket.socket(), |
| 4047 |
server_hostname=hostname) as s: |
| 4048 |
s.connect((HOST, server.port)) |
| 4049 |
self.assertIn(s.cipher()[0], { |
| 4050 |
'TLS_AES_256_GCM_SHA384', |
| 4051 |
'TLS_CHACHA20_POLY1305_SHA256', |
| 4052 |
'TLS_AES_128_GCM_SHA256', |
| 4053 |
}) |
| 4054 |
self.assertEqual(s.version(), 'TLSv1.3') |
| 4055 |
|
| 4056 |
@requires_tls_version('TLSv1_2') |
| 4057 |
@requires_tls_version('TLSv1') |
| 4058 |
@ignore_deprecation |
| 4059 |
def test_min_max_version_tlsv1_2(self): |
| 4060 |
client_context, server_context, hostname = testing_context() |
| 4061 |
# client TLSv1.0 to 1.2 |
| 4062 |
client_context.minimum_version = ssl.TLSVersion.TLSv1 |
| 4063 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4064 |
# server only TLSv1.2 |
| 4065 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 4066 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4067 |
|
| 4068 |
with ThreadedEchoServer(context=server_context) as server: |
| 4069 |
with client_context.wrap_socket(socket.socket(), |
| 4070 |
server_hostname=hostname) as s: |
| 4071 |
s.connect((HOST, server.port)) |
| 4072 |
self.assertEqual(s.version(), 'TLSv1.2') |
| 4073 |
|
| 4074 |
@requires_tls_version('TLSv1_1') |
| 4075 |
@ignore_deprecation |
| 4076 |
def test_min_max_version_tlsv1_1(self): |
| 4077 |
client_context, server_context, hostname = testing_context() |
| 4078 |
# client 1.0 to 1.2, server 1.0 to 1.1 |
| 4079 |
client_context.minimum_version = ssl.TLSVersion.TLSv1 |
| 4080 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4081 |
server_context.minimum_version = ssl.TLSVersion.TLSv1 |
| 4082 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_1 |
| 4083 |
seclevel_workaround(client_context, server_context) |
| 4084 |
|
| 4085 |
with ThreadedEchoServer(context=server_context) as server: |
| 4086 |
with client_context.wrap_socket(socket.socket(), |
| 4087 |
server_hostname=hostname) as s: |
| 4088 |
s.connect((HOST, server.port)) |
| 4089 |
self.assertEqual(s.version(), 'TLSv1.1') |
| 4090 |
|
| 4091 |
@requires_tls_version('TLSv1_2') |
| 4092 |
@requires_tls_version('TLSv1') |
| 4093 |
@ignore_deprecation |
| 4094 |
def test_min_max_version_mismatch(self): |
| 4095 |
client_context, server_context, hostname = testing_context() |
| 4096 |
# client 1.0, server 1.2 (mismatch) |
| 4097 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4098 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 4099 |
client_context.maximum_version = ssl.TLSVersion.TLSv1 |
| 4100 |
client_context.minimum_version = ssl.TLSVersion.TLSv1 |
| 4101 |
seclevel_workaround(client_context, server_context) |
| 4102 |
|
| 4103 |
with ThreadedEchoServer(context=server_context) as server: |
| 4104 |
with client_context.wrap_socket(socket.socket(), |
| 4105 |
server_hostname=hostname) as s: |
| 4106 |
with self.assertRaises(ssl.SSLError) as e: |
| 4107 |
s.connect((HOST, server.port)) |
| 4108 |
self.assertRegex(str(e.exception), "(alert|ALERT)") |
| 4109 |
|
| 4110 |
@requires_tls_version('SSLv3') |
| 4111 |
def test_min_max_version_sslv3(self): |
| 4112 |
client_context, server_context, hostname = testing_context() |
| 4113 |
server_context.minimum_version = ssl.TLSVersion.SSLv3 |
| 4114 |
client_context.minimum_version = ssl.TLSVersion.SSLv3 |
| 4115 |
client_context.maximum_version = ssl.TLSVersion.SSLv3 |
| 4116 |
seclevel_workaround(client_context, server_context) |
| 4117 |
|
| 4118 |
with ThreadedEchoServer(context=server_context) as server: |
| 4119 |
with client_context.wrap_socket(socket.socket(), |
| 4120 |
server_hostname=hostname) as s: |
| 4121 |
s.connect((HOST, server.port)) |
| 4122 |
self.assertEqual(s.version(), 'SSLv3') |
| 4123 |
|
| 4124 |
def test_default_ecdh_curve(self): |
| 4125 |
# Issue #21015: elliptic curve-based Diffie Hellman key exchange |
| 4126 |
# should be enabled by default on SSL contexts. |
| 4127 |
client_context, server_context, hostname = testing_context() |
| 4128 |
# TLSv1.3 defaults to PFS key agreement and no longer has KEA in |
| 4129 |
# cipher name. |
| 4130 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4131 |
# Prior to OpenSSL 1.0.0, ECDH ciphers have to be enabled |
| 4132 |
# explicitly using the 'ECCdraft' cipher alias. Otherwise, |
| 4133 |
# our default cipher list should prefer ECDH-based ciphers |
| 4134 |
# automatically. |
| 4135 |
with ThreadedEchoServer(context=server_context) as server: |
| 4136 |
with client_context.wrap_socket(socket.socket(), |
| 4137 |
server_hostname=hostname) as s: |
| 4138 |
s.connect((HOST, server.port)) |
| 4139 |
self.assertIn("ECDH", s.cipher()[0]) |
| 4140 |
|
| 4141 |
@unittest.skipUnless("tls-unique" in ssl.CHANNEL_BINDING_TYPES, |
| 4142 |
"'tls-unique' channel binding not available") |
| 4143 |
def test_tls_unique_channel_binding(self): |
| 4144 |
"""Test tls-unique channel binding.""" |
| 4145 |
if support.verbose: |
| 4146 |
sys.stdout.write("\n") |
| 4147 |
|
| 4148 |
client_context, server_context, hostname = testing_context() |
| 4149 |
|
| 4150 |
# tls-unique is not defined for TLSv1.3 |
| 4151 |
# https://datatracker.ietf.org/doc/html/rfc8446#appendix-C.5 |
| 4152 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4153 |
|
| 4154 |
server = ThreadedEchoServer(context=server_context, |
| 4155 |
chatty=True, |
| 4156 |
connectionchatty=False) |
| 4157 |
|
| 4158 |
with server: |
| 4159 |
with client_context.wrap_socket( |
| 4160 |
socket.socket(), |
| 4161 |
server_hostname=hostname) as s: |
| 4162 |
s.connect((HOST, server.port)) |
| 4163 |
# get the data |
| 4164 |
cb_data = s.get_channel_binding("tls-unique") |
| 4165 |
if support.verbose: |
| 4166 |
sys.stdout.write( |
| 4167 |
" got channel binding data: {0!r}\n".format(cb_data)) |
| 4168 |
|
| 4169 |
# check if it is sane |
| 4170 |
self.assertIsNotNone(cb_data) |
| 4171 |
if s.version() == 'TLSv1.3': |
| 4172 |
self.assertEqual(len(cb_data), 48) |
| 4173 |
else: |
| 4174 |
self.assertEqual(len(cb_data), 12) # True for TLSv1 |
| 4175 |
|
| 4176 |
# and compare with the peers version |
| 4177 |
s.write(b"CB tls-unique\n") |
| 4178 |
peer_data_repr = s.read().strip() |
| 4179 |
self.assertEqual(peer_data_repr, |
| 4180 |
repr(cb_data).encode("us-ascii")) |
| 4181 |
|
| 4182 |
# now, again |
| 4183 |
with client_context.wrap_socket( |
| 4184 |
socket.socket(), |
| 4185 |
server_hostname=hostname) as s: |
| 4186 |
s.connect((HOST, server.port)) |
| 4187 |
new_cb_data = s.get_channel_binding("tls-unique") |
| 4188 |
if support.verbose: |
| 4189 |
sys.stdout.write( |
| 4190 |
"got another channel binding data: {0!r}\n".format( |
| 4191 |
new_cb_data) |
| 4192 |
) |
| 4193 |
# is it really unique |
| 4194 |
self.assertNotEqual(cb_data, new_cb_data) |
| 4195 |
self.assertIsNotNone(cb_data) |
| 4196 |
if s.version() == 'TLSv1.3': |
| 4197 |
self.assertEqual(len(cb_data), 48) |
| 4198 |
else: |
| 4199 |
self.assertEqual(len(cb_data), 12) # True for TLSv1 |
| 4200 |
s.write(b"CB tls-unique\n") |
| 4201 |
peer_data_repr = s.read().strip() |
| 4202 |
self.assertEqual(peer_data_repr, |
| 4203 |
repr(new_cb_data).encode("us-ascii")) |
| 4204 |
|
| 4205 |
def test_compression(self): |
| 4206 |
client_context, server_context, hostname = testing_context() |
| 4207 |
stats = server_params_test(client_context, server_context, |
| 4208 |
chatty=True, connectionchatty=True, |
| 4209 |
sni_name=hostname) |
| 4210 |
if support.verbose: |
| 4211 |
sys.stdout.write(" got compression: {!r}\n".format(stats['compression'])) |
| 4212 |
self.assertIn(stats['compression'], { None, 'ZLIB', 'RLE' }) |
| 4213 |
|
| 4214 |
@unittest.skipUnless(hasattr(ssl, 'OP_NO_COMPRESSION'), |
| 4215 |
"ssl.OP_NO_COMPRESSION needed for this test") |
| 4216 |
def test_compression_disabled(self): |
| 4217 |
client_context, server_context, hostname = testing_context() |
| 4218 |
client_context.options |= ssl.OP_NO_COMPRESSION |
| 4219 |
server_context.options |= ssl.OP_NO_COMPRESSION |
| 4220 |
stats = server_params_test(client_context, server_context, |
| 4221 |
chatty=True, connectionchatty=True, |
| 4222 |
sni_name=hostname) |
| 4223 |
self.assertIs(stats['compression'], None) |
| 4224 |
|
| 4225 |
def test_legacy_server_connect(self): |
| 4226 |
client_context, server_context, hostname = testing_context() |
| 4227 |
client_context.options |= ssl.OP_LEGACY_SERVER_CONNECT |
| 4228 |
server_params_test(client_context, server_context, |
| 4229 |
chatty=True, connectionchatty=True, |
| 4230 |
sni_name=hostname) |
| 4231 |
|
| 4232 |
def test_no_legacy_server_connect(self): |
| 4233 |
client_context, server_context, hostname = testing_context() |
| 4234 |
client_context.options &= ~ssl.OP_LEGACY_SERVER_CONNECT |
| 4235 |
server_params_test(client_context, server_context, |
| 4236 |
chatty=True, connectionchatty=True, |
| 4237 |
sni_name=hostname) |
| 4238 |
|
| 4239 |
def test_dh_params(self): |
| 4240 |
# Check we can get a connection with ephemeral finite-field |
| 4241 |
# Diffie-Hellman (if supported). |
| 4242 |
client_context, server_context, hostname = testing_context() |
| 4243 |
dhe_aliases = {"ADH", "EDH", "DHE"} |
| 4244 |
if not (supports_kx_alias(client_context, dhe_aliases) |
| 4245 |
and supports_kx_alias(server_context, dhe_aliases)): |
| 4246 |
self.skipTest("libssl doesn't support ephemeral DH") |
| 4247 |
# test scenario needs TLS <= 1.2 |
| 4248 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4249 |
try: |
| 4250 |
server_context.load_dh_params(DHFILE) |
| 4251 |
except RuntimeError: |
| 4252 |
if Py_DEBUG_WIN32: |
| 4253 |
self.skipTest("not supported on Win32 debug build") |
| 4254 |
raise |
| 4255 |
server_context.set_ciphers("kEDH") |
| 4256 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4257 |
stats = server_params_test(client_context, server_context, |
| 4258 |
chatty=True, connectionchatty=True, |
| 4259 |
sni_name=hostname) |
| 4260 |
cipher = stats["cipher"][0] |
| 4261 |
parts = cipher.split("-") |
| 4262 |
if not dhe_aliases.intersection(parts): |
| 4263 |
self.fail("Non-DH key exchange: " + cipher[0]) |
| 4264 |
|
| 4265 |
def test_ecdh_curve(self): |
| 4266 |
# server secp384r1, client auto |
| 4267 |
client_context, server_context, hostname = testing_context() |
| 4268 |
|
| 4269 |
server_context.set_ecdh_curve("secp384r1") |
| 4270 |
server_context.set_ciphers("ECDHE:!eNULL:!aNULL") |
| 4271 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 4272 |
stats = server_params_test(client_context, server_context, |
| 4273 |
chatty=True, connectionchatty=True, |
| 4274 |
sni_name=hostname) |
| 4275 |
|
| 4276 |
# server auto, client secp384r1 |
| 4277 |
client_context, server_context, hostname = testing_context() |
| 4278 |
client_context.set_ecdh_curve("secp384r1") |
| 4279 |
server_context.set_ciphers("ECDHE:!eNULL:!aNULL") |
| 4280 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 4281 |
stats = server_params_test(client_context, server_context, |
| 4282 |
chatty=True, connectionchatty=True, |
| 4283 |
sni_name=hostname) |
| 4284 |
|
| 4285 |
# server / client curve mismatch |
| 4286 |
client_context, server_context, hostname = testing_context() |
| 4287 |
client_context.set_ecdh_curve("prime256v1") |
| 4288 |
server_context.set_ecdh_curve("secp384r1") |
| 4289 |
server_context.set_ciphers("ECDHE:!eNULL:!aNULL") |
| 4290 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 4291 |
with self.assertRaises(ssl.SSLError): |
| 4292 |
server_params_test(client_context, server_context, |
| 4293 |
chatty=True, connectionchatty=True, |
| 4294 |
sni_name=hostname) |
| 4295 |
|
| 4296 |
def test_selected_alpn_protocol(self): |
| 4297 |
# selected_alpn_protocol() is None unless ALPN is used. |
| 4298 |
client_context, server_context, hostname = testing_context() |
| 4299 |
stats = server_params_test(client_context, server_context, |
| 4300 |
chatty=True, connectionchatty=True, |
| 4301 |
sni_name=hostname) |
| 4302 |
self.assertIs(stats['client_alpn_protocol'], None) |
| 4303 |
|
| 4304 |
def test_selected_alpn_protocol_if_server_uses_alpn(self): |
| 4305 |
# selected_alpn_protocol() is None unless ALPN is used by the client. |
| 4306 |
client_context, server_context, hostname = testing_context() |
| 4307 |
server_context.set_alpn_protocols(['foo', 'bar']) |
| 4308 |
stats = server_params_test(client_context, server_context, |
| 4309 |
chatty=True, connectionchatty=True, |
| 4310 |
sni_name=hostname) |
| 4311 |
self.assertIs(stats['client_alpn_protocol'], None) |
| 4312 |
|
| 4313 |
def test_alpn_protocols(self): |
| 4314 |
server_protocols = ['foo', 'bar', 'milkshake'] |
| 4315 |
protocol_tests = [ |
| 4316 |
(['foo', 'bar'], 'foo'), |
| 4317 |
(['bar', 'foo'], 'foo'), |
| 4318 |
(['milkshake'], 'milkshake'), |
| 4319 |
(['http/3.0', 'http/4.0'], None) |
| 4320 |
] |
| 4321 |
for client_protocols, expected in protocol_tests: |
| 4322 |
client_context, server_context, hostname = testing_context() |
| 4323 |
server_context.set_alpn_protocols(server_protocols) |
| 4324 |
client_context.set_alpn_protocols(client_protocols) |
| 4325 |
|
| 4326 |
try: |
| 4327 |
stats = server_params_test(client_context, |
| 4328 |
server_context, |
| 4329 |
chatty=True, |
| 4330 |
connectionchatty=True, |
| 4331 |
sni_name=hostname) |
| 4332 |
except ssl.SSLError as e: |
| 4333 |
stats = e |
| 4334 |
|
| 4335 |
msg = "failed trying %s (s) and %s (c).\n" \ |
| 4336 |
"was expecting %s, but got %%s from the %%s" \ |
| 4337 |
% (str(server_protocols), str(client_protocols), |
| 4338 |
str(expected)) |
| 4339 |
client_result = stats['client_alpn_protocol'] |
| 4340 |
self.assertEqual(client_result, expected, |
| 4341 |
msg % (client_result, "client")) |
| 4342 |
server_result = stats['server_alpn_protocols'][-1] \ |
| 4343 |
if len(stats['server_alpn_protocols']) else 'nothing' |
| 4344 |
self.assertEqual(server_result, expected, |
| 4345 |
msg % (server_result, "server")) |
| 4346 |
|
| 4347 |
def test_npn_protocols(self): |
| 4348 |
assert not ssl.HAS_NPN |
| 4349 |
|
| 4350 |
def sni_contexts(self): |
| 4351 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4352 |
server_context.load_cert_chain(SIGNED_CERTFILE) |
| 4353 |
other_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4354 |
other_context.load_cert_chain(SIGNED_CERTFILE2) |
| 4355 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4356 |
client_context.load_verify_locations(SIGNING_CA) |
| 4357 |
return server_context, other_context, client_context |
| 4358 |
|
| 4359 |
def check_common_name(self, stats, name): |
| 4360 |
cert = stats['peercert'] |
| 4361 |
self.assertIn((('commonName', name),), cert['subject']) |
| 4362 |
|
| 4363 |
def test_sni_callback(self): |
| 4364 |
calls = [] |
| 4365 |
server_context, other_context, client_context = self.sni_contexts() |
| 4366 |
|
| 4367 |
client_context.check_hostname = False |
| 4368 |
|
| 4369 |
def servername_cb(ssl_sock, server_name, initial_context): |
| 4370 |
calls.append((server_name, initial_context)) |
| 4371 |
if server_name is not None: |
| 4372 |
ssl_sock.context = other_context |
| 4373 |
server_context.set_servername_callback(servername_cb) |
| 4374 |
|
| 4375 |
stats = server_params_test(client_context, server_context, |
| 4376 |
chatty=True, |
| 4377 |
sni_name='supermessage') |
| 4378 |
# The hostname was fetched properly, and the certificate was |
| 4379 |
# changed for the connection. |
| 4380 |
self.assertEqual(calls, [("supermessage", server_context)]) |
| 4381 |
# CERTFILE4 was selected |
| 4382 |
self.check_common_name(stats, 'fakehostname') |
| 4383 |
|
| 4384 |
calls = [] |
| 4385 |
# The callback is called with server_name=None |
| 4386 |
stats = server_params_test(client_context, server_context, |
| 4387 |
chatty=True, |
| 4388 |
sni_name=None) |
| 4389 |
self.assertEqual(calls, [(None, server_context)]) |
| 4390 |
self.check_common_name(stats, SIGNED_CERTFILE_HOSTNAME) |
| 4391 |
|
| 4392 |
# Check disabling the callback |
| 4393 |
calls = [] |
| 4394 |
server_context.set_servername_callback(None) |
| 4395 |
|
| 4396 |
stats = server_params_test(client_context, server_context, |
| 4397 |
chatty=True, |
| 4398 |
sni_name='notfunny') |
| 4399 |
# Certificate didn't change |
| 4400 |
self.check_common_name(stats, SIGNED_CERTFILE_HOSTNAME) |
| 4401 |
self.assertEqual(calls, []) |
| 4402 |
|
| 4403 |
def test_sni_callback_alert(self): |
| 4404 |
# Returning a TLS alert is reflected to the connecting client |
| 4405 |
server_context, other_context, client_context = self.sni_contexts() |
| 4406 |
|
| 4407 |
def cb_returning_alert(ssl_sock, server_name, initial_context): |
| 4408 |
return ssl.ALERT_DESCRIPTION_ACCESS_DENIED |
| 4409 |
server_context.set_servername_callback(cb_returning_alert) |
| 4410 |
with self.assertRaises(ssl.SSLError) as cm: |
| 4411 |
stats = server_params_test(client_context, server_context, |
| 4412 |
chatty=False, |
| 4413 |
sni_name='supermessage') |
| 4414 |
self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_ACCESS_DENIED') |
| 4415 |
|
| 4416 |
def test_sni_callback_raising(self): |
| 4417 |
# Raising fails the connection with a TLS handshake failure alert. |
| 4418 |
server_context, other_context, client_context = self.sni_contexts() |
| 4419 |
|
| 4420 |
def cb_raising(ssl_sock, server_name, initial_context): |
| 4421 |
1/0 |
| 4422 |
server_context.set_servername_callback(cb_raising) |
| 4423 |
|
| 4424 |
with support.catch_unraisable_exception() as catch: |
| 4425 |
with self.assertRaises(ssl.SSLError) as cm: |
| 4426 |
stats = server_params_test(client_context, server_context, |
| 4427 |
chatty=False, |
| 4428 |
sni_name='supermessage') |
| 4429 |
|
| 4430 |
# Allow for flexible libssl error messages. |
| 4431 |
regex = "(SSLV3_ALERT_HANDSHAKE_FAILURE|NO_PRIVATE_VALUE)" |
| 4432 |
self.assertRegex(cm.exception.reason, regex) |
| 4433 |
self.assertEqual(catch.unraisable.exc_type, ZeroDivisionError) |
| 4434 |
|
| 4435 |
def test_sni_callback_wrong_return_type(self): |
| 4436 |
# Returning the wrong return type terminates the TLS connection |
| 4437 |
# with an internal error alert. |
| 4438 |
server_context, other_context, client_context = self.sni_contexts() |
| 4439 |
|
| 4440 |
def cb_wrong_return_type(ssl_sock, server_name, initial_context): |
| 4441 |
return "foo" |
| 4442 |
server_context.set_servername_callback(cb_wrong_return_type) |
| 4443 |
|
| 4444 |
with support.catch_unraisable_exception() as catch: |
| 4445 |
with self.assertRaises(ssl.SSLError) as cm: |
| 4446 |
stats = server_params_test(client_context, server_context, |
| 4447 |
chatty=False, |
| 4448 |
sni_name='supermessage') |
| 4449 |
|
| 4450 |
|
| 4451 |
self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR') |
| 4452 |
self.assertEqual(catch.unraisable.exc_type, TypeError) |
| 4453 |
|
| 4454 |
def test_shared_ciphers(self): |
| 4455 |
client_context, server_context, hostname = testing_context() |
| 4456 |
client_context.set_ciphers("AES128:AES256") |
| 4457 |
server_context.set_ciphers("AES256:eNULL") |
| 4458 |
expected_algs = [ |
| 4459 |
"AES256", "AES-256", |
| 4460 |
# TLS 1.3 ciphers are always enabled |
| 4461 |
"TLS_CHACHA20", "TLS_AES", |
| 4462 |
] |
| 4463 |
|
| 4464 |
stats = server_params_test(client_context, server_context, |
| 4465 |
sni_name=hostname) |
| 4466 |
ciphers = stats['server_shared_ciphers'][0] |
| 4467 |
self.assertGreater(len(ciphers), 0) |
| 4468 |
for name, tls_version, bits in ciphers: |
| 4469 |
if not any(alg in name for alg in expected_algs): |
| 4470 |
self.fail(name) |
| 4471 |
|
| 4472 |
def test_read_write_after_close_raises_valuerror(self): |
| 4473 |
client_context, server_context, hostname = testing_context() |
| 4474 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4475 |
|
| 4476 |
with server: |
| 4477 |
s = client_context.wrap_socket(socket.socket(), |
| 4478 |
server_hostname=hostname) |
| 4479 |
s.connect((HOST, server.port)) |
| 4480 |
s.close() |
| 4481 |
|
| 4482 |
self.assertRaises(ValueError, s.read, 1024) |
| 4483 |
self.assertRaises(ValueError, s.write, b'hello') |
| 4484 |
|
| 4485 |
def test_sendfile(self): |
| 4486 |
TEST_DATA = b"x" * 512 |
| 4487 |
with open(os_helper.TESTFN, 'wb') as f: |
| 4488 |
f.write(TEST_DATA) |
| 4489 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 4490 |
client_context, server_context, hostname = testing_context() |
| 4491 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4492 |
with server: |
| 4493 |
with client_context.wrap_socket(socket.socket(), |
| 4494 |
server_hostname=hostname) as s: |
| 4495 |
s.connect((HOST, server.port)) |
| 4496 |
with open(os_helper.TESTFN, 'rb') as file: |
| 4497 |
s.sendfile(file) |
| 4498 |
self.assertEqual(s.recv(1024), TEST_DATA) |
| 4499 |
|
| 4500 |
def test_session(self): |
| 4501 |
client_context, server_context, hostname = testing_context() |
| 4502 |
# TODO: sessions aren't compatible with TLSv1.3 yet |
| 4503 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4504 |
|
| 4505 |
# first connection without session |
| 4506 |
stats = server_params_test(client_context, server_context, |
| 4507 |
sni_name=hostname) |
| 4508 |
session = stats['session'] |
| 4509 |
self.assertTrue(session.id) |
| 4510 |
self.assertGreater(session.time, 0) |
| 4511 |
self.assertGreater(session.timeout, 0) |
| 4512 |
self.assertTrue(session.has_ticket) |
| 4513 |
self.assertGreater(session.ticket_lifetime_hint, 0) |
| 4514 |
self.assertFalse(stats['session_reused']) |
| 4515 |
sess_stat = server_context.session_stats() |
| 4516 |
self.assertEqual(sess_stat['accept'], 1) |
| 4517 |
self.assertEqual(sess_stat['hits'], 0) |
| 4518 |
|
| 4519 |
# reuse session |
| 4520 |
stats = server_params_test(client_context, server_context, |
| 4521 |
session=session, sni_name=hostname) |
| 4522 |
sess_stat = server_context.session_stats() |
| 4523 |
self.assertEqual(sess_stat['accept'], 2) |
| 4524 |
self.assertEqual(sess_stat['hits'], 1) |
| 4525 |
self.assertTrue(stats['session_reused']) |
| 4526 |
session2 = stats['session'] |
| 4527 |
self.assertEqual(session2.id, session.id) |
| 4528 |
self.assertEqual(session2, session) |
| 4529 |
self.assertIsNot(session2, session) |
| 4530 |
self.assertGreaterEqual(session2.time, session.time) |
| 4531 |
self.assertGreaterEqual(session2.timeout, session.timeout) |
| 4532 |
|
| 4533 |
# another one without session |
| 4534 |
stats = server_params_test(client_context, server_context, |
| 4535 |
sni_name=hostname) |
| 4536 |
self.assertFalse(stats['session_reused']) |
| 4537 |
session3 = stats['session'] |
| 4538 |
self.assertNotEqual(session3.id, session.id) |
| 4539 |
self.assertNotEqual(session3, session) |
| 4540 |
sess_stat = server_context.session_stats() |
| 4541 |
self.assertEqual(sess_stat['accept'], 3) |
| 4542 |
self.assertEqual(sess_stat['hits'], 1) |
| 4543 |
|
| 4544 |
# reuse session again |
| 4545 |
stats = server_params_test(client_context, server_context, |
| 4546 |
session=session, sni_name=hostname) |
| 4547 |
self.assertTrue(stats['session_reused']) |
| 4548 |
session4 = stats['session'] |
| 4549 |
self.assertEqual(session4.id, session.id) |
| 4550 |
self.assertEqual(session4, session) |
| 4551 |
self.assertGreaterEqual(session4.time, session.time) |
| 4552 |
self.assertGreaterEqual(session4.timeout, session.timeout) |
| 4553 |
sess_stat = server_context.session_stats() |
| 4554 |
self.assertEqual(sess_stat['accept'], 4) |
| 4555 |
self.assertEqual(sess_stat['hits'], 2) |
| 4556 |
|
| 4557 |
def test_session_handling(self): |
| 4558 |
client_context, server_context, hostname = testing_context() |
| 4559 |
client_context2, _, _ = testing_context() |
| 4560 |
|
| 4561 |
# TODO: session reuse does not work with TLSv1.3 |
| 4562 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4563 |
client_context2.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4564 |
|
| 4565 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4566 |
with server: |
| 4567 |
with client_context.wrap_socket(socket.socket(), |
| 4568 |
server_hostname=hostname) as s: |
| 4569 |
# session is None before handshake |
| 4570 |
self.assertEqual(s.session, None) |
| 4571 |
self.assertEqual(s.session_reused, None) |
| 4572 |
s.connect((HOST, server.port)) |
| 4573 |
session = s.session |
| 4574 |
self.assertTrue(session) |
| 4575 |
with self.assertRaises(TypeError) as e: |
| 4576 |
s.session = object |
| 4577 |
self.assertEqual(str(e.exception), 'Value is not a SSLSession.') |
| 4578 |
|
| 4579 |
with client_context.wrap_socket(socket.socket(), |
| 4580 |
server_hostname=hostname) as s: |
| 4581 |
s.connect((HOST, server.port)) |
| 4582 |
# cannot set session after handshake |
| 4583 |
with self.assertRaises(ValueError) as e: |
| 4584 |
s.session = session |
| 4585 |
self.assertEqual(str(e.exception), |
| 4586 |
'Cannot set session after handshake.') |
| 4587 |
|
| 4588 |
with client_context.wrap_socket(socket.socket(), |
| 4589 |
server_hostname=hostname) as s: |
| 4590 |
# can set session before handshake and before the |
| 4591 |
# connection was established |
| 4592 |
s.session = session |
| 4593 |
s.connect((HOST, server.port)) |
| 4594 |
self.assertEqual(s.session.id, session.id) |
| 4595 |
self.assertEqual(s.session, session) |
| 4596 |
self.assertEqual(s.session_reused, True) |
| 4597 |
|
| 4598 |
with client_context2.wrap_socket(socket.socket(), |
| 4599 |
server_hostname=hostname) as s: |
| 4600 |
# cannot re-use session with a different SSLContext |
| 4601 |
with self.assertRaises(ValueError) as e: |
| 4602 |
s.session = session |
| 4603 |
s.connect((HOST, server.port)) |
| 4604 |
self.assertEqual(str(e.exception), |
| 4605 |
'Session refers to a different SSLContext.') |
| 4606 |
|
| 4607 |
@requires_tls_version('TLSv1_2') |
| 4608 |
@unittest.skipUnless(ssl.HAS_PSK, 'TLS-PSK disabled on this OpenSSL build') |
| 4609 |
def test_psk(self): |
| 4610 |
psk = bytes.fromhex('deadbeef') |
| 4611 |
|
| 4612 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4613 |
client_context.check_hostname = False |
| 4614 |
client_context.verify_mode = ssl.CERT_NONE |
| 4615 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4616 |
client_context.set_ciphers('PSK') |
| 4617 |
client_context.set_psk_client_callback(lambda hint: (None, psk)) |
| 4618 |
|
| 4619 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4620 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4621 |
server_context.set_ciphers('PSK') |
| 4622 |
server_context.set_psk_server_callback(lambda identity: psk) |
| 4623 |
|
| 4624 |
# correct PSK should connect |
| 4625 |
server = ThreadedEchoServer(context=server_context) |
| 4626 |
with server: |
| 4627 |
with client_context.wrap_socket(socket.socket()) as s: |
| 4628 |
s.connect((HOST, server.port)) |
| 4629 |
|
| 4630 |
# incorrect PSK should fail |
| 4631 |
incorrect_psk = bytes.fromhex('cafebabe') |
| 4632 |
client_context.set_psk_client_callback(lambda hint: (None, incorrect_psk)) |
| 4633 |
server = ThreadedEchoServer(context=server_context) |
| 4634 |
with server: |
| 4635 |
with client_context.wrap_socket(socket.socket()) as s: |
| 4636 |
with self.assertRaises(ssl.SSLError): |
| 4637 |
s.connect((HOST, server.port)) |
| 4638 |
|
| 4639 |
# identity_hint and client_identity should be sent to the other side |
| 4640 |
identity_hint = 'identity-hint' |
| 4641 |
client_identity = 'client-identity' |
| 4642 |
|
| 4643 |
def client_callback(hint): |
| 4644 |
self.assertEqual(hint, identity_hint) |
| 4645 |
return client_identity, psk |
| 4646 |
|
| 4647 |
def server_callback(identity): |
| 4648 |
self.assertEqual(identity, client_identity) |
| 4649 |
return psk |
| 4650 |
|
| 4651 |
client_context.set_psk_client_callback(client_callback) |
| 4652 |
server_context.set_psk_server_callback(server_callback, identity_hint) |
| 4653 |
server = ThreadedEchoServer(context=server_context) |
| 4654 |
with server: |
| 4655 |
with client_context.wrap_socket(socket.socket()) as s: |
| 4656 |
s.connect((HOST, server.port)) |
| 4657 |
|
| 4658 |
# adding client callback to server or vice versa raises an exception |
| 4659 |
with self.assertRaisesRegex(ssl.SSLError, 'Cannot add PSK server callback'): |
| 4660 |
client_context.set_psk_server_callback(server_callback, identity_hint) |
| 4661 |
with self.assertRaisesRegex(ssl.SSLError, 'Cannot add PSK client callback'): |
| 4662 |
server_context.set_psk_client_callback(client_callback) |
| 4663 |
|
| 4664 |
# test with UTF-8 identities |
| 4665 |
identity_hint = '身份暗示' # Translation: "Identity hint" |
| 4666 |
client_identity = '客户身份' # Translation: "Customer identity" |
| 4667 |
|
| 4668 |
client_context.set_psk_client_callback(client_callback) |
| 4669 |
server_context.set_psk_server_callback(server_callback, identity_hint) |
| 4670 |
server = ThreadedEchoServer(context=server_context) |
| 4671 |
with server: |
| 4672 |
with client_context.wrap_socket(socket.socket()) as s: |
| 4673 |
s.connect((HOST, server.port)) |
| 4674 |
|
| 4675 |
@requires_tls_version('TLSv1_3') |
| 4676 |
@unittest.skipUnless(ssl.HAS_PSK, 'TLS-PSK disabled on this OpenSSL build') |
| 4677 |
def test_psk_tls1_3(self): |
| 4678 |
psk = bytes.fromhex('deadbeef') |
| 4679 |
identity_hint = 'identity-hint' |
| 4680 |
client_identity = 'client-identity' |
| 4681 |
|
| 4682 |
def client_callback(hint): |
| 4683 |
# identity_hint is not sent to the client in TLS 1.3 |
| 4684 |
self.assertIsNone(hint) |
| 4685 |
return client_identity, psk |
| 4686 |
|
| 4687 |
def server_callback(identity): |
| 4688 |
self.assertEqual(identity, client_identity) |
| 4689 |
return psk |
| 4690 |
|
| 4691 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4692 |
client_context.check_hostname = False |
| 4693 |
client_context.verify_mode = ssl.CERT_NONE |
| 4694 |
client_context.minimum_version = ssl.TLSVersion.TLSv1_3 |
| 4695 |
client_context.set_ciphers('PSK') |
| 4696 |
client_context.set_psk_client_callback(client_callback) |
| 4697 |
|
| 4698 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4699 |
server_context.minimum_version = ssl.TLSVersion.TLSv1_3 |
| 4700 |
server_context.set_ciphers('PSK') |
| 4701 |
server_context.set_psk_server_callback(server_callback, identity_hint) |
| 4702 |
|
| 4703 |
server = ThreadedEchoServer(context=server_context) |
| 4704 |
with server: |
| 4705 |
with client_context.wrap_socket(socket.socket()) as s: |
| 4706 |
s.connect((HOST, server.port)) |
| 4707 |
|
| 4708 |
def test_thread_recv_while_main_thread_sends(self): |
| 4709 |
# GH-137583: Locking was added to calls to send() and recv() on SSL |
| 4710 |
# socket objects. This seemed fine at the surface level because those |
| 4711 |
# calls weren't re-entrant, but recv() calls would implicitly mimick |
| 4712 |
# holding a lock by blocking until it received data. This means that |
| 4713 |
# if a thread started to infinitely block until data was received, calls |
| 4714 |
# to send() would deadlock, because it would wait forever on the lock |
| 4715 |
# that the recv() call held. |
| 4716 |
data = b"1" * 1024 |
| 4717 |
event = threading.Event() |
| 4718 |
def background(sock): |
| 4719 |
event.set() |
| 4720 |
received = sock.recv(len(data)) |
| 4721 |
self.assertEqual(received, data) |
| 4722 |
|
| 4723 |
client_context, server_context, hostname = testing_context() |
| 4724 |
server = ThreadedEchoServer(context=server_context) |
| 4725 |
with server: |
| 4726 |
with client_context.wrap_socket(socket.socket(), |
| 4727 |
server_hostname=hostname) as sock: |
| 4728 |
sock.connect((HOST, server.port)) |
| 4729 |
sock.settimeout(1) |
| 4730 |
sock.setblocking(1) |
| 4731 |
# Ensure that the server is ready to accept requests |
| 4732 |
sock.sendall(b"123") |
| 4733 |
self.assertEqual(sock.recv(3), b"123") |
| 4734 |
with threading_helper.catch_threading_exception() as cm: |
| 4735 |
thread = threading.Thread(target=background, |
| 4736 |
args=(sock,), daemon=True) |
| 4737 |
thread.start() |
| 4738 |
event.wait() |
| 4739 |
sock.sendall(data) |
| 4740 |
thread.join() |
| 4741 |
if cm.exc_value is not None: |
| 4742 |
raise cm.exc_value |
| 4743 |
|
| 4744 |
|
| 4745 |
@unittest.skipUnless(has_tls_version('TLSv1_3') and ssl.HAS_PHA, |
| 4746 |
"Test needs TLS 1.3 PHA") |
| 4747 |
class TestPostHandshakeAuth(unittest.TestCase): |
| 4748 |
def test_pha_setter(self): |
| 4749 |
protocols = [ |
| 4750 |
ssl.PROTOCOL_TLS_SERVER, ssl.PROTOCOL_TLS_CLIENT |
| 4751 |
] |
| 4752 |
for protocol in protocols: |
| 4753 |
ctx = ssl.SSLContext(protocol) |
| 4754 |
self.assertEqual(ctx.post_handshake_auth, False) |
| 4755 |
|
| 4756 |
ctx.post_handshake_auth = True |
| 4757 |
self.assertEqual(ctx.post_handshake_auth, True) |
| 4758 |
|
| 4759 |
ctx.verify_mode = ssl.CERT_REQUIRED |
| 4760 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 4761 |
self.assertEqual(ctx.post_handshake_auth, True) |
| 4762 |
|
| 4763 |
ctx.post_handshake_auth = False |
| 4764 |
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) |
| 4765 |
self.assertEqual(ctx.post_handshake_auth, False) |
| 4766 |
|
| 4767 |
ctx.verify_mode = ssl.CERT_OPTIONAL |
| 4768 |
ctx.post_handshake_auth = True |
| 4769 |
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) |
| 4770 |
self.assertEqual(ctx.post_handshake_auth, True) |
| 4771 |
|
| 4772 |
def test_pha_required(self): |
| 4773 |
client_context, server_context, hostname = testing_context() |
| 4774 |
server_context.post_handshake_auth = True |
| 4775 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4776 |
client_context.post_handshake_auth = True |
| 4777 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4778 |
|
| 4779 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4780 |
with server: |
| 4781 |
with client_context.wrap_socket(socket.socket(), |
| 4782 |
server_hostname=hostname) as s: |
| 4783 |
s.connect((HOST, server.port)) |
| 4784 |
s.write(b'HASCERT') |
| 4785 |
self.assertEqual(s.recv(1024), b'FALSE\n') |
| 4786 |
s.write(b'PHA') |
| 4787 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4788 |
s.write(b'HASCERT') |
| 4789 |
self.assertEqual(s.recv(1024), b'TRUE\n') |
| 4790 |
# PHA method just returns true when cert is already available |
| 4791 |
s.write(b'PHA') |
| 4792 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4793 |
s.write(b'GETCERT') |
| 4794 |
cert_text = s.recv(4096).decode('us-ascii') |
| 4795 |
self.assertIn('Python Software Foundation CA', cert_text) |
| 4796 |
|
| 4797 |
def test_pha_required_nocert(self): |
| 4798 |
client_context, server_context, hostname = testing_context() |
| 4799 |
server_context.post_handshake_auth = True |
| 4800 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4801 |
client_context.post_handshake_auth = True |
| 4802 |
|
| 4803 |
def msg_cb(conn, direction, version, content_type, msg_type, data): |
| 4804 |
if support.verbose and content_type == _TLSContentType.ALERT: |
| 4805 |
info = (conn, direction, version, content_type, msg_type, data) |
| 4806 |
sys.stdout.write(f"TLS: {info!r}\n") |
| 4807 |
|
| 4808 |
server_context._msg_callback = msg_cb |
| 4809 |
client_context._msg_callback = msg_cb |
| 4810 |
|
| 4811 |
server = ThreadedEchoServer(context=server_context, chatty=True) |
| 4812 |
with server: |
| 4813 |
with client_context.wrap_socket(socket.socket(), |
| 4814 |
server_hostname=hostname, |
| 4815 |
suppress_ragged_eofs=False) as s: |
| 4816 |
s.connect((HOST, server.port)) |
| 4817 |
s.write(b'PHA') |
| 4818 |
# test sometimes fails with EOF error. Test passes as long as |
| 4819 |
# server aborts connection with an error. |
| 4820 |
with self.assertRaisesRegex( |
| 4821 |
OSError, |
| 4822 |
('certificate required' |
| 4823 |
'|EOF occurred' |
| 4824 |
'|closed by the remote host' |
| 4825 |
'|Connection reset by peer' |
| 4826 |
'|Broken pipe') |
| 4827 |
): |
| 4828 |
# receive CertificateRequest |
| 4829 |
data = s.recv(1024) |
| 4830 |
self.assertEqual(data, b'OK\n') |
| 4831 |
|
| 4832 |
# send empty Certificate + Finish |
| 4833 |
s.write(b'HASCERT') |
| 4834 |
|
| 4835 |
# receive alert |
| 4836 |
s.recv(1024) |
| 4837 |
|
| 4838 |
def test_pha_optional(self): |
| 4839 |
if support.verbose: |
| 4840 |
sys.stdout.write("\n") |
| 4841 |
|
| 4842 |
client_context, server_context, hostname = testing_context() |
| 4843 |
server_context.post_handshake_auth = True |
| 4844 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4845 |
client_context.post_handshake_auth = True |
| 4846 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4847 |
|
| 4848 |
# check CERT_OPTIONAL |
| 4849 |
server_context.verify_mode = ssl.CERT_OPTIONAL |
| 4850 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4851 |
with server: |
| 4852 |
with client_context.wrap_socket(socket.socket(), |
| 4853 |
server_hostname=hostname) as s: |
| 4854 |
s.connect((HOST, server.port)) |
| 4855 |
s.write(b'HASCERT') |
| 4856 |
self.assertEqual(s.recv(1024), b'FALSE\n') |
| 4857 |
s.write(b'PHA') |
| 4858 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4859 |
s.write(b'HASCERT') |
| 4860 |
self.assertEqual(s.recv(1024), b'TRUE\n') |
| 4861 |
|
| 4862 |
def test_pha_optional_nocert(self): |
| 4863 |
if support.verbose: |
| 4864 |
sys.stdout.write("\n") |
| 4865 |
|
| 4866 |
client_context, server_context, hostname = testing_context() |
| 4867 |
server_context.post_handshake_auth = True |
| 4868 |
server_context.verify_mode = ssl.CERT_OPTIONAL |
| 4869 |
client_context.post_handshake_auth = True |
| 4870 |
|
| 4871 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4872 |
with server: |
| 4873 |
with client_context.wrap_socket(socket.socket(), |
| 4874 |
server_hostname=hostname) as s: |
| 4875 |
s.connect((HOST, server.port)) |
| 4876 |
s.write(b'HASCERT') |
| 4877 |
self.assertEqual(s.recv(1024), b'FALSE\n') |
| 4878 |
s.write(b'PHA') |
| 4879 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4880 |
# optional doesn't fail when client does not have a cert |
| 4881 |
s.write(b'HASCERT') |
| 4882 |
self.assertEqual(s.recv(1024), b'FALSE\n') |
| 4883 |
|
| 4884 |
def test_pha_no_pha_client(self): |
| 4885 |
client_context, server_context, hostname = testing_context() |
| 4886 |
server_context.post_handshake_auth = True |
| 4887 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4888 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4889 |
|
| 4890 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4891 |
with server: |
| 4892 |
with client_context.wrap_socket(socket.socket(), |
| 4893 |
server_hostname=hostname) as s: |
| 4894 |
s.connect((HOST, server.port)) |
| 4895 |
with self.assertRaisesRegex(ssl.SSLError, 'not server'): |
| 4896 |
s.verify_client_post_handshake() |
| 4897 |
s.write(b'PHA') |
| 4898 |
self.assertIn(b'extension not received', s.recv(1024)) |
| 4899 |
|
| 4900 |
def test_pha_no_pha_server(self): |
| 4901 |
# server doesn't have PHA enabled, cert is requested in handshake |
| 4902 |
client_context, server_context, hostname = testing_context() |
| 4903 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4904 |
client_context.post_handshake_auth = True |
| 4905 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4906 |
|
| 4907 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4908 |
with server: |
| 4909 |
with client_context.wrap_socket(socket.socket(), |
| 4910 |
server_hostname=hostname) as s: |
| 4911 |
s.connect((HOST, server.port)) |
| 4912 |
s.write(b'HASCERT') |
| 4913 |
self.assertEqual(s.recv(1024), b'TRUE\n') |
| 4914 |
# PHA doesn't fail if there is already a cert |
| 4915 |
s.write(b'PHA') |
| 4916 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4917 |
s.write(b'HASCERT') |
| 4918 |
self.assertEqual(s.recv(1024), b'TRUE\n') |
| 4919 |
|
| 4920 |
def test_pha_not_tls13(self): |
| 4921 |
# TLS 1.2 |
| 4922 |
client_context, server_context, hostname = testing_context() |
| 4923 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4924 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 4925 |
client_context.post_handshake_auth = True |
| 4926 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4927 |
|
| 4928 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4929 |
with server: |
| 4930 |
with client_context.wrap_socket(socket.socket(), |
| 4931 |
server_hostname=hostname) as s: |
| 4932 |
s.connect((HOST, server.port)) |
| 4933 |
# PHA fails for TLS != 1.3 |
| 4934 |
s.write(b'PHA') |
| 4935 |
self.assertIn(b'WRONG_SSL_VERSION', s.recv(1024)) |
| 4936 |
|
| 4937 |
def test_bpo37428_pha_cert_none(self): |
| 4938 |
# verify that post_handshake_auth does not implicitly enable cert |
| 4939 |
# validation. |
| 4940 |
hostname = SIGNED_CERTFILE_HOSTNAME |
| 4941 |
client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 4942 |
client_context.post_handshake_auth = True |
| 4943 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 4944 |
# no cert validation and CA on client side |
| 4945 |
client_context.check_hostname = False |
| 4946 |
client_context.verify_mode = ssl.CERT_NONE |
| 4947 |
|
| 4948 |
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 4949 |
server_context.load_cert_chain(SIGNED_CERTFILE) |
| 4950 |
server_context.load_verify_locations(SIGNING_CA) |
| 4951 |
server_context.post_handshake_auth = True |
| 4952 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 4953 |
|
| 4954 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4955 |
with server: |
| 4956 |
with client_context.wrap_socket(socket.socket(), |
| 4957 |
server_hostname=hostname) as s: |
| 4958 |
s.connect((HOST, server.port)) |
| 4959 |
s.write(b'HASCERT') |
| 4960 |
self.assertEqual(s.recv(1024), b'FALSE\n') |
| 4961 |
s.write(b'PHA') |
| 4962 |
self.assertEqual(s.recv(1024), b'OK\n') |
| 4963 |
s.write(b'HASCERT') |
| 4964 |
self.assertEqual(s.recv(1024), b'TRUE\n') |
| 4965 |
# server cert has not been validated |
| 4966 |
self.assertEqual(s.getpeercert(), {}) |
| 4967 |
|
| 4968 |
def test_internal_chain_client(self): |
| 4969 |
client_context, server_context, hostname = testing_context( |
| 4970 |
server_chain=False |
| 4971 |
) |
| 4972 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 4973 |
with server: |
| 4974 |
with client_context.wrap_socket( |
| 4975 |
socket.socket(), |
| 4976 |
server_hostname=hostname |
| 4977 |
) as s: |
| 4978 |
s.connect((HOST, server.port)) |
| 4979 |
vc = s._sslobj.get_verified_chain() |
| 4980 |
self.assertEqual(len(vc), 2) |
| 4981 |
ee, ca = vc |
| 4982 |
uvc = s._sslobj.get_unverified_chain() |
| 4983 |
self.assertEqual(len(uvc), 1) |
| 4984 |
|
| 4985 |
self.assertEqual(ee, uvc[0]) |
| 4986 |
self.assertEqual(hash(ee), hash(uvc[0])) |
| 4987 |
self.assertEqual(repr(ee), repr(uvc[0])) |
| 4988 |
|
| 4989 |
self.assertNotEqual(ee, ca) |
| 4990 |
self.assertNotEqual(hash(ee), hash(ca)) |
| 4991 |
self.assertNotEqual(repr(ee), repr(ca)) |
| 4992 |
self.assertNotEqual(ee.get_info(), ca.get_info()) |
| 4993 |
self.assertIn("CN=localhost", repr(ee)) |
| 4994 |
self.assertIn("CN=our-ca-server", repr(ca)) |
| 4995 |
|
| 4996 |
pem = ee.public_bytes(_ssl.ENCODING_PEM) |
| 4997 |
der = ee.public_bytes(_ssl.ENCODING_DER) |
| 4998 |
self.assertIsInstance(pem, str) |
| 4999 |
self.assertIn("-----BEGIN CERTIFICATE-----", pem) |
| 5000 |
self.assertIsInstance(der, bytes) |
| 5001 |
self.assertEqual( |
| 5002 |
ssl.PEM_cert_to_DER_cert(pem), der |
| 5003 |
) |
| 5004 |
|
| 5005 |
def test_certificate_chain(self): |
| 5006 |
client_context, server_context, hostname = testing_context( |
| 5007 |
server_chain=False |
| 5008 |
) |
| 5009 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5010 |
|
| 5011 |
with open(SIGNING_CA) as f: |
| 5012 |
expected_ca_cert = ssl.PEM_cert_to_DER_cert(f.read()) |
| 5013 |
|
| 5014 |
with open(SINGED_CERTFILE_ONLY) as f: |
| 5015 |
expected_ee_cert = ssl.PEM_cert_to_DER_cert(f.read()) |
| 5016 |
|
| 5017 |
with server: |
| 5018 |
with client_context.wrap_socket( |
| 5019 |
socket.socket(), |
| 5020 |
server_hostname=hostname |
| 5021 |
) as s: |
| 5022 |
s.connect((HOST, server.port)) |
| 5023 |
vc = s.get_verified_chain() |
| 5024 |
self.assertEqual(len(vc), 2) |
| 5025 |
|
| 5026 |
ee, ca = vc |
| 5027 |
self.assertIsInstance(ee, bytes) |
| 5028 |
self.assertIsInstance(ca, bytes) |
| 5029 |
self.assertEqual(expected_ca_cert, ca) |
| 5030 |
self.assertEqual(expected_ee_cert, ee) |
| 5031 |
|
| 5032 |
uvc = s.get_unverified_chain() |
| 5033 |
self.assertEqual(len(uvc), 1) |
| 5034 |
self.assertIsInstance(uvc[0], bytes) |
| 5035 |
|
| 5036 |
self.assertEqual(ee, uvc[0]) |
| 5037 |
self.assertNotEqual(ee, ca) |
| 5038 |
|
| 5039 |
def test_internal_chain_server(self): |
| 5040 |
client_context, server_context, hostname = testing_context() |
| 5041 |
client_context.load_cert_chain(SIGNED_CERTFILE) |
| 5042 |
server_context.verify_mode = ssl.CERT_REQUIRED |
| 5043 |
server_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 5044 |
|
| 5045 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5046 |
with server: |
| 5047 |
with client_context.wrap_socket( |
| 5048 |
socket.socket(), |
| 5049 |
server_hostname=hostname |
| 5050 |
) as s: |
| 5051 |
s.connect((HOST, server.port)) |
| 5052 |
s.write(b'VERIFIEDCHAIN\n') |
| 5053 |
res = s.recv(1024) |
| 5054 |
self.assertEqual(res, b'\x02\n') |
| 5055 |
s.write(b'UNVERIFIEDCHAIN\n') |
| 5056 |
res = s.recv(1024) |
| 5057 |
self.assertEqual(res, b'\x02\n') |
| 5058 |
|
| 5059 |
|
| 5060 |
class TestSSLDebug(unittest.TestCase): |
| 5061 |
|
| 5062 |
def keylog_lines(self, fname=os_helper.TESTFN): |
| 5063 |
with open(fname) as f: |
| 5064 |
return len(list(f)) |
| 5065 |
|
| 5066 |
@requires_keylog |
| 5067 |
def test_keylog_defaults(self): |
| 5068 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 5069 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 5070 |
self.assertEqual(ctx.keylog_filename, None) |
| 5071 |
|
| 5072 |
self.assertFalse(os.path.isfile(os_helper.TESTFN)) |
| 5073 |
try: |
| 5074 |
ctx.keylog_filename = os_helper.TESTFN |
| 5075 |
except RuntimeError: |
| 5076 |
if Py_DEBUG_WIN32: |
| 5077 |
self.skipTest("not supported on Win32 debug build") |
| 5078 |
raise |
| 5079 |
self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) |
| 5080 |
self.assertTrue(os.path.isfile(os_helper.TESTFN)) |
| 5081 |
self.assertEqual(self.keylog_lines(), 1) |
| 5082 |
|
| 5083 |
ctx.keylog_filename = None |
| 5084 |
self.assertEqual(ctx.keylog_filename, None) |
| 5085 |
|
| 5086 |
with self.assertRaises((IsADirectoryError, PermissionError)): |
| 5087 |
# Windows raises PermissionError |
| 5088 |
ctx.keylog_filename = os.path.dirname( |
| 5089 |
os.path.abspath(os_helper.TESTFN)) |
| 5090 |
|
| 5091 |
with self.assertRaises(TypeError): |
| 5092 |
ctx.keylog_filename = 1 |
| 5093 |
|
| 5094 |
@requires_keylog |
| 5095 |
def test_keylog_filename(self): |
| 5096 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 5097 |
client_context, server_context, hostname = testing_context() |
| 5098 |
|
| 5099 |
try: |
| 5100 |
client_context.keylog_filename = os_helper.TESTFN |
| 5101 |
except RuntimeError: |
| 5102 |
if Py_DEBUG_WIN32: |
| 5103 |
self.skipTest("not supported on Win32 debug build") |
| 5104 |
raise |
| 5105 |
|
| 5106 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5107 |
with server: |
| 5108 |
with client_context.wrap_socket(socket.socket(), |
| 5109 |
server_hostname=hostname) as s: |
| 5110 |
s.connect((HOST, server.port)) |
| 5111 |
# header, 5 lines for TLS 1.3 |
| 5112 |
self.assertEqual(self.keylog_lines(), 6) |
| 5113 |
|
| 5114 |
client_context.keylog_filename = None |
| 5115 |
server_context.keylog_filename = os_helper.TESTFN |
| 5116 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5117 |
with server: |
| 5118 |
with client_context.wrap_socket(socket.socket(), |
| 5119 |
server_hostname=hostname) as s: |
| 5120 |
s.connect((HOST, server.port)) |
| 5121 |
self.assertGreaterEqual(self.keylog_lines(), 11) |
| 5122 |
|
| 5123 |
client_context.keylog_filename = os_helper.TESTFN |
| 5124 |
server_context.keylog_filename = os_helper.TESTFN |
| 5125 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5126 |
with server: |
| 5127 |
with client_context.wrap_socket(socket.socket(), |
| 5128 |
server_hostname=hostname) as s: |
| 5129 |
s.connect((HOST, server.port)) |
| 5130 |
self.assertGreaterEqual(self.keylog_lines(), 21) |
| 5131 |
|
| 5132 |
client_context.keylog_filename = None |
| 5133 |
server_context.keylog_filename = None |
| 5134 |
|
| 5135 |
@requires_keylog |
| 5136 |
@unittest.skipIf(sys.flags.ignore_environment, |
| 5137 |
"test is not compatible with ignore_environment") |
| 5138 |
def test_keylog_env(self): |
| 5139 |
self.addCleanup(os_helper.unlink, os_helper.TESTFN) |
| 5140 |
with unittest.mock.patch.dict(os.environ): |
| 5141 |
os.environ['SSLKEYLOGFILE'] = os_helper.TESTFN |
| 5142 |
self.assertEqual(os.environ['SSLKEYLOGFILE'], os_helper.TESTFN) |
| 5143 |
|
| 5144 |
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 5145 |
self.assertEqual(ctx.keylog_filename, None) |
| 5146 |
|
| 5147 |
try: |
| 5148 |
ctx = ssl.create_default_context() |
| 5149 |
except RuntimeError: |
| 5150 |
if Py_DEBUG_WIN32: |
| 5151 |
self.skipTest("not supported on Win32 debug build") |
| 5152 |
raise |
| 5153 |
self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) |
| 5154 |
|
| 5155 |
ctx = ssl._create_stdlib_context() |
| 5156 |
self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) |
| 5157 |
|
| 5158 |
def test_msg_callback(self): |
| 5159 |
client_context, server_context, hostname = testing_context() |
| 5160 |
|
| 5161 |
def msg_cb(conn, direction, version, content_type, msg_type, data): |
| 5162 |
pass |
| 5163 |
|
| 5164 |
self.assertIs(client_context._msg_callback, None) |
| 5165 |
client_context._msg_callback = msg_cb |
| 5166 |
self.assertIs(client_context._msg_callback, msg_cb) |
| 5167 |
with self.assertRaises(TypeError): |
| 5168 |
client_context._msg_callback = object() |
| 5169 |
|
| 5170 |
def test_msg_callback_tls12(self): |
| 5171 |
client_context, server_context, hostname = testing_context() |
| 5172 |
client_context.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 5173 |
|
| 5174 |
msg = [] |
| 5175 |
|
| 5176 |
def msg_cb(conn, direction, version, content_type, msg_type, data): |
| 5177 |
self.assertIsInstance(conn, ssl.SSLSocket) |
| 5178 |
self.assertIsInstance(data, bytes) |
| 5179 |
self.assertIn(direction, {'read', 'write'}) |
| 5180 |
msg.append((direction, version, content_type, msg_type)) |
| 5181 |
|
| 5182 |
client_context._msg_callback = msg_cb |
| 5183 |
|
| 5184 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5185 |
with server: |
| 5186 |
with client_context.wrap_socket(socket.socket(), |
| 5187 |
server_hostname=hostname) as s: |
| 5188 |
s.connect((HOST, server.port)) |
| 5189 |
|
| 5190 |
self.assertIn( |
| 5191 |
("read", TLSVersion.TLSv1_2, _TLSContentType.HANDSHAKE, |
| 5192 |
_TLSMessageType.SERVER_KEY_EXCHANGE), |
| 5193 |
msg |
| 5194 |
) |
| 5195 |
self.assertIn( |
| 5196 |
("write", TLSVersion.TLSv1_2, _TLSContentType.CHANGE_CIPHER_SPEC, |
| 5197 |
_TLSMessageType.CHANGE_CIPHER_SPEC), |
| 5198 |
msg |
| 5199 |
) |
| 5200 |
|
| 5201 |
def test_msg_callback_deadlock_bpo43577(self): |
| 5202 |
client_context, server_context, hostname = testing_context() |
| 5203 |
server_context2 = testing_context()[1] |
| 5204 |
|
| 5205 |
def msg_cb(conn, direction, version, content_type, msg_type, data): |
| 5206 |
pass |
| 5207 |
|
| 5208 |
def sni_cb(sock, servername, ctx): |
| 5209 |
sock.context = server_context2 |
| 5210 |
|
| 5211 |
server_context._msg_callback = msg_cb |
| 5212 |
server_context.sni_callback = sni_cb |
| 5213 |
|
| 5214 |
server = ThreadedEchoServer(context=server_context, chatty=False) |
| 5215 |
with server: |
| 5216 |
with client_context.wrap_socket(socket.socket(), |
| 5217 |
server_hostname=hostname) as s: |
| 5218 |
s.connect((HOST, server.port)) |
| 5219 |
with client_context.wrap_socket(socket.socket(), |
| 5220 |
server_hostname=hostname) as s: |
| 5221 |
s.connect((HOST, server.port)) |
| 5222 |
|
| 5223 |
|
| 5224 |
def set_socket_so_linger_on_with_zero_timeout(sock): |
| 5225 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) |
| 5226 |
|
| 5227 |
|
| 5228 |
class TestPreHandshakeClose(unittest.TestCase): |
| 5229 |
"""Verify behavior of close sockets with received data before to the handshake. |
| 5230 |
""" |
| 5231 |
|
| 5232 |
class SingleConnectionTestServerThread(threading.Thread): |
| 5233 |
|
| 5234 |
def __init__(self, *, name, call_after_accept, timeout=None): |
| 5235 |
self.call_after_accept = call_after_accept |
| 5236 |
self.received_data = b'' # set by .run() |
| 5237 |
self.wrap_error = None # set by .run() |
| 5238 |
self.listener = None # set by .start() |
| 5239 |
self.port = None # set by .start() |
| 5240 |
if timeout is None: |
| 5241 |
self.timeout = support.SHORT_TIMEOUT |
| 5242 |
else: |
| 5243 |
self.timeout = timeout |
| 5244 |
super().__init__(name=name) |
| 5245 |
|
| 5246 |
def __enter__(self): |
| 5247 |
self.start() |
| 5248 |
return self |
| 5249 |
|
| 5250 |
def __exit__(self, *args): |
| 5251 |
try: |
| 5252 |
if self.listener: |
| 5253 |
self.listener.close() |
| 5254 |
except OSError: |
| 5255 |
pass |
| 5256 |
self.join() |
| 5257 |
self.wrap_error = None # avoid dangling references |
| 5258 |
|
| 5259 |
def start(self): |
| 5260 |
self.ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
| 5261 |
self.ssl_ctx.verify_mode = ssl.CERT_REQUIRED |
| 5262 |
self.ssl_ctx.load_verify_locations(cafile=ONLYCERT) |
| 5263 |
self.ssl_ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY) |
| 5264 |
self.listener = socket.socket() |
| 5265 |
self.port = socket_helper.bind_port(self.listener) |
| 5266 |
self.listener.settimeout(self.timeout) |
| 5267 |
self.listener.listen(1) |
| 5268 |
super().start() |
| 5269 |
|
| 5270 |
def run(self): |
| 5271 |
try: |
| 5272 |
conn, address = self.listener.accept() |
| 5273 |
except TimeoutError: |
| 5274 |
# on timeout, just close the listener |
| 5275 |
return |
| 5276 |
finally: |
| 5277 |
self.listener.close() |
| 5278 |
|
| 5279 |
with conn: |
| 5280 |
if self.call_after_accept(conn): |
| 5281 |
return |
| 5282 |
try: |
| 5283 |
tls_socket = self.ssl_ctx.wrap_socket(conn, server_side=True) |
| 5284 |
except OSError as err: # ssl.SSLError inherits from OSError |
| 5285 |
self.wrap_error = err |
| 5286 |
else: |
| 5287 |
try: |
| 5288 |
self.received_data = tls_socket.recv(400) |
| 5289 |
except OSError: |
| 5290 |
pass # closed, protocol error, etc. |
| 5291 |
|
| 5292 |
def non_linux_skip_if_other_okay_error(self, err): |
| 5293 |
if sys.platform in ("linux", "android"): |
| 5294 |
return # Expect the full test setup to always work on Linux. |
| 5295 |
if (isinstance(err, ConnectionResetError) or |
| 5296 |
(isinstance(err, OSError) and err.errno == errno.EINVAL) or |
| 5297 |
re.search('wrong.version.number', str(getattr(err, "reason", "")), re.I) or |
| 5298 |
re.search('record.layer.failure', str(getattr(err, "reason", "")), re.I) |
| 5299 |
): |
| 5300 |
# On Windows the TCP RST leads to a ConnectionResetError |
| 5301 |
# (ECONNRESET) which Linux doesn't appear to surface to userspace. |
| 5302 |
# If wrap_socket() winds up on the "if connected:" path and doing |
| 5303 |
# the actual wrapping... we get an SSLError from OpenSSL. This is |
| 5304 |
# typically WRONG_VERSION_NUMBER. The same happens on iOS, but |
| 5305 |
# RECORD_LAYER_FAILURE is the error. |
| 5306 |
# |
| 5307 |
# While appropriate, neither is the scenario we're specifically |
| 5308 |
# trying to test. The way this test is written is known to work on |
| 5309 |
# Linux. We'll skip it anywhere else that it does not present as |
| 5310 |
# doing so. |
| 5311 |
try: |
| 5312 |
self.skipTest(f"Could not recreate conditions on {sys.platform}:" |
| 5313 |
f" {err=}") |
| 5314 |
finally: |
| 5315 |
# gh-108342: Explicitly break the reference cycle |
| 5316 |
err = None |
| 5317 |
|
| 5318 |
# If maintaining this conditional winds up being a problem. |
| 5319 |
# just turn this into an unconditional skip anything but Linux. |
| 5320 |
# The important thing is that our CI has the logic covered. |
| 5321 |
|
| 5322 |
def test_preauth_data_to_tls_server(self): |
| 5323 |
server_accept_called = threading.Event() |
| 5324 |
ready_for_server_wrap_socket = threading.Event() |
| 5325 |
|
| 5326 |
def call_after_accept(unused): |
| 5327 |
server_accept_called.set() |
| 5328 |
if not ready_for_server_wrap_socket.wait(support.SHORT_TIMEOUT): |
| 5329 |
raise RuntimeError("wrap_socket event never set, test may fail.") |
| 5330 |
return False # Tell the server thread to continue. |
| 5331 |
|
| 5332 |
server = self.SingleConnectionTestServerThread( |
| 5333 |
call_after_accept=call_after_accept, |
| 5334 |
name="preauth_data_to_tls_server") |
| 5335 |
self.enterContext(server) # starts it & unittest.TestCase stops it. |
| 5336 |
|
| 5337 |
with socket.socket() as client: |
| 5338 |
client.connect(server.listener.getsockname()) |
| 5339 |
# This forces an immediate connection close via RST on .close(). |
| 5340 |
set_socket_so_linger_on_with_zero_timeout(client) |
| 5341 |
client.setblocking(False) |
| 5342 |
|
| 5343 |
server_accept_called.wait() |
| 5344 |
client.send(b"DELETE /data HTTP/1.0\r\n\r\n") |
| 5345 |
client.close() # RST |
| 5346 |
|
| 5347 |
ready_for_server_wrap_socket.set() |
| 5348 |
server.join() |
| 5349 |
|
| 5350 |
wrap_error = server.wrap_error |
| 5351 |
server.wrap_error = None |
| 5352 |
try: |
| 5353 |
self.assertEqual(b"", server.received_data) |
| 5354 |
self.assertIsInstance(wrap_error, OSError) # All platforms. |
| 5355 |
self.non_linux_skip_if_other_okay_error(wrap_error) |
| 5356 |
self.assertIsInstance(wrap_error, ssl.SSLError) |
| 5357 |
self.assertIn("before TLS handshake with data", wrap_error.args[1]) |
| 5358 |
self.assertIn("before TLS handshake with data", wrap_error.reason) |
| 5359 |
self.assertNotEqual(0, wrap_error.args[0]) |
| 5360 |
self.assertIsNone(wrap_error.library, msg="attr must exist") |
| 5361 |
finally: |
| 5362 |
# gh-108342: Explicitly break the reference cycle |
| 5363 |
wrap_error = None |
| 5364 |
server = None |
| 5365 |
|
| 5366 |
def test_preauth_data_to_tls_client(self): |
| 5367 |
server_can_continue_with_wrap_socket = threading.Event() |
| 5368 |
client_can_continue_with_wrap_socket = threading.Event() |
| 5369 |
|
| 5370 |
def call_after_accept(conn_to_client): |
| 5371 |
if not server_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT): |
| 5372 |
print("ERROR: test client took too long") |
| 5373 |
|
| 5374 |
# This forces an immediate connection close via RST on .close(). |
| 5375 |
set_socket_so_linger_on_with_zero_timeout(conn_to_client) |
| 5376 |
conn_to_client.send( |
| 5377 |
b"HTTP/1.0 307 Temporary Redirect\r\n" |
| 5378 |
b"Location: https://example.com/someone-elses-server\r\n" |
| 5379 |
b"\r\n") |
| 5380 |
conn_to_client.close() # RST |
| 5381 |
client_can_continue_with_wrap_socket.set() |
| 5382 |
return True # Tell the server to stop. |
| 5383 |
|
| 5384 |
server = self.SingleConnectionTestServerThread( |
| 5385 |
call_after_accept=call_after_accept, |
| 5386 |
name="preauth_data_to_tls_client") |
| 5387 |
self.enterContext(server) # starts it & unittest.TestCase stops it. |
| 5388 |
# Redundant; call_after_accept sets SO_LINGER on the accepted conn. |
| 5389 |
set_socket_so_linger_on_with_zero_timeout(server.listener) |
| 5390 |
|
| 5391 |
with socket.socket() as client: |
| 5392 |
client.connect(server.listener.getsockname()) |
| 5393 |
server_can_continue_with_wrap_socket.set() |
| 5394 |
|
| 5395 |
if not client_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT): |
| 5396 |
self.fail("test server took too long") |
| 5397 |
ssl_ctx = ssl.create_default_context() |
| 5398 |
try: |
| 5399 |
tls_client = ssl_ctx.wrap_socket( |
| 5400 |
client, server_hostname="localhost") |
| 5401 |
except OSError as err: # SSLError inherits from OSError |
| 5402 |
wrap_error = err |
| 5403 |
received_data = b"" |
| 5404 |
else: |
| 5405 |
wrap_error = None |
| 5406 |
received_data = tls_client.recv(400) |
| 5407 |
tls_client.close() |
| 5408 |
|
| 5409 |
server.join() |
| 5410 |
try: |
| 5411 |
self.assertEqual(b"", received_data) |
| 5412 |
self.assertIsInstance(wrap_error, OSError) # All platforms. |
| 5413 |
self.non_linux_skip_if_other_okay_error(wrap_error) |
| 5414 |
self.assertIsInstance(wrap_error, ssl.SSLError) |
| 5415 |
self.assertIn("before TLS handshake with data", wrap_error.args[1]) |
| 5416 |
self.assertIn("before TLS handshake with data", wrap_error.reason) |
| 5417 |
self.assertNotEqual(0, wrap_error.args[0]) |
| 5418 |
self.assertIsNone(wrap_error.library, msg="attr must exist") |
| 5419 |
finally: |
| 5420 |
# gh-108342: Explicitly break the reference cycle |
| 5421 |
with warnings_helper.check_no_resource_warning(self): |
| 5422 |
wrap_error = None |
| 5423 |
server = None |
| 5424 |
|
| 5425 |
def test_https_client_non_tls_response_ignored(self): |
| 5426 |
server_responding = threading.Event() |
| 5427 |
|
| 5428 |
class SynchronizedHTTPSConnection(http.client.HTTPSConnection): |
| 5429 |
def connect(self): |
| 5430 |
# Call clear text HTTP connect(), not the encrypted HTTPS (TLS) |
| 5431 |
# connect(): wrap_socket() is called manually below. |
| 5432 |
http.client.HTTPConnection.connect(self) |
| 5433 |
|
| 5434 |
# Wait for our fault injection server to have done its thing. |
| 5435 |
if not server_responding.wait(support.SHORT_TIMEOUT) and support.verbose: |
| 5436 |
sys.stdout.write("server_responding event never set.") |
| 5437 |
self.sock = self._context.wrap_socket( |
| 5438 |
self.sock, server_hostname=self.host) |
| 5439 |
|
| 5440 |
def call_after_accept(conn_to_client): |
| 5441 |
# This forces an immediate connection close via RST on .close(). |
| 5442 |
set_socket_so_linger_on_with_zero_timeout(conn_to_client) |
| 5443 |
conn_to_client.send( |
| 5444 |
b"HTTP/1.0 402 Payment Required\r\n" |
| 5445 |
b"\r\n") |
| 5446 |
conn_to_client.close() # RST |
| 5447 |
server_responding.set() |
| 5448 |
return True # Tell the server to stop. |
| 5449 |
|
| 5450 |
timeout = 2.0 |
| 5451 |
server = self.SingleConnectionTestServerThread( |
| 5452 |
call_after_accept=call_after_accept, |
| 5453 |
name="non_tls_http_RST_responder", |
| 5454 |
timeout=timeout) |
| 5455 |
self.enterContext(server) # starts it & unittest.TestCase stops it. |
| 5456 |
# Redundant; call_after_accept sets SO_LINGER on the accepted conn. |
| 5457 |
set_socket_so_linger_on_with_zero_timeout(server.listener) |
| 5458 |
|
| 5459 |
connection = SynchronizedHTTPSConnection( |
| 5460 |
server.listener.getsockname()[0], |
| 5461 |
port=server.port, |
| 5462 |
context=ssl.create_default_context(), |
| 5463 |
timeout=timeout, |
| 5464 |
) |
| 5465 |
|
| 5466 |
# There are lots of reasons this raises as desired, long before this |
| 5467 |
# test was added. Sending the request requires a successful TLS wrapped |
| 5468 |
# socket; that fails if the connection is broken. It may seem pointless |
| 5469 |
# to test this. It serves as an illustration of something that we never |
| 5470 |
# want to happen... properly not happening. |
| 5471 |
with warnings_helper.check_no_resource_warning(self), \ |
| 5472 |
self.assertRaises(OSError): |
| 5473 |
connection.request("HEAD", "/test", headers={"Host": "localhost"}) |
| 5474 |
response = connection.getresponse() |
| 5475 |
|
| 5476 |
server.join() |
| 5477 |
|
| 5478 |
|
| 5479 |
class TestEnumerations(unittest.TestCase): |
| 5480 |
|
| 5481 |
def test_tlsversion(self): |
| 5482 |
class CheckedTLSVersion(enum.IntEnum): |
| 5483 |
MINIMUM_SUPPORTED = _ssl.PROTO_MINIMUM_SUPPORTED |
| 5484 |
SSLv3 = _ssl.PROTO_SSLv3 |
| 5485 |
TLSv1 = _ssl.PROTO_TLSv1 |
| 5486 |
TLSv1_1 = _ssl.PROTO_TLSv1_1 |
| 5487 |
TLSv1_2 = _ssl.PROTO_TLSv1_2 |
| 5488 |
TLSv1_3 = _ssl.PROTO_TLSv1_3 |
| 5489 |
MAXIMUM_SUPPORTED = _ssl.PROTO_MAXIMUM_SUPPORTED |
| 5490 |
enum._test_simple_enum(CheckedTLSVersion, TLSVersion) |
| 5491 |
|
| 5492 |
def test_tlscontenttype(self): |
| 5493 |
class Checked_TLSContentType(enum.IntEnum): |
| 5494 |
"""Content types (record layer) |
| 5495 |
|
| 5496 |
See RFC 8446, section B.1 |
| 5497 |
""" |
| 5498 |
CHANGE_CIPHER_SPEC = 20 |
| 5499 |
ALERT = 21 |
| 5500 |
HANDSHAKE = 22 |
| 5501 |
APPLICATION_DATA = 23 |
| 5502 |
# pseudo content types |
| 5503 |
HEADER = 0x100 |
| 5504 |
INNER_CONTENT_TYPE = 0x101 |
| 5505 |
enum._test_simple_enum(Checked_TLSContentType, _TLSContentType) |
| 5506 |
|
| 5507 |
def test_tlsalerttype(self): |
| 5508 |
class Checked_TLSAlertType(enum.IntEnum): |
| 5509 |
"""Alert types for TLSContentType.ALERT messages |
| 5510 |
|
| 5511 |
See RFC 8446, section B.2 |
| 5512 |
""" |
| 5513 |
CLOSE_NOTIFY = 0 |
| 5514 |
UNEXPECTED_MESSAGE = 10 |
| 5515 |
BAD_RECORD_MAC = 20 |
| 5516 |
DECRYPTION_FAILED = 21 |
| 5517 |
RECORD_OVERFLOW = 22 |
| 5518 |
DECOMPRESSION_FAILURE = 30 |
| 5519 |
HANDSHAKE_FAILURE = 40 |
| 5520 |
NO_CERTIFICATE = 41 |
| 5521 |
BAD_CERTIFICATE = 42 |
| 5522 |
UNSUPPORTED_CERTIFICATE = 43 |
| 5523 |
CERTIFICATE_REVOKED = 44 |
| 5524 |
CERTIFICATE_EXPIRED = 45 |
| 5525 |
CERTIFICATE_UNKNOWN = 46 |
| 5526 |
ILLEGAL_PARAMETER = 47 |
| 5527 |
UNKNOWN_CA = 48 |
| 5528 |
ACCESS_DENIED = 49 |
| 5529 |
DECODE_ERROR = 50 |
| 5530 |
DECRYPT_ERROR = 51 |
| 5531 |
EXPORT_RESTRICTION = 60 |
| 5532 |
PROTOCOL_VERSION = 70 |
| 5533 |
INSUFFICIENT_SECURITY = 71 |
| 5534 |
INTERNAL_ERROR = 80 |
| 5535 |
INAPPROPRIATE_FALLBACK = 86 |
| 5536 |
USER_CANCELED = 90 |
| 5537 |
NO_RENEGOTIATION = 100 |
| 5538 |
MISSING_EXTENSION = 109 |
| 5539 |
UNSUPPORTED_EXTENSION = 110 |
| 5540 |
CERTIFICATE_UNOBTAINABLE = 111 |
| 5541 |
UNRECOGNIZED_NAME = 112 |
| 5542 |
BAD_CERTIFICATE_STATUS_RESPONSE = 113 |
| 5543 |
BAD_CERTIFICATE_HASH_VALUE = 114 |
| 5544 |
UNKNOWN_PSK_IDENTITY = 115 |
| 5545 |
CERTIFICATE_REQUIRED = 116 |
| 5546 |
NO_APPLICATION_PROTOCOL = 120 |
| 5547 |
enum._test_simple_enum(Checked_TLSAlertType, _TLSAlertType) |
| 5548 |
|
| 5549 |
def test_tlsmessagetype(self): |
| 5550 |
class Checked_TLSMessageType(enum.IntEnum): |
| 5551 |
"""Message types (handshake protocol) |
| 5552 |
|
| 5553 |
See RFC 8446, section B.3 |
| 5554 |
""" |
| 5555 |
HELLO_REQUEST = 0 |
| 5556 |
CLIENT_HELLO = 1 |
| 5557 |
SERVER_HELLO = 2 |
| 5558 |
HELLO_VERIFY_REQUEST = 3 |
| 5559 |
NEWSESSION_TICKET = 4 |
| 5560 |
END_OF_EARLY_DATA = 5 |
| 5561 |
HELLO_RETRY_REQUEST = 6 |
| 5562 |
ENCRYPTED_EXTENSIONS = 8 |
| 5563 |
CERTIFICATE = 11 |
| 5564 |
SERVER_KEY_EXCHANGE = 12 |
| 5565 |
CERTIFICATE_REQUEST = 13 |
| 5566 |
SERVER_DONE = 14 |
| 5567 |
CERTIFICATE_VERIFY = 15 |
| 5568 |
CLIENT_KEY_EXCHANGE = 16 |
| 5569 |
FINISHED = 20 |
| 5570 |
CERTIFICATE_URL = 21 |
| 5571 |
CERTIFICATE_STATUS = 22 |
| 5572 |
SUPPLEMENTAL_DATA = 23 |
| 5573 |
KEY_UPDATE = 24 |
| 5574 |
NEXT_PROTO = 67 |
| 5575 |
MESSAGE_HASH = 254 |
| 5576 |
CHANGE_CIPHER_SPEC = 0x0101 |
| 5577 |
enum._test_simple_enum(Checked_TLSMessageType, _TLSMessageType) |
| 5578 |
|
| 5579 |
def test_sslmethod(self): |
| 5580 |
Checked_SSLMethod = enum._old_convert_( |
| 5581 |
enum.IntEnum, '_SSLMethod', 'ssl', |
| 5582 |
lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23', |
| 5583 |
source=ssl._ssl, |
| 5584 |
) |
| 5585 |
# This member is assigned dynamically in `ssl.py`: |
| 5586 |
Checked_SSLMethod.PROTOCOL_SSLv23 = Checked_SSLMethod.PROTOCOL_TLS |
| 5587 |
enum._test_simple_enum(Checked_SSLMethod, ssl._SSLMethod) |
| 5588 |
|
| 5589 |
def test_options(self): |
| 5590 |
CheckedOptions = enum._old_convert_( |
| 5591 |
enum.IntFlag, 'Options', 'ssl', |
| 5592 |
lambda name: name.startswith('OP_'), |
| 5593 |
source=ssl._ssl, |
| 5594 |
) |
| 5595 |
enum._test_simple_enum(CheckedOptions, ssl.Options) |
| 5596 |
|
| 5597 |
def test_alertdescription(self): |
| 5598 |
CheckedAlertDescription = enum._old_convert_( |
| 5599 |
enum.IntEnum, 'AlertDescription', 'ssl', |
| 5600 |
lambda name: name.startswith('ALERT_DESCRIPTION_'), |
| 5601 |
source=ssl._ssl, |
| 5602 |
) |
| 5603 |
enum._test_simple_enum(CheckedAlertDescription, ssl.AlertDescription) |
| 5604 |
|
| 5605 |
def test_sslerrornumber(self): |
| 5606 |
Checked_SSLErrorNumber = enum._old_convert_( |
| 5607 |
enum.IntEnum, 'SSLErrorNumber', 'ssl', |
| 5608 |
lambda name: name.startswith('SSL_ERROR_'), |
| 5609 |
source=ssl._ssl, |
| 5610 |
) |
| 5611 |
enum._test_simple_enum(Checked_SSLErrorNumber, ssl.SSLErrorNumber) |
| 5612 |
|
| 5613 |
def test_verifyflags(self): |
| 5614 |
CheckedVerifyFlags = enum._old_convert_( |
| 5615 |
enum.IntFlag, 'VerifyFlags', 'ssl', |
| 5616 |
lambda name: name.startswith('VERIFY_'), |
| 5617 |
source=ssl._ssl, |
| 5618 |
) |
| 5619 |
enum._test_simple_enum(CheckedVerifyFlags, ssl.VerifyFlags) |
| 5620 |
|
| 5621 |
def test_verifymode(self): |
| 5622 |
CheckedVerifyMode = enum._old_convert_( |
| 5623 |
enum.IntEnum, 'VerifyMode', 'ssl', |
| 5624 |
lambda name: name.startswith('CERT_'), |
| 5625 |
source=ssl._ssl, |
| 5626 |
) |
| 5627 |
enum._test_simple_enum(CheckedVerifyMode, ssl.VerifyMode) |
| 5628 |
|
| 5629 |
|
| 5630 |
def setUpModule(): |
| 5631 |
if support.verbose: |
| 5632 |
plats = { |
| 5633 |
'Mac': platform.mac_ver, |
| 5634 |
'Windows': platform.win32_ver, |
| 5635 |
} |
| 5636 |
for name, func in plats.items(): |
| 5637 |
plat = func() |
| 5638 |
if plat and plat[0]: |
| 5639 |
plat = '%s %r' % (name, plat) |
| 5640 |
break |
| 5641 |
else: |
| 5642 |
plat = repr(platform.platform()) |
| 5643 |
print("test_ssl: testing with %r %r" % |
| 5644 |
(ssl.OPENSSL_VERSION, ssl.OPENSSL_VERSION_INFO)) |
| 5645 |
print(" under %s" % plat) |
| 5646 |
print(" HAS_SNI = %r" % ssl.HAS_SNI) |
| 5647 |
print(" OP_ALL = 0x%8x" % ssl.OP_ALL) |
| 5648 |
try: |
| 5649 |
print(" OP_NO_TLSv1_1 = 0x%8x" % ssl.OP_NO_TLSv1_1) |
| 5650 |
except AttributeError: |
| 5651 |
pass |
| 5652 |
|
| 5653 |
for filename in [ |
| 5654 |
CERTFILE, BYTES_CERTFILE, |
| 5655 |
ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, |
| 5656 |
SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA, |
| 5657 |
BADCERT, BADKEY, EMPTYCERT]: |
| 5658 |
if not os.path.exists(filename): |
| 5659 |
raise support.TestFailed("Can't read certificate file %r" % filename) |
| 5660 |
|
| 5661 |
thread_info = threading_helper.threading_setup() |
| 5662 |
unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info) |
| 5663 |
|
| 5664 |
|
| 5665 |
if __name__ == "__main__": |
| 5666 |
unittest.main() |